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 ) {
182 if ( empty($post_data) )
183 $post_data = &$_POST;
185 // Clear out any data in internal vars.
186 unset( $post_data['filter'] );
188 $post_ID = (int) $post_data['post_ID'];
189 $post = get_post( $post_ID );
190 $post_data['post_type'] = $post->post_type;
191 $post_data['post_mime_type'] = $post->post_mime_type;
193 if ( ! empty( $post_data['post_status'] ) ) {
194 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
196 if ( 'inherit' == $post_data['post_status'] ) {
197 unset( $post_data['post_status'] );
201 $ptype = get_post_type_object($post_data['post_type']);
202 if ( !current_user_can( 'edit_post', $post_ID ) ) {
203 if ( 'page' == $post_data['post_type'] )
204 wp_die( __('You are not allowed to edit this page.' ));
206 wp_die( __('You are not allowed to edit this post.' ));
209 if ( post_type_supports( $ptype->name, 'revisions' ) ) {
210 $revisions = wp_get_post_revisions( $post_ID, array( 'order' => 'ASC', 'posts_per_page' => 1 ) );
211 $revision = current( $revisions );
213 // Check if the revisions have been upgraded
214 if ( $revisions && _wp_get_post_revision_version( $revision ) < 1 )
215 _wp_upgrade_revisions_of_post( $post, wp_get_post_revisions( $post_ID ) );
218 if ( isset($post_data['visibility']) ) {
219 switch ( $post_data['visibility'] ) {
221 $post_data['post_password'] = '';
224 unset( $post_data['sticky'] );
227 $post_data['post_status'] = 'private';
228 $post_data['post_password'] = '';
229 unset( $post_data['sticky'] );
234 $post_data = _wp_translate_postdata( true, $post_data );
235 if ( is_wp_error($post_data) )
236 wp_die( $post_data->get_error_message() );
239 if ( isset( $post_data['post_format'] ) )
240 set_post_format( $post_ID, $post_data['post_format'] );
242 $format_meta_urls = array( 'url', 'link_url', 'quote_source_url' );
243 foreach ( $format_meta_urls as $format_meta_url ) {
244 $keyed = '_format_' . $format_meta_url;
245 if ( isset( $post_data[ $keyed ] ) )
246 update_post_meta( $post_ID, $keyed, wp_slash( esc_url_raw( wp_unslash( $post_data[ $keyed ] ) ) ) );
249 $format_keys = array( 'quote', 'quote_source_name', 'image', 'gallery', 'audio_embed', 'video_embed' );
251 foreach ( $format_keys as $key ) {
252 $keyed = '_format_' . $key;
253 if ( isset( $post_data[ $keyed ] ) ) {
254 if ( current_user_can( 'unfiltered_html' ) )
255 update_post_meta( $post_ID, $keyed, $post_data[ $keyed ] );
257 update_post_meta( $post_ID, $keyed, wp_filter_post_kses( $post_data[ $keyed ] ) );
261 if ( 'attachment' === $post_data['post_type'] && preg_match( '#^(audio|video)/#', $post_data['post_mime_type'] ) ) {
262 $id3data = wp_get_attachment_metadata( $post_ID );
263 if ( ! is_array( $id3data ) ) {
267 foreach ( wp_get_attachment_id3_keys( $post, 'edit' ) as $key => $label ) {
268 if ( isset( $post_data[ 'id3_' . $key ] ) ) {
269 $id3data[ $key ] = sanitize_text_field( wp_unslash( $post_data[ 'id3_' . $key ] ) );
272 wp_update_attachment_metadata( $post_ID, $id3data );
276 if ( isset($post_data['meta']) && $post_data['meta'] ) {
277 foreach ( $post_data['meta'] as $key => $value ) {
278 if ( !$meta = get_post_meta_by_id( $key ) )
280 if ( $meta->post_id != $post_ID )
282 if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
284 update_meta( $key, $value['key'], $value['value'] );
288 if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
289 foreach ( $post_data['deletemeta'] as $key => $value ) {
290 if ( !$meta = get_post_meta_by_id( $key ) )
292 if ( $meta->post_id != $post_ID )
294 if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
301 if ( 'attachment' == $post_data['post_type'] ) {
302 if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
303 $image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
304 if ( $image_alt != get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) ) {
305 $image_alt = wp_strip_all_tags( $image_alt, true );
306 // update_meta expects slashed.
307 update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
311 $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
313 /** This filter is documented in wp-admin/includes/media.php */
314 $post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
317 add_meta( $post_ID );
319 update_post_meta( $post_ID, '_edit_last', get_current_user_id() );
321 $success = wp_update_post( $post_data );
322 // If the save failed, see if we can sanity check the main fields and try again
323 if ( ! $success && is_callable( array( $wpdb, 'strip_invalid_text_for_column' ) ) ) {
324 $fields = array( 'post_title', 'post_content', 'post_excerpt' );
326 foreach( $fields as $field ) {
327 if ( isset( $post_data[ $field ] ) ) {
328 $post_data[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->posts, $field, $post_data[ $field ] );
332 wp_update_post( $post_data );
335 // Now that we have an ID we can fix any attachment anchor hrefs
336 _fix_attachment_links( $post_ID );
338 wp_set_post_lock( $post_ID );
340 if ( current_user_can( $ptype->cap->edit_others_posts ) ) {
341 if ( ! empty( $post_data['sticky'] ) )
342 stick_post( $post_ID );
344 unstick_post( $post_ID );
351 * Process the post data for the bulk editing of posts.
353 * Updates all bulk edited posts/pages, adding (but not removing) tags and
354 * categories. Skips pages when they would be their own parent or child.
358 * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
361 function bulk_edit_posts( $post_data = null ) {
364 if ( empty($post_data) )
365 $post_data = &$_POST;
367 if ( isset($post_data['post_type']) )
368 $ptype = get_post_type_object($post_data['post_type']);
370 $ptype = get_post_type_object('post');
372 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
373 if ( 'page' == $ptype->name )
374 wp_die( __('You are not allowed to edit pages.'));
376 wp_die( __('You are not allowed to edit posts.'));
379 if ( -1 == $post_data['_status'] ) {
380 $post_data['post_status'] = null;
381 unset($post_data['post_status']);
383 $post_data['post_status'] = $post_data['_status'];
385 unset($post_data['_status']);
387 if ( ! empty( $post_data['post_status'] ) ) {
388 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
390 if ( 'inherit' == $post_data['post_status'] ) {
391 unset( $post_data['post_status'] );
395 $post_IDs = array_map( 'intval', (array) $post_data['post'] );
398 'post_author', 'post_status', 'post_password',
399 'post_parent', 'page_template', 'comment_status',
400 'ping_status', 'keep_private', 'tax_input',
401 'post_category', 'sticky', 'post_format',
404 foreach ( $reset as $field ) {
405 if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
406 unset($post_data[$field]);
409 if ( isset($post_data['post_category']) ) {
410 if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
411 $new_cats = array_map( 'absint', $post_data['post_category'] );
413 unset($post_data['post_category']);
416 $tax_input = array();
417 if ( isset($post_data['tax_input'])) {
418 foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
421 if ( is_taxonomy_hierarchical( $tax_name ) ) {
422 $tax_input[ $tax_name ] = array_map( 'absint', $terms );
424 $comma = _x( ',', 'tag delimiter' );
425 if ( ',' !== $comma )
426 $terms = str_replace( $comma, ',', $terms );
427 $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
432 if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
433 $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
436 for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
437 $children[] = $parent;
439 foreach ( $pages as $page ) {
440 if ( $page->ID == $parent ) {
441 $parent = $page->post_parent;
448 $updated = $skipped = $locked = array();
449 $shared_post_data = $post_data;
451 foreach ( $post_IDs as $post_ID ) {
452 // Start with fresh post data with each iteration.
453 $post_data = $shared_post_data;
455 $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
457 if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( 'edit_post', $post_ID ) ) {
458 $skipped[] = $post_ID;
462 if ( wp_check_post_lock( $post_ID ) ) {
463 $locked[] = $post_ID;
467 $post = get_post( $post_ID );
468 $tax_names = get_object_taxonomies( $post );
469 foreach ( $tax_names as $tax_name ) {
470 $taxonomy_obj = get_taxonomy($tax_name);
471 if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
472 $new_terms = $tax_input[$tax_name];
474 $new_terms = array();
476 if ( $taxonomy_obj->hierarchical )
477 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
479 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
481 $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
484 if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
485 $cats = (array) wp_get_post_categories($post_ID);
486 $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
487 unset( $post_data['tax_input']['category'] );
490 $post_data['post_type'] = $post->post_type;
491 $post_data['post_mime_type'] = $post->post_mime_type;
492 $post_data['guid'] = $post->guid;
494 foreach ( array( 'comment_status', 'ping_status', 'post_author' ) as $field ) {
495 if ( ! isset( $post_data[ $field ] ) ) {
496 $post_data[ $field ] = $post->$field;
500 $post_data['ID'] = $post_ID;
501 $post_data['post_ID'] = $post_ID;
503 $post_data = _wp_translate_postdata( true, $post_data );
504 if ( is_wp_error( $post_data ) ) {
505 $skipped[] = $post_ID;
509 $updated[] = wp_update_post( $post_data );
511 if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
512 if ( 'sticky' == $post_data['sticky'] )
513 stick_post( $post_ID );
515 unstick_post( $post_ID );
518 if ( isset( $post_data['post_format'] ) )
519 set_post_format( $post_ID, $post_data['post_format'] );
522 return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
526 * Default post information to use when populating the "Write Post" form.
530 * @param string $post_type A post type string, defaults to 'post'.
531 * @return WP_Post Post object containing all the default post data as attributes
533 function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
535 if ( !empty( $_REQUEST['post_title'] ) )
536 $post_title = esc_html( wp_unslash( $_REQUEST['post_title'] ));
539 if ( !empty( $_REQUEST['content'] ) )
540 $post_content = esc_html( wp_unslash( $_REQUEST['content'] ));
543 if ( !empty( $_REQUEST['excerpt'] ) )
544 $post_excerpt = esc_html( wp_unslash( $_REQUEST['excerpt'] ));
546 if ( $create_in_db ) {
547 $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
548 $post = get_post( $post_id );
549 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
550 set_post_format( $post, get_option( 'default_post_format' ) );
552 $post = new stdClass;
554 $post->post_author = '';
555 $post->post_date = '';
556 $post->post_date_gmt = '';
557 $post->post_password = '';
558 $post->post_name = '';
559 $post->post_type = $post_type;
560 $post->post_status = 'draft';
563 $post->comment_status = get_option( 'default_comment_status' );
564 $post->ping_status = get_option( 'default_ping_status' );
565 $post->post_pingback = get_option( 'default_pingback_flag' );
566 $post->post_category = get_option( 'default_category' );
567 $post->page_template = 'default';
568 $post->post_parent = 0;
569 $post->menu_order = 0;
570 $post = new WP_Post( $post );
574 * Filter the default post content initially used in the "Write Post" form.
578 * @param string $post_content Default post content.
579 * @param WP_Post $post Post object.
581 $post->post_content = apply_filters( 'default_content', $post_content, $post );
584 * Filter the default post title initially used in the "Write Post" form.
588 * @param string $post_title Default post title.
589 * @param WP_Post $post Post object.
591 $post->post_title = apply_filters( 'default_title', $post_title, $post );
594 * Filter the default post excerpt initially used in the "Write Post" form.
598 * @param string $post_excerpt Default post excerpt.
599 * @param WP_Post $post Post object.
601 $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
607 * Determine if a post exists based on title, content, and date
611 * @param string $title Post title
612 * @param string $content Optional post content
613 * @param string $date Optional post date
614 * @return int Post ID if post exists, 0 otherwise.
616 function post_exists($title, $content = '', $date = '') {
619 $post_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
620 $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
621 $post_date = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
623 $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
626 if ( !empty ( $date ) ) {
627 $query .= ' AND post_date = %s';
628 $args[] = $post_date;
631 if ( !empty ( $title ) ) {
632 $query .= ' AND post_title = %s';
633 $args[] = $post_title;
636 if ( !empty ( $content ) ) {
637 $query .= 'AND post_content = %s';
638 $args[] = $post_content;
641 if ( !empty ( $args ) )
642 return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
648 * Creates a new post from the "Write Post" form using $_POST information.
652 * @return int|WP_Error
654 function wp_write_post() {
655 if ( isset($_POST['post_type']) )
656 $ptype = get_post_type_object($_POST['post_type']);
658 $ptype = get_post_type_object('post');
660 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
661 if ( 'page' == $ptype->name )
662 return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this site.' ) );
664 return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this site.' ) );
667 $_POST['post_mime_type'] = '';
669 // Clear out any data in internal vars.
670 unset( $_POST['filter'] );
672 // Edit don't write if we have a post id.
673 if ( isset( $_POST['post_ID'] ) )
676 if ( isset($_POST['visibility']) ) {
677 switch ( $_POST['visibility'] ) {
679 $_POST['post_password'] = '';
682 unset( $_POST['sticky'] );
685 $_POST['post_status'] = 'private';
686 $_POST['post_password'] = '';
687 unset( $_POST['sticky'] );
692 $translated = _wp_translate_postdata( false );
693 if ( is_wp_error($translated) )
697 $post_ID = wp_insert_post( $_POST );
698 if ( is_wp_error( $post_ID ) )
701 if ( empty($post_ID) )
704 add_meta( $post_ID );
706 add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
708 // Now that we have an ID we can fix any attachment anchor hrefs
709 _fix_attachment_links( $post_ID );
711 wp_set_post_lock( $post_ID );
717 * Calls wp_write_post() and handles the errors.
723 function write_post() {
724 $result = wp_write_post();
725 if ( is_wp_error( $result ) )
726 wp_die( $result->get_error_message() );
736 * {@internal Missing Short Description}}
740 * @param int $post_ID
743 function add_meta( $post_ID ) {
744 $post_ID = (int) $post_ID;
746 $metakeyselect = isset($_POST['metakeyselect']) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
747 $metakeyinput = isset($_POST['metakeyinput']) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
748 $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
749 if ( is_string( $metavalue ) )
750 $metavalue = trim( $metavalue );
752 if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
754 * We have a key/value pair. If both the select and the input
755 * for the key have data, the input takes precedence.
757 if ( '#NONE#' != $metakeyselect )
758 $metakey = $metakeyselect;
761 $metakey = $metakeyinput; // default
763 if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
766 $metakey = wp_slash( $metakey );
768 return add_post_meta( $post_ID, $metakey, $metavalue );
775 * {@internal Missing Short Description}}
782 function delete_meta( $mid ) {
783 return delete_metadata_by_mid( 'post' , $mid );
787 * Get a list of previously defined keys.
793 function get_meta_keys() {
796 $keys = $wpdb->get_col( "
800 ORDER BY meta_key" );
806 * {@internal Missing Short Description}}
811 * @return object|bool
813 function get_post_meta_by_id( $mid ) {
814 return get_metadata_by_mid( 'post', $mid );
818 * {@internal Missing Short Description}}
820 * Some postmeta stuff.
827 function has_meta( $postid ) {
830 return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
831 FROM $wpdb->postmeta WHERE post_id = %d
832 ORDER BY meta_key,meta_id", $postid), ARRAY_A );
836 * {@internal Missing Short Description}}
840 * @param int $meta_id
841 * @param string $meta_key Expect Slashed
842 * @param string $meta_value Expect Slashed
845 function update_meta( $meta_id, $meta_key, $meta_value ) {
846 $meta_key = wp_unslash( $meta_key );
847 $meta_value = wp_unslash( $meta_value );
849 return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
857 * Replace hrefs of attachment anchors with up-to-date permalinks.
862 * @param int|object $post Post ID or post object.
863 * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
865 function _fix_attachment_links( $post ) {
866 $post = get_post( $post, ARRAY_A );
867 $content = $post['post_content'];
869 // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
870 if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ) ) )
873 // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero)
874 if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) )
877 $site_url = get_bloginfo('url');
878 $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s)
881 foreach ( $link_matches[1] as $key => $value ) {
882 if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-')
883 || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
884 || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) )
887 $quote = $url_match[1]; // the quote (single or double)
888 $url_id = (int) $url_match[2];
889 $rel_id = (int) $rel_match[1];
891 if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false )
894 $link = $link_matches[0][$key];
895 $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
897 $content = str_replace( $link, $replace, $content );
901 $post['post_content'] = $content;
902 // Escape data pulled from DB.
903 $post = add_magic_quotes($post);
905 return wp_update_post($post);
910 * Get all the possible statuses for a post_type
914 * @param string $type The post_type you want the statuses for
915 * @return array As array of all the statuses for the supplied post type
917 function get_available_post_statuses($type = 'post') {
918 $stati = wp_count_posts($type);
920 return array_keys(get_object_vars($stati));
924 * Run the wp query to fetch the posts for listing on the edit posts page
928 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
931 function wp_edit_posts_query( $q = false ) {
934 $q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
935 $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
936 $post_stati = get_post_stati();
938 if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
939 $post_type = $q['post_type'];
943 $avail_post_stati = get_available_post_statuses($post_type);
945 if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
946 $post_status = $q['post_status'];
950 if ( isset($q['orderby']) )
951 $orderby = $q['orderby'];
952 elseif ( isset($q['post_status']) && in_array($q['post_status'], array('pending', 'draft')) )
953 $orderby = 'modified';
955 if ( isset($q['order']) )
956 $order = $q['order'];
957 elseif ( isset($q['post_status']) && 'pending' == $q['post_status'] )
960 $per_page = "edit_{$post_type}_per_page";
961 $posts_per_page = (int) get_user_option( $per_page );
962 if ( empty( $posts_per_page ) || $posts_per_page < 1 )
963 $posts_per_page = 20;
966 * Filter the number of items per page to show for a specific 'per_page' type.
968 * The dynamic portion of the hook name, `$post_type`, refers to the post type.
970 * Some examples of filter hooks generated here include: 'edit_attachment_per_page',
971 * 'edit_post_per_page', 'edit_page_per_page', etc.
975 * @param int $posts_per_page Number of posts to display per page for the given post
978 $posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
981 * Filter the number of posts displayed per page when specifically listing "posts".
985 * @param int $posts_per_page Number of posts to be displayed. Default 20.
986 * @param string $post_type The post type.
988 $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
990 $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
992 // Hierarchical types require special args.
993 if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
994 $query['orderby'] = 'menu_order title';
995 $query['order'] = 'asc';
996 $query['posts_per_page'] = -1;
997 $query['posts_per_archive_page'] = -1;
1000 if ( ! empty( $q['show_sticky'] ) )
1001 $query['post__in'] = (array) get_option( 'sticky_posts' );
1005 return $avail_post_stati;
1009 * {@internal Missing Short Description}}
1013 * @param string $type
1016 function get_available_post_mime_types($type = 'attachment') {
1019 $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
1024 * Executes a query for attachments. An array of WP_Query arguments
1025 * can be passed in, which will override the arguments set by this function.
1029 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
1032 function wp_edit_attachments_query( $q = false ) {
1036 $q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0;
1037 $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1038 $q['post_type'] = 'attachment';
1039 $post_type = get_post_type_object( 'attachment' );
1040 $states = 'inherit';
1041 if ( current_user_can( $post_type->cap->read_private_posts ) )
1042 $states .= ',private';
1044 $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
1045 $q['post_status'] = isset( $q['attachment-filter'] ) && 'trash' == $q['attachment-filter'] ? 'trash' : $states;
1047 $media_per_page = (int) get_user_option( 'upload_per_page' );
1048 if ( empty( $media_per_page ) || $media_per_page < 1 )
1049 $media_per_page = 20;
1052 * Filter the number of items to list per page when listing media items.
1056 * @param int $media_per_page Number of media to list. Default 20.
1058 $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
1060 $post_mime_types = get_post_mime_types();
1061 $avail_post_mime_types = get_available_post_mime_types('attachment');
1063 if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) )
1064 unset($q['post_mime_type']);
1066 foreach( array_keys( $post_mime_types ) as $type ) {
1067 if ( isset( $q['attachment-filter'] ) && "post_mime_type:$type" == $q['attachment-filter'] ) {
1068 $q['post_mime_type'] = $type;
1073 if ( isset( $q['detached'] ) || ( isset( $q['attachment-filter'] ) && 'detached' == $q['attachment-filter'] ) ) {
1074 $q['post_parent'] = 0;
1079 return array($post_mime_types, $avail_post_mime_types);
1083 * Returns the list of classes to be used by a metabox
1088 * @param string $page
1091 function postbox_classes( $id, $page ) {
1092 if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
1093 $classes = array( '' );
1094 } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
1095 if ( !is_array( $closed ) ) {
1096 $classes = array( '' );
1098 $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
1101 $classes = array( '' );
1105 * Filter the postbox classes for a specific screen and screen ID combo.
1107 * The dynamic portions of the hook name, `$page` and `$id`, refer to
1108 * the screen and screen ID, respectively.
1112 * @param array $classes An array of postbox classes.
1114 $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
1115 return implode( ' ', $classes );
1119 * Get a sample permalink based off of the post name.
1123 * @param int $id Post ID or post object.
1124 * @param string $title Optional. Title. Default null.
1125 * @param string $name Optional. Name. Default null.
1126 * @return array Array with two entries of type string.
1128 function get_sample_permalink($id, $title = null, $name = null) {
1129 $post = get_post( $id );
1131 return array( '', '' );
1133 $ptype = get_post_type_object($post->post_type);
1135 $original_status = $post->post_status;
1136 $original_date = $post->post_date;
1137 $original_name = $post->post_name;
1139 // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
1140 if ( in_array( $post->post_status, array( 'draft', 'pending' ) ) ) {
1141 $post->post_status = 'publish';
1142 $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
1145 // If the user wants to set a new name -- override the current one
1146 // Note: if empty name is supplied -- use the title instead, see #6072
1147 if ( !is_null($name) )
1148 $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
1150 $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
1152 $post->filter = 'sample';
1154 $permalink = get_permalink($post, true);
1156 // Replace custom post_type Token with generic pagename token for ease of use.
1157 $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
1159 // Handle page hierarchy
1160 if ( $ptype->hierarchical ) {
1161 $uri = get_page_uri($post);
1162 $uri = untrailingslashit($uri);
1163 $uri = strrev( stristr( strrev( $uri ), '/' ) );
1164 $uri = untrailingslashit($uri);
1166 /** This filter is documented in wp-admin/edit-tag-form.php */
1167 $uri = apply_filters( 'editable_slug', $uri );
1170 $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
1173 /** This filter is documented in wp-admin/edit-tag-form.php */
1174 $permalink = array( $permalink, apply_filters( 'editable_slug', $post->post_name ) );
1175 $post->post_status = $original_status;
1176 $post->post_date = $original_date;
1177 $post->post_name = $original_name;
1178 unset($post->filter);
1184 * Returns the HTML of the sample permalink slug editor.
1188 * @param int $id Post ID or post object.
1189 * @param string $new_title Optional. New title. Default null.
1190 * @param string $new_slug Optional. New slug. Default null.
1191 * @return string The HTML of the sample permalink slug editor.
1193 function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1194 $post = get_post( $id );
1198 list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
1200 if ( current_user_can( 'read_post', $post->ID ) ) {
1201 $ptype = get_post_type_object( $post->post_type );
1202 $view_post = $ptype->labels->view_item;
1205 if ( 'publish' == get_post_status( $post ) ) {
1206 $title = __('Click to edit this part of the permalink');
1208 $title = __('Temporary permalink. Click to edit this part.');
1211 if ( false === strpos( $permalink, '%postname%' ) && false === strpos( $permalink, '%pagename%' ) ) {
1212 $return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink" tabindex="-1">' . $permalink . "</span>\n";
1213 if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) ) {
1214 $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
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, urldecode( $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";
1241 if ( isset( $view_post ) ) {
1242 if( 'draft' == $post->post_status ) {
1243 $preview_link = set_url_scheme( get_permalink( $post->ID ) );
1244 /** This filter is documented in wp-admin/includes/meta-boxes.php */
1245 $preview_link = apply_filters( 'preview_post_link', add_query_arg( 'preview', 'true', $preview_link ), $post );
1246 $return .= "<span id='view-post-btn'><a href='" . esc_url( $preview_link ) . "' class='button button-small' target='wp-preview-{$post->ID}'>$view_post</a></span>\n";
1248 $return .= "<span id='view-post-btn'><a href='" . get_permalink( $post ) . "' class='button button-small'>$view_post</a></span>\n";
1253 * Filter the sample permalink HTML markup.
1257 * @param string $return Sample permalink HTML markup.
1258 * @param int|WP_Post $id Post object or ID.
1259 * @param string $new_title New sample permalink title.
1260 * @param string $new_slug New sample permalink slug.
1262 $return = apply_filters( 'get_sample_permalink_html', $return, $id, $new_title, $new_slug );
1268 * Output HTML for the post thumbnail meta-box.
1272 * @param int $thumbnail_id ID of the attachment used for thumbnail
1273 * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post.
1274 * @return string html
1276 function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1277 global $content_width, $_wp_additional_image_sizes;
1279 $post = get_post( $post );
1281 $upload_iframe_src = esc_url( get_upload_iframe_src('image', $post->ID ) );
1282 $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>';
1283 $content = sprintf( $set_thumbnail_link, $upload_iframe_src, esc_html__( 'Set featured image' ) );
1285 if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1286 $old_content_width = $content_width;
1287 $content_width = 266;
1288 if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) )
1289 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
1291 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' );
1292 if ( !empty( $thumbnail_html ) ) {
1293 $ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
1294 $content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
1295 $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>';
1297 $content_width = $old_content_width;
1301 * Filter the admin post thumbnail HTML markup to return.
1305 * @param string $content Admin post thumbnail HTML markup.
1306 * @param int $post_id Post ID.
1308 return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID );
1312 * Check to see if the post is currently being edited by another user.
1316 * @param int $post_id ID of the post to check for editing
1317 * @return integer False: not locked or locked by current user. Int: user ID of user with lock.
1319 function wp_check_post_lock( $post_id ) {
1320 if ( !$post = get_post( $post_id ) )
1323 if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) )
1326 $lock = explode( ':', $lock );
1328 $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1330 /** This filter is documented in wp-admin/includes/ajax-actions.php */
1331 $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
1333 if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
1339 * Mark the post as currently being edited by the current user
1343 * @param int $post_id ID of the post to being edited
1344 * @return bool|array Returns false if the post doesn't exist of there is no current user, or
1345 * an array of the lock time and the user ID.
1347 function wp_set_post_lock( $post_id ) {
1348 if ( !$post = get_post( $post_id ) )
1350 if ( 0 == ($user_id = get_current_user_id()) )
1354 $lock = "$now:$user_id";
1356 update_post_meta( $post->ID, '_edit_lock', $lock );
1357 return array( $now, $user_id );
1361 * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
1366 function _admin_notice_post_locked() {
1367 if ( ! $post = get_post() )
1371 if ( $user_id = wp_check_post_lock( $post->ID ) )
1372 $user = get_userdata( $user_id );
1377 * Filter whether to show the post locked dialog.
1379 * Returning a falsey value to the filter will short-circuit displaying the dialog.
1383 * @param bool $display Whether to display the dialog. Default true.
1384 * @param WP_User|bool $user WP_User object on success, false otherwise.
1386 if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) )
1394 if ( $locked && ( $sendback = wp_get_referer() ) &&
1395 false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
1397 $sendback_text = __('Go back');
1399 $sendback = admin_url( 'edit.php' );
1401 if ( 'post' != $post->post_type )
1402 $sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
1404 $sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
1407 $hidden = $locked ? '' : ' hidden';
1410 <div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
1411 <div class="notification-dialog-background"></div>
1412 <div class="notification-dialog">
1416 if ( get_post_type_object( $post->post_type )->public ) {
1417 $preview_link = set_url_scheme( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) );
1419 if ( 'publish' == $post->post_status || $user->ID != $post->post_author ) {
1420 // Latest content is in autosave
1421 $nonce = wp_create_nonce( 'post_preview_' . $post->ID );
1422 $preview_link = add_query_arg( array( 'preview_id' => $post->ID, 'preview_nonce' => $nonce ), $preview_link );
1428 /** This filter is documented in wp-admin/includes/meta-boxes.php */
1429 $preview_link = apply_filters( 'preview_post_link', $preview_link, $post );
1432 * Filter whether to allow the post lock to be overridden.
1434 * Returning a falsey value to the filter will disable the ability
1435 * to override the post lock.
1439 * @param bool $override Whether to allow overriding post locks. Default true.
1440 * @param WP_Post $post Post object.
1441 * @param WP_User $user User object.
1443 $override = apply_filters( 'override_post_lock', true, $post, $user );
1444 $tab_last = $override ? '' : ' wp-tab-last';
1447 <div class="post-locked-message">
1448 <div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
1449 <p class="currently-editing wp-tab-first" tabindex="0">
1451 _e( 'This content is currently locked.' );
1453 printf( ' ' . __( 'If you take over, %s will be blocked from continuing to edit.' ), esc_html( $user->display_name ) );
1458 * Fires inside the post locked dialog before the buttons are displayed.
1462 * @param WP_Post $post Post object.
1464 do_action( 'post_locked_dialog', $post );
1467 <a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
1468 <?php if ( $preview_link ) { ?>
1469 <a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e('Preview'); ?></a>
1473 // Allow plugins to prevent some users overriding the post lock
1476 <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>
1486 <div class="post-taken-over">
1487 <div class="post-locked-avatar"></div>
1488 <p class="wp-tab-first" tabindex="0">
1489 <span class="currently-editing"></span><br />
1490 <span class="locked-saving hidden"><img src="images/wpspin_light-2x.gif" width="16" height="16" /> <?php _e('Saving revision...'); ?></span>
1491 <span class="locked-saved hidden"><?php _e('Your latest changes were saved as a revision.'); ?></span>
1495 * Fires inside the dialog displayed when a user has lost the post lock.
1499 * @param WP_Post $post Post object.
1501 do_action( 'post_lock_lost_dialog', $post );
1503 <p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
1515 * Creates autosave data for the specified post from $_POST data.
1517 * @package WordPress
1518 * @subpackage Post_Revisions
1521 * @param mixed $post_data Associative array containing the post data or int post ID.
1522 * @return mixed The autosave revision ID. WP_Error or 0 on error.
1524 function wp_create_post_autosave( $post_data ) {
1525 if ( is_numeric( $post_data ) ) {
1526 $post_id = $post_data;
1527 $post_data = &$_POST;
1529 $post_id = (int) $post_data['post_ID'];
1532 $post_data = _wp_translate_postdata( true, $post_data );
1533 if ( is_wp_error( $post_data ) )
1536 $post_author = get_current_user_id();
1538 // Store one autosave per author. If there is already an autosave, overwrite it.
1539 if ( $old_autosave = wp_get_post_autosave( $post_id, $post_author ) ) {
1540 $new_autosave = _wp_post_revision_fields( $post_data, true );
1541 $new_autosave['ID'] = $old_autosave->ID;
1542 $new_autosave['post_author'] = $post_author;
1544 // If the new autosave has the same content as the post, delete the autosave.
1545 $post = get_post( $post_id );
1546 $autosave_is_different = false;
1547 foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields() ) ) as $field ) {
1548 if ( normalize_whitespace( $new_autosave[ $field ] ) != normalize_whitespace( $post->$field ) ) {
1549 $autosave_is_different = true;
1554 if ( ! $autosave_is_different ) {
1555 wp_delete_post_revision( $old_autosave->ID );
1560 * Fires before an autosave is stored.
1564 * @param array $new_autosave Post array - the autosave that is about to be saved.
1566 do_action( 'wp_creating_autosave', $new_autosave );
1568 return wp_update_post( $new_autosave );
1571 // _wp_put_post_revision() expects unescaped.
1572 $post_data = wp_unslash( $post_data );
1574 // Otherwise create the new autosave as a special post revision
1575 return _wp_put_post_revision( $post_data, true );
1579 * Save draft or manually autosave for showing preview.
1581 * @package WordPress
1584 * @return str URL to redirect to show the preview
1586 function post_preview() {
1588 $post_ID = (int) $_POST['post_ID'];
1589 $_POST['ID'] = $post_ID;
1591 if ( ! $post = get_post( $post_ID ) ) {
1592 wp_die( __( 'You are not allowed to edit this post.' ) );
1595 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1596 wp_die( __( 'You are not allowed to edit this post.' ) );
1599 $is_autosave = false;
1601 if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'draft' == $post->post_status || 'auto-draft' == $post->post_status ) ) {
1602 $saved_post_id = edit_post();
1604 $is_autosave = true;
1606 if ( 'auto-draft' == $_POST['post_status'] )
1607 $_POST['post_status'] = 'draft';
1609 $saved_post_id = wp_create_post_autosave( $post->ID );
1612 if ( is_wp_error( $saved_post_id ) )
1613 wp_die( $saved_post_id->get_error_message() );
1615 $query_args = array( 'preview' => 'true' );
1617 if ( $is_autosave && $saved_post_id ) {
1618 $query_args['preview_id'] = $post->ID;
1619 $query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
1621 if ( isset( $_POST['post_format'] ) )
1622 $query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
1625 $url = add_query_arg( $query_args, get_permalink( $post->ID ) );
1627 /** This filter is documented in wp-admin/includes/meta-boxes.php */
1628 return apply_filters( 'preview_post_link', $url, $post );
1632 * Save a post submitted with XHR
1634 * Intended for use with heartbeat and autosave.js
1638 * @param array $post_data Associative array of the submitted post data.
1639 * @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
1640 * Te ID can be the draft post_id or the autosave revision post_id.
1642 function wp_autosave( $post_data ) {
1644 if ( ! defined( 'DOING_AUTOSAVE' ) )
1645 define( 'DOING_AUTOSAVE', true );
1647 $post_id = (int) $post_data['post_id'];
1648 $post_data['ID'] = $post_data['post_ID'] = $post_id;
1650 if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
1651 return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
1654 $post = get_post( $post_id );
1656 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1657 return new WP_Error( 'edit_posts', __( 'You are not allowed to edit this item.' ) );
1660 if ( 'auto-draft' == $post->post_status )
1661 $post_data['post_status'] = 'draft';
1663 if ( $post_data['post_type'] != 'page' && ! empty( $post_data['catslist'] ) )
1664 $post_data['post_category'] = explode( ',', $post_data['catslist'] );
1666 if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'auto-draft' == $post->post_status || 'draft' == $post->post_status ) ) {
1667 // Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked
1668 return edit_post( wp_slash( $post_data ) );
1670 // Non drafts or other users drafts are not overwritten. The autosave is stored in a special post revision for each user.
1671 return wp_create_post_autosave( wp_slash( $post_data ) );