3 * WordPress Post Administration API.
6 * @subpackage Administration
10 * Rename $_POST data from form names to DB post columns.
12 * Manipulates $_POST directly.
17 * @param bool $update Are we updating a pre-existing post?
18 * @param array $post_data Array of post data. Defaults to the contents of $_POST.
19 * @return object|bool WP_Error on failure, true on success.
21 function _wp_translate_postdata( $update = false, $post_data = null ) {
23 if ( empty($post_data) )
27 $post_data['ID'] = (int) $post_data['post_ID'];
29 if ( isset( $post_data['content'] ) )
30 $post_data['post_content'] = $post_data['content'];
32 if ( isset( $post_data['excerpt'] ) )
33 $post_data['post_excerpt'] = $post_data['excerpt'];
35 if ( isset( $post_data['parent_id'] ) )
36 $post_data['post_parent'] = (int) $post_data['parent_id'];
38 if ( isset($post_data['trackback_url']) )
39 $post_data['to_ping'] = $post_data['trackback_url'];
41 if ( !isset($post_data['user_ID']) )
42 $post_data['user_ID'] = $GLOBALS['user_ID'];
44 if (!empty ( $post_data['post_author_override'] ) ) {
45 $post_data['post_author'] = (int) $post_data['post_author_override'];
47 if (!empty ( $post_data['post_author'] ) ) {
48 $post_data['post_author'] = (int) $post_data['post_author'];
50 $post_data['post_author'] = (int) $post_data['user_ID'];
54 $ptype = get_post_type_object( $post_data['post_type'] );
55 if ( isset($post_data['user_ID']) && ($post_data['post_author'] != $post_data['user_ID']) ) {
56 if ( !current_user_can( $ptype->cap->edit_others_posts ) ) {
57 if ( 'page' == $post_data['post_type'] ) {
58 return new WP_Error( 'edit_others_pages', $update ?
59 __( 'You are not allowed to edit pages as this user.' ) :
60 __( 'You are not allowed to create pages as this user.' )
63 return new WP_Error( 'edit_others_posts', $update ?
64 __( 'You are not allowed to edit posts as this user.' ) :
65 __( 'You are not allowed to post as this user.' )
71 // What to do based on which button they pressed
72 if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] )
73 $post_data['post_status'] = 'draft';
74 if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] )
75 $post_data['post_status'] = 'private';
76 if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) )
77 $post_data['post_status'] = 'publish';
78 if ( isset($post_data['advanced']) && '' != $post_data['advanced'] )
79 $post_data['post_status'] = 'draft';
80 if ( isset($post_data['pending']) && '' != $post_data['pending'] )
81 $post_data['post_status'] = 'pending';
83 if ( isset( $post_data['ID'] ) )
84 $post_id = $post_data['ID'];
87 $previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;
89 // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
90 // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
91 if ( isset($post_data['post_status']) && ('publish' == $post_data['post_status'] && !current_user_can( $ptype->cap->publish_posts )) )
92 if ( $previous_status != 'publish' || !current_user_can( 'edit_post', $post_id ) )
93 $post_data['post_status'] = 'pending';
95 if ( ! isset($post_data['post_status']) )
96 $post_data['post_status'] = $previous_status;
98 if (!isset( $post_data['comment_status'] ))
99 $post_data['comment_status'] = 'closed';
101 if (!isset( $post_data['ping_status'] ))
102 $post_data['ping_status'] = 'closed';
104 foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
105 if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) {
106 $post_data['edit_date'] = '1';
111 if ( !empty( $post_data['edit_date'] ) ) {
112 $aa = $post_data['aa'];
113 $mm = $post_data['mm'];
114 $jj = $post_data['jj'];
115 $hh = $post_data['hh'];
116 $mn = $post_data['mn'];
117 $ss = $post_data['ss'];
118 $aa = ($aa <= 0 ) ? date('Y') : $aa;
119 $mm = ($mm <= 0 ) ? date('n') : $mm;
120 $jj = ($jj > 31 ) ? 31 : $jj;
121 $jj = ($jj <= 0 ) ? date('j') : $jj;
122 $hh = ($hh > 23 ) ? $hh -24 : $hh;
123 $mn = ($mn > 59 ) ? $mn -60 : $mn;
124 $ss = ($ss > 59 ) ? $ss -60 : $ss;
125 $post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
126 $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
133 * Update an existing post with values provided in $_POST.
137 * @param array $post_data Optional.
138 * @return int Post ID.
140 function edit_post( $post_data = null ) {
142 if ( empty($post_data) )
143 $post_data = &$_POST;
145 // Clear out any data in internal vars.
146 unset( $post_data['filter'] );
148 $post_ID = (int) $post_data['post_ID'];
149 $post = get_post( $post_ID );
150 $post_data['post_type'] = $post->post_type;
151 $post_data['post_mime_type'] = $post->post_mime_type;
153 $ptype = get_post_type_object($post_data['post_type']);
154 if ( !current_user_can( $ptype->cap->edit_post, $post_ID ) ) {
155 if ( 'page' == $post_data['post_type'] )
156 wp_die( __('You are not allowed to edit this page.' ));
158 wp_die( __('You are not allowed to edit this post.' ));
161 // Autosave shouldn't save too soon after a real save
162 if ( 'autosave' == $post_data['action'] ) {
163 $post =& get_post( $post_ID );
165 $then = strtotime($post->post_date_gmt . ' +0000');
166 $delta = AUTOSAVE_INTERVAL / 2;
167 if ( ($now - $then) < $delta )
171 $post_data = _wp_translate_postdata( true, $post_data );
172 if ( is_wp_error($post_data) )
173 wp_die( $post_data->get_error_message() );
174 if ( 'autosave' != $post_data['action'] && 'auto-draft' == $post_data['post_status'] )
175 $post_data['post_status'] = 'draft';
177 if ( isset($post_data['visibility']) ) {
178 switch ( $post_data['visibility'] ) {
180 $post_data['post_password'] = '';
183 unset( $post_data['sticky'] );
186 $post_data['post_status'] = 'private';
187 $post_data['post_password'] = '';
188 unset( $post_data['sticky'] );
194 if ( isset( $post_data['post_format'] ) ) {
195 if ( current_theme_supports( 'post-formats', $post_data['post_format'] ) )
196 set_post_format( $post_ID, $post_data['post_format'] );
197 elseif ( '0' == $post_data['post_format'] )
198 set_post_format( $post_ID, false );
202 if ( isset($post_data['meta']) && $post_data['meta'] ) {
203 foreach ( $post_data['meta'] as $key => $value ) {
204 if ( !$meta = get_post_meta_by_id( $key ) )
206 if ( $meta->post_id != $post_ID )
208 if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
210 update_meta( $key, $value['key'], $value['value'] );
214 if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
215 foreach ( $post_data['deletemeta'] as $key => $value ) {
216 if ( !$meta = get_post_meta_by_id( $key ) )
218 if ( $meta->post_id != $post_ID )
220 if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
226 add_meta( $post_ID );
228 update_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
230 wp_update_post( $post_data );
232 // Now that we have an ID we can fix any attachment anchor hrefs
233 _fix_attachment_links( $post_ID );
235 wp_set_post_lock( $post_ID );
237 if ( current_user_can( $ptype->cap->edit_others_posts ) ) {
238 if ( ! empty( $post_data['sticky'] ) )
239 stick_post( $post_ID );
241 unstick_post( $post_ID );
248 * Process the post data for the bulk editing of posts.
250 * Updates all bulk edited posts/pages, adding (but not removing) tags and
251 * categories. Skips pages when they would be their own parent or child.
255 * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
258 function bulk_edit_posts( $post_data = null ) {
261 if ( empty($post_data) )
262 $post_data = &$_POST;
264 if ( isset($post_data['post_type']) )
265 $ptype = get_post_type_object($post_data['post_type']);
267 $ptype = get_post_type_object('post');
269 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
270 if ( 'page' == $ptype->name )
271 wp_die( __('You are not allowed to edit pages.'));
273 wp_die( __('You are not allowed to edit posts.'));
276 if ( -1 == $post_data['_status'] ) {
277 $post_data['post_status'] = null;
278 unset($post_data['post_status']);
280 $post_data['post_status'] = $post_data['_status'];
282 unset($post_data['_status']);
284 $post_IDs = array_map( 'intval', (array) $post_data['post'] );
286 $reset = array( 'post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tax_input', 'post_category', 'sticky' );
287 foreach ( $reset as $field ) {
288 if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
289 unset($post_data[$field]);
292 if ( isset($post_data['post_category']) ) {
293 if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
294 $new_cats = array_map( 'absint', $post_data['post_category'] );
296 unset($post_data['post_category']);
299 $tax_input = array();
300 if ( isset($post_data['tax_input'])) {
301 foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
304 if ( is_taxonomy_hierarchical( $tax_name ) ) {
305 $tax_input[$tax_name] = array_map( 'absint', $terms );
307 $tax_input[$tax_name] = preg_replace( '/\s*,\s*/', ',', rtrim( trim($terms), ' ,' ) );
308 $tax_input[$tax_name] = explode(',', $tax_input[$tax_name]);
313 if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
314 $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
317 for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
318 $children[] = $parent;
320 foreach ( $pages as $page ) {
321 if ( $page->ID == $parent ) {
322 $parent = $page->post_parent;
329 if ( isset( $post_data['post_format'] ) ) {
330 if ( '0' == $post_data['post_format'] )
331 $post_data['post_format'] = false;
332 // don't change the post format if it's not supported or not '0' (standard)
333 elseif ( ! current_theme_supports( 'post-formats', $post_data['post_format'] ) )
334 unset( $post_data['post_format'] );
337 $updated = $skipped = $locked = array();
338 foreach ( $post_IDs as $post_ID ) {
339 $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
341 if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( $post_type_object->cap->edit_post, $post_ID ) ) {
342 $skipped[] = $post_ID;
346 if ( wp_check_post_lock( $post_ID ) ) {
347 $locked[] = $post_ID;
351 $post = get_post( $post_ID );
352 $tax_names = get_object_taxonomies( $post );
353 foreach ( $tax_names as $tax_name ) {
354 $taxonomy_obj = get_taxonomy($tax_name);
355 if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
356 $new_terms = $tax_input[$tax_name];
358 $new_terms = array();
360 if ( $taxonomy_obj->hierarchical )
361 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
363 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
365 $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
368 if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
369 $cats = (array) wp_get_post_categories($post_ID);
370 $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
371 unset( $post_data['tax_input']['category'] );
374 $post_data['post_mime_type'] = $post->post_mime_type;
375 $post_data['guid'] = $post->guid;
377 $post_data['ID'] = $post_ID;
378 $updated[] = wp_update_post( $post_data );
380 if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
381 if ( 'sticky' == $post_data['sticky'] )
382 stick_post( $post_ID );
384 unstick_post( $post_ID );
387 if ( isset( $post_data['post_format'] ) )
388 set_post_format( $post_ID, $post_data['post_format'] );
391 return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
395 * Default post information to use when populating the "Write Post" form.
399 * @param string $post_type A post type string, defaults to 'post'.
400 * @return object stdClass object containing all the default post data as attributes
402 function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
406 if ( !empty( $_REQUEST['post_title'] ) )
407 $post_title = esc_html( stripslashes( $_REQUEST['post_title'] ));
410 if ( !empty( $_REQUEST['content'] ) )
411 $post_content = esc_html( stripslashes( $_REQUEST['content'] ));
414 if ( !empty( $_REQUEST['excerpt'] ) )
415 $post_excerpt = esc_html( stripslashes( $_REQUEST['excerpt'] ));
417 if ( $create_in_db ) {
418 // Cleanup old auto-drafts more than 7 days old
419 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
420 foreach ( (array) $old_posts as $delete )
421 wp_delete_post( $delete, true ); // Force delete
422 $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
423 $post = get_post( $post_id );
424 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
425 set_post_format( $post, get_option( 'default_post_format' ) );
427 $post = new stdClass;
429 $post->post_author = '';
430 $post->post_date = '';
431 $post->post_date_gmt = '';
432 $post->post_password = '';
433 $post->post_type = $post_type;
434 $post->post_status = 'draft';
437 $post->comment_status = get_option( 'default_comment_status' );
438 $post->ping_status = get_option( 'default_ping_status' );
439 $post->post_pingback = get_option( 'default_pingback_flag' );
440 $post->post_category = get_option( 'default_category' );
441 $post->page_template = 'default';
442 $post->post_parent = 0;
443 $post->menu_order = 0;
446 $post->post_content = apply_filters( 'default_content', $post_content, $post );
447 $post->post_title = apply_filters( 'default_title', $post_title, $post );
448 $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
449 $post->post_name = '';
455 * Get the default page information to use.
459 * @return object stdClass object containing all the default post data as attributes
461 function get_default_page_to_edit() {
462 $page = get_default_post_to_edit();
463 $page->post_type = 'page';
468 * Get an existing post and format it for editing.
472 * @param unknown_type $id
475 function get_post_to_edit( $id ) {
477 $post = get_post( $id, OBJECT, 'edit' );
479 if ( $post->post_type == 'page' )
480 $post->page_template = get_post_meta( $id, '_wp_page_template', true );
486 * Determine if a post exists based on title, content, and date
490 * @param string $title Post title
491 * @param string $content Optional post content
492 * @param string $date Optional post date
493 * @return int Post ID if post exists, 0 otherwise.
495 function post_exists($title, $content = '', $date = '') {
498 $post_title = stripslashes( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
499 $post_content = stripslashes( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
500 $post_date = stripslashes( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
502 $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
505 if ( !empty ( $date ) ) {
506 $query .= ' AND post_date = %s';
507 $args[] = $post_date;
510 if ( !empty ( $title ) ) {
511 $query .= ' AND post_title = %s';
512 $args[] = $post_title;
515 if ( !empty ( $content ) ) {
516 $query .= 'AND post_content = %s';
517 $args[] = $post_content;
520 if ( !empty ( $args ) )
521 return $wpdb->get_var( $wpdb->prepare($query, $args) );
527 * Creates a new post from the "Write Post" form using $_POST information.
533 function wp_write_post() {
536 if ( isset($_POST['post_type']) )
537 $ptype = get_post_type_object($_POST['post_type']);
539 $ptype = get_post_type_object('post');
541 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
542 if ( 'page' == $ptype->name )
543 return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this site.' ) );
545 return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this site.' ) );
548 $_POST['post_mime_type'] = '';
550 // Clear out any data in internal vars.
551 unset( $_POST['filter'] );
553 // Edit don't write if we have a post id.
554 if ( isset( $_POST['post_ID'] ) )
557 $translated = _wp_translate_postdata( false );
558 if ( is_wp_error($translated) )
561 if ( isset($_POST['visibility']) ) {
562 switch ( $_POST['visibility'] ) {
564 $_POST['post_password'] = '';
567 unset( $_POST['sticky'] );
570 $_POST['post_status'] = 'private';
571 $_POST['post_password'] = '';
572 unset( $_POST['sticky'] );
578 $post_ID = wp_insert_post( $_POST );
579 if ( is_wp_error( $post_ID ) )
582 if ( empty($post_ID) )
585 add_meta( $post_ID );
587 add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
589 // Now that we have an ID we can fix any attachment anchor hrefs
590 _fix_attachment_links( $post_ID );
592 wp_set_post_lock( $post_ID );
598 * Calls wp_write_post() and handles the errors.
602 * @uses wp_write_post()
603 * @uses is_wp_error()
607 function write_post() {
608 $result = wp_write_post();
609 if ( is_wp_error( $result ) )
610 wp_die( $result->get_error_message() );
620 * {@internal Missing Short Description}}
624 * @param unknown_type $post_ID
627 function add_meta( $post_ID ) {
629 $post_ID = (int) $post_ID;
631 $metakeyselect = isset($_POST['metakeyselect']) ? stripslashes( trim( $_POST['metakeyselect'] ) ) : '';
632 $metakeyinput = isset($_POST['metakeyinput']) ? stripslashes( trim( $_POST['metakeyinput'] ) ) : '';
633 $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
634 if ( is_string( $metavalue ) )
635 $metavalue = trim( $metavalue );
637 if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
638 // We have a key/value pair. If both the select and the
639 // input for the key have data, the input takes precedence:
641 if ( '#NONE#' != $metakeyselect )
642 $metakey = $metakeyselect;
645 $metakey = $metakeyinput; // default
647 if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
650 $metakey = esc_sql( $metakey );
652 return add_post_meta( $post_ID, $metakey, $metavalue );
659 * {@internal Missing Short Description}}
663 * @param unknown_type $mid
666 function delete_meta( $mid ) {
667 return delete_metadata_by_mid( 'post' , $mid );
671 * Get a list of previously defined keys.
677 function get_meta_keys() {
680 $keys = $wpdb->get_col( "
684 ORDER BY meta_key" );
690 * {@internal Missing Short Description}}
694 * @param unknown_type $mid
697 function get_post_meta_by_id( $mid ) {
698 return get_metadata_by_mid( 'post', $mid );
702 * {@internal Missing Short Description}}
704 * Some postmeta stuff.
708 * @param unknown_type $postid
711 function has_meta( $postid ) {
714 return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
715 FROM $wpdb->postmeta WHERE post_id = %d
716 ORDER BY meta_key,meta_id", $postid), ARRAY_A );
720 * {@internal Missing Short Description}}
724 * @param unknown_type $meta_id
725 * @param unknown_type $meta_key Expect Slashed
726 * @param unknown_type $meta_value Expect Slashed
729 function update_meta( $meta_id, $meta_key, $meta_value ) {
730 $meta_key = stripslashes( $meta_key );
731 $meta_value = stripslashes_deep( $meta_value );
733 return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
741 * Replace hrefs of attachment anchors with up-to-date permalinks.
746 * @param unknown_type $post_ID
749 function _fix_attachment_links( $post_ID ) {
750 global $_fix_attachment_link_id;
752 $post = & get_post( $post_ID, ARRAY_A );
754 $search = "#<a[^>]+rel=('|\")[^'\"]*attachment[^>]*>#ie";
756 // See if we have any rel="attachment" links
757 if ( 0 == preg_match_all( $search, $post['post_content'], $anchor_matches, PREG_PATTERN_ORDER ) )
761 $search = "#[\s]+rel=(\"|')(.*?)wp-att-(\d+)\\1#i";
762 foreach ( $anchor_matches[0] as $anchor ) {
763 if ( 0 == preg_match( $search, $anchor, $id_matches ) )
766 $id = (int) $id_matches[3];
768 // While we have the attachment ID, let's adopt any orphans.
769 $attachment = & get_post( $id, ARRAY_A );
770 if ( ! empty( $attachment) && ! is_object( get_post( $attachment['post_parent'] ) ) ) {
771 $attachment['post_parent'] = $post_ID;
772 // Escape data pulled from DB.
773 $attachment = add_magic_quotes( $attachment );
774 wp_update_post( $attachment );
777 $post_search[$i] = $anchor;
778 $_fix_attachment_link_id = $id;
779 $post_replace[$i] = preg_replace_callback( "#href=(\"|')[^'\"]*\\1#", '_fix_attachment_links_replace_cb', $anchor );
783 $post['post_content'] = str_replace( $post_search, $post_replace, $post['post_content'] );
785 // Escape data pulled from DB.
786 $post = add_magic_quotes( $post);
788 return wp_update_post( $post);
791 function _fix_attachment_links_replace_cb($match) {
792 global $_fix_attachment_link_id;
793 return stripslashes( 'href='.$match[1] ).get_attachment_link( $_fix_attachment_link_id ).stripslashes( $match[1] );
797 * Move child posts to a new parent.
802 * @param unknown_type $old_ID
803 * @param unknown_type $new_ID
806 function _relocate_children( $old_ID, $new_ID ) {
808 $old_ID = (int) $old_ID;
809 $new_ID = (int) $new_ID;
811 $children = $wpdb->get_col( $wpdb->prepare("
814 WHERE meta_key = '_wp_attachment_temp_parent'
815 AND meta_value = %d", $old_ID) );
817 foreach ( $children as $child_id ) {
818 $wpdb->update($wpdb->posts, array('post_parent' => $new_ID), array('ID' => $child_id) );
819 delete_post_meta($child_id, '_wp_attachment_temp_parent');
824 * Get all the possible statuses for a post_type
828 * @param string $type The post_type you want the statuses for
829 * @return array As array of all the statuses for the supplied post type
831 function get_available_post_statuses($type = 'post') {
832 $stati = wp_count_posts($type);
834 return array_keys(get_object_vars($stati));
838 * Run the wp query to fetch the posts for listing on the edit posts page
842 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
845 function wp_edit_posts_query( $q = false ) {
848 $q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
849 $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
850 $post_stati = get_post_stati();
852 if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
853 $post_type = $q['post_type'];
857 $avail_post_stati = get_available_post_statuses($post_type);
859 if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
860 $post_status = $q['post_status'];
864 if ( isset($q['orderby']) )
865 $orderby = $q['orderby'];
866 elseif ( isset($q['post_status']) && in_array($q['post_status'], array('pending', 'draft')) )
867 $orderby = 'modified';
869 if ( isset($q['order']) )
870 $order = $q['order'];
871 elseif ( isset($q['post_status']) && 'pending' == $q['post_status'] )
874 $per_page = 'edit_' . $post_type . '_per_page';
875 $posts_per_page = (int) get_user_option( $per_page );
876 if ( empty( $posts_per_page ) || $posts_per_page < 1 )
877 $posts_per_page = 20;
879 $posts_per_page = apply_filters( $per_page, $posts_per_page );
880 $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
882 $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
884 // Hierarchical types require special args.
885 if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
886 $query['orderby'] = 'menu_order title';
887 $query['order'] = 'asc';
888 $query['posts_per_page'] = -1;
889 $query['posts_per_archive_page'] = -1;
892 if ( ! empty( $q['show_sticky'] ) )
893 $query['post__in'] = (array) get_option( 'sticky_posts' );
897 return $avail_post_stati;
901 * Get default post mime types
907 function get_post_mime_types() {
908 $post_mime_types = array( // array( adj, noun )
909 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
910 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
911 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
914 return apply_filters('post_mime_types', $post_mime_types);
918 * {@internal Missing Short Description}}
922 * @param unknown_type $type
925 function get_available_post_mime_types($type = 'attachment') {
928 $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
933 * {@internal Missing Short Description}}
937 * @param unknown_type $q
940 function wp_edit_attachments_query( $q = false ) {
944 $q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0;
945 $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
946 $q['post_type'] = 'attachment';
947 $post_type = get_post_type_object( 'attachment' );
949 if ( current_user_can( $post_type->cap->read_private_posts ) )
950 $states .= ',private';
952 $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
953 $media_per_page = (int) get_user_option( 'upload_per_page' );
954 if ( empty( $media_per_page ) || $media_per_page < 1 )
955 $media_per_page = 20;
956 $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
958 $post_mime_types = get_post_mime_types();
959 $avail_post_mime_types = get_available_post_mime_types('attachment');
961 if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) )
962 unset($q['post_mime_type']);
964 if ( isset($q['detached']) )
965 add_filter('posts_where', '_edit_attachments_query_helper');
969 if ( isset($q['detached']) )
970 remove_filter('posts_where', '_edit_attachments_query_helper');
972 return array($post_mime_types, $avail_post_mime_types);
975 function _edit_attachments_query_helper($where) {
976 return $where .= ' AND post_parent < 1';
980 * Returns the list of classes to be used by a metabox
982 * @uses get_user_option()
985 * @param unknown_type $id
986 * @param unknown_type $page
989 function postbox_classes( $id, $page ) {
990 if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
991 $classes = array( '' );
992 } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
993 if ( !is_array( $closed ) ) {
994 $classes = array( '' );
996 $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
999 $classes = array( '' );
1002 $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
1003 return implode( ' ', $classes );
1007 * {@internal Missing Short Description}}
1011 * @param int|object $id Post ID or post object.
1012 * @param string $title (optional) Title
1013 * @param string $name (optional) Name
1014 * @return array With two entries of type string
1016 function get_sample_permalink($id, $title = null, $name = null) {
1017 $post = &get_post($id);
1019 return array('', '');
1021 $ptype = get_post_type_object($post->post_type);
1023 $original_status = $post->post_status;
1024 $original_date = $post->post_date;
1025 $original_name = $post->post_name;
1027 // Hack: get_permalink would return ugly permalink for
1028 // drafts, so we will fake, that our post is published
1029 if ( in_array($post->post_status, array('draft', 'pending')) ) {
1030 $post->post_status = 'publish';
1031 $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
1034 // If the user wants to set a new name -- override the current one
1035 // Note: if empty name is supplied -- use the title instead, see #6072
1036 if ( !is_null($name) )
1037 $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
1039 $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
1041 $post->filter = 'sample';
1043 $permalink = get_permalink($post, true);
1045 // Replace custom post_type Token with generic pagename token for ease of use.
1046 $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
1048 // Handle page hierarchy
1049 if ( $ptype->hierarchical ) {
1050 $uri = get_page_uri($post);
1051 $uri = untrailingslashit($uri);
1052 $uri = strrev( stristr( strrev( $uri ), '/' ) );
1053 $uri = untrailingslashit($uri);
1054 $uri = apply_filters( 'editable_slug', $uri );
1057 $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
1060 $permalink = array($permalink, apply_filters('editable_slug', $post->post_name));
1061 $post->post_status = $original_status;
1062 $post->post_date = $original_date;
1063 $post->post_name = $original_name;
1064 unset($post->filter);
1070 * sample permalink html
1072 * intended to be used for the inplace editor of the permalink post slug on in the post (and page?) editor.
1076 * @param int|object $id Post ID or post object.
1077 * @param string $new_title (optional) New title
1078 * @param string $new_slug (optional) New slug
1079 * @return string intended to be used for the inplace editor of the permalink post slug on in the post (and page?) editor.
1081 function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1083 $post = &get_post($id);
1085 list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
1087 if ( 'publish' == $post->post_status ) {
1088 $ptype = get_post_type_object($post->post_type);
1089 $view_post = $ptype->labels->view_item;
1090 $title = __('Click to edit this part of the permalink');
1092 $title = __('Temporary permalink. Click to edit this part.');
1095 if ( false === strpos($permalink, '%postname%') && false === strpos($permalink, '%pagename%') ) {
1096 $return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink">' . $permalink . "</span>\n";
1097 if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) )
1098 $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
1099 if ( isset($view_post) )
1100 $return .= "<span id='view-post-btn'><a href='$permalink' class='button' target='_blank'>$view_post</a></span>\n";
1102 $return = apply_filters('get_sample_permalink_html', $return, $id, $new_title, $new_slug);
1107 if ( function_exists('mb_strlen') ) {
1108 if ( mb_strlen($post_name) > 30 ) {
1109 $post_name_abridged = mb_substr($post_name, 0, 14). '…' . mb_substr($post_name, -14);
1111 $post_name_abridged = $post_name;
1114 if ( strlen($post_name) > 30 ) {
1115 $post_name_abridged = substr($post_name, 0, 14). '…' . substr($post_name, -14);
1117 $post_name_abridged = $post_name;
1121 $post_name_html = '<span id="editable-post-name" title="' . $title . '">' . $post_name_abridged . '</span>';
1122 $display_link = str_replace(array('%pagename%','%postname%'), $post_name_html, $permalink);
1123 $view_link = str_replace(array('%pagename%','%postname%'), $post_name, $permalink);
1124 $return = '<strong>' . __('Permalink:') . "</strong>\n";
1125 $return .= '<span id="sample-permalink">' . $display_link . "</span>\n";
1126 $return .= '‎'; // Fix bi-directional text display defect in RTL languages.
1127 $return .= '<span id="edit-slug-buttons"><a href="#post_name" class="edit-slug button hide-if-no-js" onclick="editPermalink(' . $id . '); return false;">' . __('Edit') . "</a></span>\n";
1128 $return .= '<span id="editable-post-name-full">' . $post_name . "</span>\n";
1129 if ( isset($view_post) )
1130 $return .= "<span id='view-post-btn'><a href='$view_link' class='button' target='_blank'>$view_post</a></span>\n";
1132 $return = apply_filters('get_sample_permalink_html', $return, $id, $new_title, $new_slug);
1138 * Output HTML for the post thumbnail meta-box.
1142 * @param int $thumbnail_id ID of the attachment used for thumbnail
1143 * @return string html
1145 function _wp_post_thumbnail_html( $thumbnail_id = NULL ) {
1146 global $content_width, $_wp_additional_image_sizes, $post_ID;
1147 $set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="' . esc_url( get_upload_iframe_src('image') ) . '" id="set-post-thumbnail" class="thickbox">%s</a></p>';
1148 $content = sprintf($set_thumbnail_link, esc_html__( 'Set featured image' ));
1150 if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1151 $old_content_width = $content_width;
1152 $content_width = 266;
1153 if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) )
1154 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
1156 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' );
1157 if ( !empty( $thumbnail_html ) ) {
1158 $ajax_nonce = wp_create_nonce( "set_post_thumbnail-$post_ID" );
1159 $content = sprintf($set_thumbnail_link, $thumbnail_html);
1160 $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail" onclick="WPRemoveThumbnail(\'' . $ajax_nonce . '\');return false;">' . esc_html__( 'Remove featured image' ) . '</a></p>';
1162 $content_width = $old_content_width;
1165 return apply_filters( 'admin_post_thumbnail_html', $content );
1169 * Check to see if the post is currently being edited by another user.
1173 * @param int $post_id ID of the post to check for editing
1174 * @return bool|int False: not locked or locked by current user. Int: user ID of user with lock.
1176 function wp_check_post_lock( $post_id ) {
1177 if ( !$post = get_post( $post_id ) )
1180 if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) )
1183 $lock = explode( ':', $lock );
1185 $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1187 $time_window = apply_filters( 'wp_check_post_lock_window', AUTOSAVE_INTERVAL * 2 );
1189 if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
1195 * Mark the post as currently being edited by the current user
1199 * @param int $post_id ID of the post to being edited
1200 * @return bool|array Returns false if the post doesn't exist of there is no current user, or
1201 * an array of the lock time and the user ID.
1203 function wp_set_post_lock( $post_id ) {
1204 if ( !$post = get_post( $post_id ) )
1206 if ( 0 == ($user_id = get_current_user_id()) )
1210 $lock = "$now:$user_id";
1212 update_post_meta( $post->ID, '_edit_lock', $lock );
1213 return array( $now, $user_id );
1217 * Outputs the notice message to say that someone else is editing this post at the moment.
1222 function _admin_notice_post_locked() {
1225 $lock = explode( ':', get_post_meta( $post->ID, '_edit_lock', true ) );
1226 $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1227 $last_user = get_userdata( $user );
1228 $last_user_name = $last_user ? $last_user->display_name : __('Somebody');
1230 switch ($post->post_type) {
1232 $message = __( 'Warning: %s is currently editing this post' );
1235 $message = __( 'Warning: %s is currently editing this page' );
1238 $message = __( 'Warning: %s is currently editing this.' );
1241 $message = sprintf( $message, esc_html( $last_user_name ) );
1242 echo "<div class='error'><p>$message</p></div>";
1246 * Creates autosave data for the specified post from $_POST data.
1248 * @package WordPress
1249 * @subpackage Post_Revisions
1252 * @uses _wp_translate_postdata()
1253 * @uses _wp_post_revision_fields()
1257 function wp_create_post_autosave( $post_id ) {
1258 $translated = _wp_translate_postdata( true );
1259 if ( is_wp_error( $translated ) )
1262 // Only store one autosave. If there is already an autosave, overwrite it.
1263 if ( $old_autosave = wp_get_post_autosave( $post_id ) ) {
1264 $new_autosave = _wp_post_revision_fields( $_POST, true );
1265 $new_autosave['ID'] = $old_autosave->ID;
1266 $new_autosave['post_author'] = get_current_user_id();
1267 return wp_update_post( $new_autosave );
1270 // _wp_put_post_revision() expects unescaped.
1271 $_POST = stripslashes_deep($_POST);
1273 // Otherwise create the new autosave as a special post revision
1274 return _wp_put_post_revision( $_POST, true );
1278 * Save draft or manually autosave for showing preview.
1280 * @package WordPress
1283 * @uses get_post_status()
1286 * @uses current_user_can()
1288 * @uses wp_create_post_autosave()
1289 * @uses add_query_arg()
1290 * @uses wp_create_nonce()
1292 * @return str URL to redirect to show the preview
1294 function post_preview() {
1296 $post_ID = (int) $_POST['post_ID'];
1297 $status = get_post_status( $post_ID );
1298 if ( 'auto-draft' == $status )
1299 wp_die( __('Preview not available. Please save as a draft first.') );
1301 if ( isset($_POST['catslist']) )
1302 $_POST['post_category'] = explode(",", $_POST['catslist']);
1304 if ( isset($_POST['tags_input']) )
1305 $_POST['tags_input'] = explode(",", $_POST['tags_input']);
1307 if ( $_POST['post_type'] == 'page' || empty($_POST['post_category']) )
1308 unset($_POST['post_category']);
1310 $_POST['ID'] = $post_ID;
1311 $post = get_post($post_ID);
1313 if ( 'page' == $post->post_type ) {
1314 if ( !current_user_can('edit_page', $post_ID) )
1315 wp_die(__('You are not allowed to edit this page.'));
1317 if ( !current_user_can('edit_post', $post_ID) )
1318 wp_die(__('You are not allowed to edit this post.'));
1321 if ( 'draft' == $post->post_status ) {
1323 } else { // Non drafts are not overwritten. The autosave is stored in a special post revision.
1324 $id = wp_create_post_autosave( $post->ID );
1325 if ( ! is_wp_error($id) )
1329 if ( is_wp_error($id) )
1330 wp_die( $id->get_error_message() );
1332 if ( $_POST['post_status'] == 'draft' ) {
1333 $url = add_query_arg( 'preview', 'true', get_permalink($id) );
1335 $nonce = wp_create_nonce('post_preview_' . $id);
1336 $url = add_query_arg( array( 'preview' => 'true', 'preview_id' => $id, 'preview_nonce' => $nonce ), get_permalink($id) );