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 $ptype = get_post_type_object( $post_data['post_type'] );
31 if ( $update && ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
32 if ( 'page' == $post_data['post_type'] )
33 return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) );
35 return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) );
36 } elseif ( ! $update && ! current_user_can( $ptype->cap->create_posts ) ) {
37 if ( 'page' == $post_data['post_type'] )
38 return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
40 return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
43 if ( isset( $post_data['content'] ) )
44 $post_data['post_content'] = $post_data['content'];
46 if ( isset( $post_data['excerpt'] ) )
47 $post_data['post_excerpt'] = $post_data['excerpt'];
49 if ( isset( $post_data['parent_id'] ) )
50 $post_data['post_parent'] = (int) $post_data['parent_id'];
52 if ( isset($post_data['trackback_url']) )
53 $post_data['to_ping'] = $post_data['trackback_url'];
55 $post_data['user_ID'] = get_current_user_id();
57 if (!empty ( $post_data['post_author_override'] ) ) {
58 $post_data['post_author'] = (int) $post_data['post_author_override'];
60 if (!empty ( $post_data['post_author'] ) ) {
61 $post_data['post_author'] = (int) $post_data['post_author'];
63 $post_data['post_author'] = (int) $post_data['user_ID'];
67 if ( isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] )
68 && ! current_user_can( $ptype->cap->edit_others_posts ) ) {
70 if ( 'page' == $post_data['post_type'] )
71 return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) );
73 return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) );
75 if ( 'page' == $post_data['post_type'] )
76 return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
78 return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
82 if ( ! empty( $post_data['post_status'] ) ) {
83 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
85 // No longer an auto-draft
86 if ( 'auto-draft' === $post_data['post_status'] ) {
87 $post_data['post_status'] = 'draft';
90 if ( ! get_post_status_object( $post_data['post_status'] ) ) {
91 unset( $post_data['post_status'] );
95 // What to do based on which button they pressed
96 if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] )
97 $post_data['post_status'] = 'draft';
98 if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] )
99 $post_data['post_status'] = 'private';
100 if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) )
101 $post_data['post_status'] = 'publish';
102 if ( isset($post_data['advanced']) && '' != $post_data['advanced'] )
103 $post_data['post_status'] = 'draft';
104 if ( isset($post_data['pending']) && '' != $post_data['pending'] )
105 $post_data['post_status'] = 'pending';
107 if ( isset( $post_data['ID'] ) )
108 $post_id = $post_data['ID'];
111 $previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;
113 if ( isset( $post_data['post_status'] ) && 'private' == $post_data['post_status'] && ! current_user_can( $ptype->cap->publish_posts ) ) {
114 $post_data['post_status'] = $previous_status ? $previous_status : 'pending';
117 $published_statuses = array( 'publish', 'future' );
119 // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
120 // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
121 if ( isset($post_data['post_status']) && (in_array( $post_data['post_status'], $published_statuses ) && !current_user_can( $ptype->cap->publish_posts )) )
122 if ( ! in_array( $previous_status, $published_statuses ) || !current_user_can( 'edit_post', $post_id ) )
123 $post_data['post_status'] = 'pending';
125 if ( ! isset( $post_data['post_status'] ) ) {
126 $post_data['post_status'] = 'auto-draft' === $previous_status ? 'draft' : $previous_status;
129 if ( isset( $post_data['post_password'] ) && ! current_user_can( $ptype->cap->publish_posts ) ) {
130 unset( $post_data['post_password'] );
133 if (!isset( $post_data['comment_status'] ))
134 $post_data['comment_status'] = 'closed';
136 if (!isset( $post_data['ping_status'] ))
137 $post_data['ping_status'] = 'closed';
139 foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
140 if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) {
141 $post_data['edit_date'] = '1';
146 if ( !empty( $post_data['edit_date'] ) ) {
147 $aa = $post_data['aa'];
148 $mm = $post_data['mm'];
149 $jj = $post_data['jj'];
150 $hh = $post_data['hh'];
151 $mn = $post_data['mn'];
152 $ss = $post_data['ss'];
153 $aa = ($aa <= 0 ) ? date('Y') : $aa;
154 $mm = ($mm <= 0 ) ? date('n') : $mm;
155 $jj = ($jj > 31 ) ? 31 : $jj;
156 $jj = ($jj <= 0 ) ? date('j') : $jj;
157 $hh = ($hh > 23 ) ? $hh -24 : $hh;
158 $mn = ($mn > 59 ) ? $mn -60 : $mn;
159 $ss = ($ss > 59 ) ? $ss -60 : $ss;
160 $post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
161 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] );
162 if ( !$valid_date ) {
163 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
165 $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
172 * Update an existing post with values provided in $_POST.
176 * @param array $post_data Optional.
177 * @return int Post ID.
179 function edit_post( $post_data = null ) {
181 if ( empty($post_data) )
182 $post_data = &$_POST;
184 // Clear out any data in internal vars.
185 unset( $post_data['filter'] );
187 $post_ID = (int) $post_data['post_ID'];
188 $post = get_post( $post_ID );
189 $post_data['post_type'] = $post->post_type;
190 $post_data['post_mime_type'] = $post->post_mime_type;
192 if ( ! empty( $post_data['post_status'] ) ) {
193 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
195 if ( 'inherit' == $post_data['post_status'] ) {
196 unset( $post_data['post_status'] );
200 $ptype = get_post_type_object($post_data['post_type']);
201 if ( !current_user_can( 'edit_post', $post_ID ) ) {
202 if ( 'page' == $post_data['post_type'] )
203 wp_die( __('You are not allowed to edit this page.' ));
205 wp_die( __('You are not allowed to edit this post.' ));
208 if ( post_type_supports( $ptype->name, 'revisions' ) ) {
209 $revisions = wp_get_post_revisions( $post_ID, array( 'order' => 'ASC', 'posts_per_page' => 1 ) );
210 $revision = current( $revisions );
212 // Check if the revisions have been upgraded
213 if ( $revisions && _wp_get_post_revision_version( $revision ) < 1 )
214 _wp_upgrade_revisions_of_post( $post, wp_get_post_revisions( $post_ID ) );
217 if ( isset($post_data['visibility']) ) {
218 switch ( $post_data['visibility'] ) {
220 $post_data['post_password'] = '';
223 unset( $post_data['sticky'] );
226 $post_data['post_status'] = 'private';
227 $post_data['post_password'] = '';
228 unset( $post_data['sticky'] );
233 $post_data = _wp_translate_postdata( true, $post_data );
234 if ( is_wp_error($post_data) )
235 wp_die( $post_data->get_error_message() );
238 if ( isset( $post_data['post_format'] ) )
239 set_post_format( $post_ID, $post_data['post_format'] );
241 $format_meta_urls = array( 'url', 'link_url', 'quote_source_url' );
242 foreach ( $format_meta_urls as $format_meta_url ) {
243 $keyed = '_format_' . $format_meta_url;
244 if ( isset( $post_data[ $keyed ] ) )
245 update_post_meta( $post_ID, $keyed, wp_slash( esc_url_raw( wp_unslash( $post_data[ $keyed ] ) ) ) );
248 $format_keys = array( 'quote', 'quote_source_name', 'image', 'gallery', 'audio_embed', 'video_embed' );
250 foreach ( $format_keys as $key ) {
251 $keyed = '_format_' . $key;
252 if ( isset( $post_data[ $keyed ] ) ) {
253 if ( current_user_can( 'unfiltered_html' ) )
254 update_post_meta( $post_ID, $keyed, $post_data[ $keyed ] );
256 update_post_meta( $post_ID, $keyed, wp_filter_post_kses( $post_data[ $keyed ] ) );
260 if ( 'attachment' === $post_data['post_type'] && preg_match( '#^(audio|video)/#', $post_data['post_mime_type'] ) ) {
261 $id3data = wp_get_attachment_metadata( $post_ID );
262 if ( ! is_array( $id3data ) ) {
266 foreach ( wp_get_attachment_id3_keys( $post, 'edit' ) as $key => $label ) {
267 if ( isset( $post_data[ 'id3_' . $key ] ) ) {
268 $id3data[ $key ] = sanitize_text_field( wp_unslash( $post_data[ 'id3_' . $key ] ) );
271 wp_update_attachment_metadata( $post_ID, $id3data );
275 if ( isset($post_data['meta']) && $post_data['meta'] ) {
276 foreach ( $post_data['meta'] as $key => $value ) {
277 if ( !$meta = get_post_meta_by_id( $key ) )
279 if ( $meta->post_id != $post_ID )
281 if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
283 update_meta( $key, $value['key'], $value['value'] );
287 if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
288 foreach ( $post_data['deletemeta'] as $key => $value ) {
289 if ( !$meta = get_post_meta_by_id( $key ) )
291 if ( $meta->post_id != $post_ID )
293 if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
300 if ( 'attachment' == $post_data['post_type'] ) {
301 if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
302 $image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
303 if ( $image_alt != get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) ) {
304 $image_alt = wp_strip_all_tags( $image_alt, true );
305 // update_meta expects slashed
306 update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
310 $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
312 /** This filter is documented in wp-admin/includes/media.php */
313 $post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
316 add_meta( $post_ID );
318 update_post_meta( $post_ID, '_edit_last', get_current_user_id() );
320 wp_update_post( $post_data );
322 // Now that we have an ID we can fix any attachment anchor hrefs
323 _fix_attachment_links( $post_ID );
325 wp_set_post_lock( $post_ID );
327 if ( current_user_can( $ptype->cap->edit_others_posts ) ) {
328 if ( ! empty( $post_data['sticky'] ) )
329 stick_post( $post_ID );
331 unstick_post( $post_ID );
338 * Process the post data for the bulk editing of posts.
340 * Updates all bulk edited posts/pages, adding (but not removing) tags and
341 * categories. Skips pages when they would be their own parent or child.
345 * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
348 function bulk_edit_posts( $post_data = null ) {
351 if ( empty($post_data) )
352 $post_data = &$_POST;
354 if ( isset($post_data['post_type']) )
355 $ptype = get_post_type_object($post_data['post_type']);
357 $ptype = get_post_type_object('post');
359 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
360 if ( 'page' == $ptype->name )
361 wp_die( __('You are not allowed to edit pages.'));
363 wp_die( __('You are not allowed to edit posts.'));
366 if ( -1 == $post_data['_status'] ) {
367 $post_data['post_status'] = null;
368 unset($post_data['post_status']);
370 $post_data['post_status'] = $post_data['_status'];
372 unset($post_data['_status']);
374 if ( ! empty( $post_data['post_status'] ) ) {
375 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
377 if ( 'inherit' == $post_data['post_status'] ) {
378 unset( $post_data['post_status'] );
382 $post_IDs = array_map( 'intval', (array) $post_data['post'] );
385 'post_author', 'post_status', 'post_password',
386 'post_parent', 'page_template', 'comment_status',
387 'ping_status', 'keep_private', 'tax_input',
388 'post_category', 'sticky', 'post_format',
391 foreach ( $reset as $field ) {
392 if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
393 unset($post_data[$field]);
396 if ( isset($post_data['post_category']) ) {
397 if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
398 $new_cats = array_map( 'absint', $post_data['post_category'] );
400 unset($post_data['post_category']);
403 $tax_input = array();
404 if ( isset($post_data['tax_input'])) {
405 foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
408 if ( is_taxonomy_hierarchical( $tax_name ) ) {
409 $tax_input[ $tax_name ] = array_map( 'absint', $terms );
411 $comma = _x( ',', 'tag delimiter' );
412 if ( ',' !== $comma )
413 $terms = str_replace( $comma, ',', $terms );
414 $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
419 if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
420 $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
423 for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
424 $children[] = $parent;
426 foreach ( $pages as $page ) {
427 if ( $page->ID == $parent ) {
428 $parent = $page->post_parent;
435 $updated = $skipped = $locked = array();
436 $shared_post_data = $post_data;
438 foreach ( $post_IDs as $post_ID ) {
439 // Start with fresh post data with each iteration.
440 $post_data = $shared_post_data;
442 $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
444 if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( 'edit_post', $post_ID ) ) {
445 $skipped[] = $post_ID;
449 if ( wp_check_post_lock( $post_ID ) ) {
450 $locked[] = $post_ID;
454 $post = get_post( $post_ID );
455 $tax_names = get_object_taxonomies( $post );
456 foreach ( $tax_names as $tax_name ) {
457 $taxonomy_obj = get_taxonomy($tax_name);
458 if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
459 $new_terms = $tax_input[$tax_name];
461 $new_terms = array();
463 if ( $taxonomy_obj->hierarchical )
464 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
466 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
468 $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
471 if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
472 $cats = (array) wp_get_post_categories($post_ID);
473 $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
474 unset( $post_data['tax_input']['category'] );
477 $post_data['post_type'] = $post->post_type;
478 $post_data['post_mime_type'] = $post->post_mime_type;
479 $post_data['guid'] = $post->guid;
481 foreach ( array( 'comment_status', 'ping_status', 'post_author' ) as $field ) {
482 if ( ! isset( $post_data[ $field ] ) ) {
483 $post_data[ $field ] = $post->$field;
487 $post_data['ID'] = $post_ID;
488 $post_data['post_ID'] = $post_ID;
490 $post_data = _wp_translate_postdata( true, $post_data );
491 if ( is_wp_error( $post_data ) ) {
492 $skipped[] = $post_ID;
496 $updated[] = wp_update_post( $post_data );
498 if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
499 if ( 'sticky' == $post_data['sticky'] )
500 stick_post( $post_ID );
502 unstick_post( $post_ID );
505 if ( isset( $post_data['post_format'] ) )
506 set_post_format( $post_ID, $post_data['post_format'] );
509 return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
513 * Default post information to use when populating the "Write Post" form.
517 * @param string $post_type A post type string, defaults to 'post'.
518 * @return WP_Post Post object containing all the default post data as attributes
520 function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
524 if ( !empty( $_REQUEST['post_title'] ) )
525 $post_title = esc_html( wp_unslash( $_REQUEST['post_title'] ));
528 if ( !empty( $_REQUEST['content'] ) )
529 $post_content = esc_html( wp_unslash( $_REQUEST['content'] ));
532 if ( !empty( $_REQUEST['excerpt'] ) )
533 $post_excerpt = esc_html( wp_unslash( $_REQUEST['excerpt'] ));
535 if ( $create_in_db ) {
536 $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
537 $post = get_post( $post_id );
538 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
539 set_post_format( $post, get_option( 'default_post_format' ) );
541 $post = new stdClass;
543 $post->post_author = '';
544 $post->post_date = '';
545 $post->post_date_gmt = '';
546 $post->post_password = '';
547 $post->post_type = $post_type;
548 $post->post_status = 'draft';
551 $post->comment_status = get_option( 'default_comment_status' );
552 $post->ping_status = get_option( 'default_ping_status' );
553 $post->post_pingback = get_option( 'default_pingback_flag' );
554 $post->post_category = get_option( 'default_category' );
555 $post->page_template = 'default';
556 $post->post_parent = 0;
557 $post->menu_order = 0;
558 $post = new WP_Post( $post );
562 * Filter the default post content initially used in the "Write Post" form.
566 * @param string $post_content Default post content.
567 * @param WP_Post $post Post object.
569 $post->post_content = apply_filters( 'default_content', $post_content, $post );
572 * Filter the default post title initially used in the "Write Post" form.
576 * @param string $post_title Default post title.
577 * @param WP_Post $post Post object.
579 $post->post_title = apply_filters( 'default_title', $post_title, $post );
582 * Filter the default post excerpt initially used in the "Write Post" form.
586 * @param string $post_excerpt Default post excerpt.
587 * @param WP_Post $post Post object.
589 $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
590 $post->post_name = '';
596 * Determine if a post exists based on title, content, and date
600 * @param string $title Post title
601 * @param string $content Optional post content
602 * @param string $date Optional post date
603 * @return int Post ID if post exists, 0 otherwise.
605 function post_exists($title, $content = '', $date = '') {
608 $post_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
609 $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
610 $post_date = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
612 $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
615 if ( !empty ( $date ) ) {
616 $query .= ' AND post_date = %s';
617 $args[] = $post_date;
620 if ( !empty ( $title ) ) {
621 $query .= ' AND post_title = %s';
622 $args[] = $post_title;
625 if ( !empty ( $content ) ) {
626 $query .= 'AND post_content = %s';
627 $args[] = $post_content;
630 if ( !empty ( $args ) )
631 return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
637 * Creates a new post from the "Write Post" form using $_POST information.
643 function wp_write_post() {
644 if ( isset($_POST['post_type']) )
645 $ptype = get_post_type_object($_POST['post_type']);
647 $ptype = get_post_type_object('post');
649 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
650 if ( 'page' == $ptype->name )
651 return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this site.' ) );
653 return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this site.' ) );
656 $_POST['post_mime_type'] = '';
658 // Clear out any data in internal vars.
659 unset( $_POST['filter'] );
661 // Edit don't write if we have a post id.
662 if ( isset( $_POST['post_ID'] ) )
665 if ( isset($_POST['visibility']) ) {
666 switch ( $_POST['visibility'] ) {
668 $_POST['post_password'] = '';
671 unset( $_POST['sticky'] );
674 $_POST['post_status'] = 'private';
675 $_POST['post_password'] = '';
676 unset( $_POST['sticky'] );
681 $translated = _wp_translate_postdata( false );
682 if ( is_wp_error($translated) )
686 $post_ID = wp_insert_post( $_POST );
687 if ( is_wp_error( $post_ID ) )
690 if ( empty($post_ID) )
693 add_meta( $post_ID );
695 add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
697 // Now that we have an ID we can fix any attachment anchor hrefs
698 _fix_attachment_links( $post_ID );
700 wp_set_post_lock( $post_ID );
706 * Calls wp_write_post() and handles the errors.
710 * @uses wp_write_post()
711 * @uses is_wp_error()
715 function write_post() {
716 $result = wp_write_post();
717 if ( is_wp_error( $result ) )
718 wp_die( $result->get_error_message() );
728 * {@internal Missing Short Description}}
732 * @param unknown_type $post_ID
735 function add_meta( $post_ID ) {
737 $post_ID = (int) $post_ID;
739 $metakeyselect = isset($_POST['metakeyselect']) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
740 $metakeyinput = isset($_POST['metakeyinput']) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
741 $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
742 if ( is_string( $metavalue ) )
743 $metavalue = trim( $metavalue );
745 if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
746 // We have a key/value pair. If both the select and the
747 // input for the key have data, the input takes precedence:
749 if ( '#NONE#' != $metakeyselect )
750 $metakey = $metakeyselect;
753 $metakey = $metakeyinput; // default
755 if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
758 $metakey = wp_slash( $metakey );
760 return add_post_meta( $post_ID, $metakey, $metavalue );
767 * {@internal Missing Short Description}}
771 * @param unknown_type $mid
774 function delete_meta( $mid ) {
775 return delete_metadata_by_mid( 'post' , $mid );
779 * Get a list of previously defined keys.
785 function get_meta_keys() {
788 $keys = $wpdb->get_col( "
792 ORDER BY meta_key" );
798 * {@internal Missing Short Description}}
802 * @param unknown_type $mid
805 function get_post_meta_by_id( $mid ) {
806 return get_metadata_by_mid( 'post', $mid );
810 * {@internal Missing Short Description}}
812 * Some postmeta stuff.
816 * @param unknown_type $postid
819 function has_meta( $postid ) {
822 return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
823 FROM $wpdb->postmeta WHERE post_id = %d
824 ORDER BY meta_key,meta_id", $postid), ARRAY_A );
828 * {@internal Missing Short Description}}
832 * @param unknown_type $meta_id
833 * @param unknown_type $meta_key Expect Slashed
834 * @param unknown_type $meta_value Expect Slashed
837 function update_meta( $meta_id, $meta_key, $meta_value ) {
838 $meta_key = wp_unslash( $meta_key );
839 $meta_value = wp_unslash( $meta_value );
841 return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
849 * Replace hrefs of attachment anchors with up-to-date permalinks.
854 * @param int|object $post Post ID or post object.
855 * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
857 function _fix_attachment_links( $post ) {
858 $post = get_post( $post, ARRAY_A );
859 $content = $post['post_content'];
861 // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
862 if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ) ) )
865 // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero)
866 if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) )
869 $site_url = get_bloginfo('url');
870 $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s)
873 foreach ( $link_matches[1] as $key => $value ) {
874 if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-')
875 || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
876 || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) )
879 $quote = $url_match[1]; // the quote (single or double)
880 $url_id = (int) $url_match[2];
881 $rel_id = (int) $rel_match[1];
883 if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false )
886 $link = $link_matches[0][$key];
887 $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
889 $content = str_replace( $link, $replace, $content );
893 $post['post_content'] = $content;
894 // Escape data pulled from DB.
895 $post = add_magic_quotes($post);
897 return wp_update_post($post);
902 * Get all the possible statuses for a post_type
906 * @param string $type The post_type you want the statuses for
907 * @return array As array of all the statuses for the supplied post type
909 function get_available_post_statuses($type = 'post') {
910 $stati = wp_count_posts($type);
912 return array_keys(get_object_vars($stati));
916 * Run the wp query to fetch the posts for listing on the edit posts page
920 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
923 function wp_edit_posts_query( $q = false ) {
926 $q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
927 $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
928 $post_stati = get_post_stati();
930 if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
931 $post_type = $q['post_type'];
935 $avail_post_stati = get_available_post_statuses($post_type);
937 if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
938 $post_status = $q['post_status'];
942 if ( isset($q['orderby']) )
943 $orderby = $q['orderby'];
944 elseif ( isset($q['post_status']) && in_array($q['post_status'], array('pending', 'draft')) )
945 $orderby = 'modified';
947 if ( isset($q['order']) )
948 $order = $q['order'];
949 elseif ( isset($q['post_status']) && 'pending' == $q['post_status'] )
952 $per_page = 'edit_' . $post_type . '_per_page';
953 $posts_per_page = (int) get_user_option( $per_page );
954 if ( empty( $posts_per_page ) || $posts_per_page < 1 )
955 $posts_per_page = 20;
958 * Filter the number of items per page to show for a specific 'per_page' type.
960 * The dynamic hook name, $per_page, refers to a hook name comprised of the post type,
961 * preceded by 'edit_', and succeeded by '_per_page', e.g. 'edit_$post_type_per_page'.
963 * Some examples of filter hooks generated here include: 'edit_attachment_per_page',
964 * 'edit_post_per_page', 'edit_page_per_page', etc.
968 * @param int $posts_per_page Number of posts to display per page for the given 'per_page'
971 $posts_per_page = apply_filters( $per_page, $posts_per_page );
974 * Filter the number of posts displayed per page when specifically listing "posts".
978 * @param int $per_page Number of posts to be displayed. Default 20.
979 * @param string $post_type The post type.
981 $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
983 $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
985 // Hierarchical types require special args.
986 if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
987 $query['orderby'] = 'menu_order title';
988 $query['order'] = 'asc';
989 $query['posts_per_page'] = -1;
990 $query['posts_per_archive_page'] = -1;
993 if ( ! empty( $q['show_sticky'] ) )
994 $query['post__in'] = (array) get_option( 'sticky_posts' );
998 return $avail_post_stati;
1002 * {@internal Missing Short Description}}
1006 * @param unknown_type $type
1009 function get_available_post_mime_types($type = 'attachment') {
1012 $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
1017 * Executes a query for attachments. An array of WP_Query arguments
1018 * can be passed in, which will override the arguments set by this function.
1022 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
1025 function wp_edit_attachments_query( $q = false ) {
1029 $q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0;
1030 $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1031 $q['post_type'] = 'attachment';
1032 $post_type = get_post_type_object( 'attachment' );
1033 $states = 'inherit';
1034 if ( current_user_can( $post_type->cap->read_private_posts ) )
1035 $states .= ',private';
1037 $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
1038 $media_per_page = (int) get_user_option( 'upload_per_page' );
1039 if ( empty( $media_per_page ) || $media_per_page < 1 )
1040 $media_per_page = 20;
1043 * Filter the number of items to list per page when listing media items.
1047 * @param int $media_per_page Number of media to list. Default 20.
1049 $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
1051 $post_mime_types = get_post_mime_types();
1052 $avail_post_mime_types = get_available_post_mime_types('attachment');
1054 if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) )
1055 unset($q['post_mime_type']);
1057 if ( isset($q['detached']) )
1058 $q['post_parent'] = 0;
1062 return array($post_mime_types, $avail_post_mime_types);
1066 * Returns the list of classes to be used by a metabox
1068 * @uses get_user_option()
1071 * @param unknown_type $id
1072 * @param unknown_type $page
1075 function postbox_classes( $id, $page ) {
1076 if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
1077 $classes = array( '' );
1078 } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
1079 if ( !is_array( $closed ) ) {
1080 $classes = array( '' );
1082 $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
1085 $classes = array( '' );
1089 * Filter the postbox classes for a specific screen and screen ID combo.
1091 * The dynamic portions of the hook name, $page, and $id, refer to
1092 * the screen, and screen ID, respectively.
1096 * @param array $classes An array of postbox classes.
1098 $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
1099 return implode( ' ', $classes );
1103 * {@internal Missing Short Description}}
1107 * @param int|object $id Post ID or post object.
1108 * @param string $title (optional) Title
1109 * @param string $name (optional) Name
1110 * @return array With two entries of type string
1112 function get_sample_permalink($id, $title = null, $name = null) {
1113 $post = get_post( $id );
1115 return array( '', '' );
1117 $ptype = get_post_type_object($post->post_type);
1119 $original_status = $post->post_status;
1120 $original_date = $post->post_date;
1121 $original_name = $post->post_name;
1123 // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
1124 if ( in_array( $post->post_status, array( 'draft', 'pending' ) ) ) {
1125 $post->post_status = 'publish';
1126 $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
1129 // If the user wants to set a new name -- override the current one
1130 // Note: if empty name is supplied -- use the title instead, see #6072
1131 if ( !is_null($name) )
1132 $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
1134 $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
1136 $post->filter = 'sample';
1138 $permalink = get_permalink($post, true);
1140 // Replace custom post_type Token with generic pagename token for ease of use.
1141 $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
1143 // Handle page hierarchy
1144 if ( $ptype->hierarchical ) {
1145 $uri = get_page_uri($post);
1146 $uri = untrailingslashit($uri);
1147 $uri = strrev( stristr( strrev( $uri ), '/' ) );
1148 $uri = untrailingslashit($uri);
1150 /** This filter is documented in wp-admin/edit-tag-form.php */
1151 $uri = apply_filters( 'editable_slug', $uri );
1154 $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
1157 /** This filter is documented in wp-admin/edit-tag-form.php */
1158 $permalink = array( $permalink, apply_filters( 'editable_slug', $post->post_name ) );
1159 $post->post_status = $original_status;
1160 $post->post_date = $original_date;
1161 $post->post_name = $original_name;
1162 unset($post->filter);
1168 * Returns the HTML of the sample permalink slug editor.
1172 * @param int|object $id Post ID or post object.
1173 * @param string $new_title Optional. New title.
1174 * @param string $new_slug Optional. New slug.
1175 * @return string The HTML of the sample permalink slug editor.
1177 function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1178 $post = get_post( $id );
1182 list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
1184 if ( current_user_can( 'read_post', $post->ID ) ) {
1185 $ptype = get_post_type_object( $post->post_type );
1186 $view_post = $ptype->labels->view_item;
1189 if ( 'publish' == get_post_status( $post ) ) {
1190 $title = __('Click to edit this part of the permalink');
1192 $title = __('Temporary permalink. Click to edit this part.');
1195 if ( false === strpos($permalink, '%postname%') && false === strpos($permalink, '%pagename%') ) {
1196 $return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink" tabindex="-1">' . $permalink . "</span>\n";
1197 if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) )
1198 $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
1199 if ( isset( $view_post ) )
1200 $return .= "<span id='view-post-btn'><a href='$permalink' class='button button-small'>$view_post</a></span>\n";
1203 * Filter the sample permalink HTML markup.
1207 * @param string $return Sample permalink HTML markup.
1208 * @param int|WP_Post $id Post object or ID.
1209 * @param string $new_title New sample permalink title.
1210 * @param string $new_slug New sample permalink slug.
1212 $return = apply_filters( 'get_sample_permalink_html', $return, $id, $new_title, $new_slug );
1217 if ( function_exists('mb_strlen') ) {
1218 if ( mb_strlen($post_name) > 30 ) {
1219 $post_name_abridged = mb_substr($post_name, 0, 14). '…' . mb_substr($post_name, -14);
1221 $post_name_abridged = $post_name;
1224 if ( strlen($post_name) > 30 ) {
1225 $post_name_abridged = substr($post_name, 0, 14). '…' . substr($post_name, -14);
1227 $post_name_abridged = $post_name;
1231 $post_name_html = '<span id="editable-post-name" title="' . $title . '">' . $post_name_abridged . '</span>';
1232 $display_link = str_replace(array('%pagename%','%postname%'), $post_name_html, $permalink);
1233 $view_link = str_replace(array('%pagename%','%postname%'), $post_name, $permalink);
1234 $return = '<strong>' . __('Permalink:') . "</strong>\n";
1235 $return .= '<span id="sample-permalink" tabindex="-1">' . $display_link . "</span>\n";
1236 $return .= '‎'; // Fix bi-directional text display defect in RTL languages.
1237 $return .= '<span id="edit-slug-buttons"><a href="#post_name" class="edit-slug button button-small hide-if-no-js" onclick="editPermalink(' . $id . '); return false;">' . __('Edit') . "</a></span>\n";
1238 $return .= '<span id="editable-post-name-full">' . $post_name . "</span>\n";
1240 if ( isset( $view_post ) ) {
1241 $return .= "<span id='view-post-btn'><a href='" . get_permalink( $post ) . "' class='button button-small'>$view_post</a></span>\n";
1244 /** This filter is documented in wp-admin/includes/post.php */
1245 $return = apply_filters( 'get_sample_permalink_html', $return, $id, $new_title, $new_slug );
1251 * Output HTML for the post thumbnail meta-box.
1255 * @param int $thumbnail_id ID of the attachment used for thumbnail
1256 * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post.
1257 * @return string html
1259 function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1260 global $content_width, $_wp_additional_image_sizes;
1262 $post = get_post( $post );
1264 $upload_iframe_src = esc_url( get_upload_iframe_src('image', $post->ID ) );
1265 $set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="%s" id="set-post-thumbnail" class="thickbox">%s</a></p>';
1266 $content = sprintf( $set_thumbnail_link, $upload_iframe_src, esc_html__( 'Set featured image' ) );
1268 if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1269 $old_content_width = $content_width;
1270 $content_width = 266;
1271 if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) )
1272 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
1274 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' );
1275 if ( !empty( $thumbnail_html ) ) {
1276 $ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
1277 $content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
1278 $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>';
1280 $content_width = $old_content_width;
1284 * Filter the admin post thumbnail HTML markup to return.
1288 * @param string $content Admin post thumbnail HTML markup.
1289 * @param int $post_id Post ID.
1291 return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID );
1295 * Check to see if the post is currently being edited by another user.
1299 * @param int $post_id ID of the post to check for editing
1300 * @return bool|int False: not locked or locked by current user. Int: user ID of user with lock.
1302 function wp_check_post_lock( $post_id ) {
1303 if ( !$post = get_post( $post_id ) )
1306 if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) )
1309 $lock = explode( ':', $lock );
1311 $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1313 /** This filter is documented in wp-admin/includes/ajax-actions.php */
1314 $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
1316 if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
1322 * Mark the post as currently being edited by the current user
1326 * @param int $post_id ID of the post to being edited
1327 * @return bool|array Returns false if the post doesn't exist of there is no current user, or
1328 * an array of the lock time and the user ID.
1330 function wp_set_post_lock( $post_id ) {
1331 if ( !$post = get_post( $post_id ) )
1333 if ( 0 == ($user_id = get_current_user_id()) )
1337 $lock = "$now:$user_id";
1339 update_post_meta( $post->ID, '_edit_lock', $lock );
1340 return array( $now, $user_id );
1344 * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
1349 function _admin_notice_post_locked() {
1350 if ( ! $post = get_post() )
1354 if ( $user_id = wp_check_post_lock( $post->ID ) )
1355 $user = get_userdata( $user_id );
1360 * Filter whether to show the post locked dialog.
1362 * Returning a falsey value to the filter will short-circuit displaying the dialog.
1366 * @param bool $display Whether to display the dialog. Default true.
1367 * @param WP_User|bool $user WP_User object on success, false otherwise.
1369 if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) )
1377 if ( $locked && ( $sendback = wp_get_referer() ) &&
1378 false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
1380 $sendback_text = __('Go back');
1382 $sendback = admin_url( 'edit.php' );
1384 if ( 'post' != $post->post_type )
1385 $sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
1387 $sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
1390 $hidden = $locked ? '' : ' hidden';
1393 <div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
1394 <div class="notification-dialog-background"></div>
1395 <div class="notification-dialog">
1399 if ( get_post_type_object( $post->post_type )->public ) {
1400 $preview_link = set_url_scheme( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) );
1402 if ( 'publish' == $post->post_status || $user->ID != $post->post_author ) {
1403 // Latest content is in autosave
1404 $nonce = wp_create_nonce( 'post_preview_' . $post->ID );
1405 $preview_link = add_query_arg( array( 'preview_id' => $post->ID, 'preview_nonce' => $nonce ), $preview_link );
1411 /** This filter is documented in wp-admin/includes/meta-boxes.php */
1412 $preview_link = apply_filters( 'preview_post_link', $preview_link );
1415 * Filter whether to allow the post lock to be overridden.
1417 * Returning a falsey value to the filter will disable the ability
1418 * to override the post lock.
1422 * @param bool $override Whether to allow overriding post locks. Default true.
1423 * @param WP_Post $post Post object.
1424 * @param WP_User $user User object.
1426 $override = apply_filters( 'override_post_lock', true, $post, $user );
1427 $tab_last = $override ? '' : ' wp-tab-last';
1430 <div class="post-locked-message">
1431 <div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
1432 <p class="currently-editing wp-tab-first" tabindex="0">
1434 _e( 'This content is currently locked.' );
1436 printf( ' ' . __( 'If you take over, %s will be blocked from continuing to edit.' ), esc_html( $user->display_name ) );
1441 * Fires inside the post locked dialog before the buttons are displayed.
1445 * @param WP_Post $post Post object.
1447 do_action( 'post_locked_dialog', $post );
1450 <a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
1451 <?php if ( $preview_link ) { ?>
1452 <a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e('Preview'); ?></a>
1456 // Allow plugins to prevent some users overriding the post lock
1459 <a class="button button-primary wp-tab-last" href="<?php echo esc_url( add_query_arg( 'get-post-lock', '1', get_edit_post_link( $post->ID, 'url' ) ) ); ?>"><?php _e('Take over'); ?></a>
1469 <div class="post-taken-over">
1470 <div class="post-locked-avatar"></div>
1471 <p class="wp-tab-first" tabindex="0">
1472 <span class="currently-editing"></span><br>
1473 <span class="locked-saving hidden"><img src="images/wpspin_light-2x.gif" width="16" height="16" /> <?php _e('Saving revision...'); ?></span>
1474 <span class="locked-saved hidden"><?php _e('Your latest changes were saved as a revision.'); ?></span>
1478 * Fires inside the dialog displayed when a user has lost the post lock.
1482 * @param WP_Post $post Post object.
1484 do_action( 'post_lock_lost_dialog', $post );
1486 <p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
1498 * Creates autosave data for the specified post from $_POST data.
1500 * @package WordPress
1501 * @subpackage Post_Revisions
1504 * @uses _wp_translate_postdata()
1505 * @uses _wp_post_revision_fields()
1507 * @param mixed $post_data Associative array containing the post data or int post ID.
1508 * @return mixed The autosave revision ID. WP_Error or 0 on error.
1510 function wp_create_post_autosave( $post_data ) {
1511 if ( is_numeric( $post_data ) ) {
1512 $post_id = $post_data;
1513 $post_data = &$_POST;
1515 $post_id = (int) $post_data['post_ID'];
1518 $post_data = _wp_translate_postdata( true, $post_data );
1519 if ( is_wp_error( $post_data ) )
1522 $post_author = get_current_user_id();
1524 // Store one autosave per author. If there is already an autosave, overwrite it.
1525 if ( $old_autosave = wp_get_post_autosave( $post_id, $post_author ) ) {
1526 $new_autosave = _wp_post_revision_fields( $post_data, true );
1527 $new_autosave['ID'] = $old_autosave->ID;
1528 $new_autosave['post_author'] = $post_author;
1530 // If the new autosave has the same content as the post, delete the autosave.
1531 $post = get_post( $post_id );
1532 $autosave_is_different = false;
1533 foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields() ) ) as $field ) {
1534 if ( normalize_whitespace( $new_autosave[ $field ] ) != normalize_whitespace( $post->$field ) ) {
1535 $autosave_is_different = true;
1540 if ( ! $autosave_is_different ) {
1541 wp_delete_post_revision( $old_autosave->ID );
1545 return wp_update_post( $new_autosave );
1548 // _wp_put_post_revision() expects unescaped.
1549 $post_data = wp_unslash( $post_data );
1551 // Otherwise create the new autosave as a special post revision
1552 return _wp_put_post_revision( $post_data, true );
1556 * Save draft or manually autosave for showing preview.
1558 * @package WordPress
1561 * @uses get_post_status()
1564 * @uses current_user_can()
1566 * @uses wp_create_post_autosave()
1567 * @uses add_query_arg()
1568 * @uses wp_create_nonce()
1570 * @return str URL to redirect to show the preview
1572 function post_preview() {
1574 $post_ID = (int) $_POST['post_ID'];
1575 $_POST['ID'] = $post_ID;
1577 if ( ! $post = get_post( $post_ID ) ) {
1578 wp_die( __( 'You are not allowed to edit this post.' ) );
1581 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1582 wp_die( __( 'You are not allowed to edit this post.' ) );
1585 $is_autosave = false;
1587 if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'draft' == $post->post_status || 'auto-draft' == $post->post_status ) ) {
1588 $saved_post_id = edit_post();
1590 $is_autosave = true;
1592 if ( 'auto-draft' == $_POST['post_status'] )
1593 $_POST['post_status'] = 'draft';
1595 $saved_post_id = wp_create_post_autosave( $post->ID );
1598 if ( is_wp_error( $saved_post_id ) )
1599 wp_die( $saved_post_id->get_error_message() );
1601 $query_args = array( 'preview' => 'true' );
1603 if ( $is_autosave && $saved_post_id ) {
1604 $query_args['preview_id'] = $post->ID;
1605 $query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
1607 if ( isset( $_POST['post_format'] ) )
1608 $query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
1611 $url = add_query_arg( $query_args, get_permalink( $post->ID ) );
1613 /** This filter is documented in wp-admin/includes/meta-boxes.php */
1614 return apply_filters( 'preview_post_link', $url );
1618 * Save a post submitted with XHR
1620 * Intended for use with heartbeat and autosave.js
1624 * @param $post_data Associative array of the submitted post data.
1625 * @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
1626 * Te ID can be the draft post_id or the autosave revision post_id.
1628 function wp_autosave( $post_data ) {
1630 if ( ! defined( 'DOING_AUTOSAVE' ) )
1631 define( 'DOING_AUTOSAVE', true );
1633 $post_id = (int) $post_data['post_id'];
1634 $post_data['ID'] = $post_data['post_ID'] = $post_id;
1636 if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
1637 return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
1640 $post = get_post( $post_id );
1642 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1643 return new WP_Error( 'edit_posts', __( 'You are not allowed to edit this item.' ) );
1646 if ( 'auto-draft' == $post->post_status )
1647 $post_data['post_status'] = 'draft';
1649 if ( $post_data['post_type'] != 'page' && ! empty( $post_data['catslist'] ) )
1650 $post_data['post_category'] = explode( ',', $post_data['catslist'] );
1652 if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'auto-draft' == $post->post_status || 'draft' == $post->post_status ) ) {
1653 // Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked
1654 return edit_post( wp_slash( $post_data ) );
1656 // Non drafts or other users drafts are not overwritten. The autosave is stored in a special post revision for each user.
1657 return wp_create_post_autosave( wp_slash( $post_data ) );