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', __( 'Sorry, you are not allowed to edit pages as this user.' ) );
35 return new WP_Error( 'edit_others_posts', __( 'Sorry, 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', __( 'Sorry, you are not allowed to create pages as this user.' ) );
40 return new WP_Error( 'edit_others_posts', __( 'Sorry, 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', __( 'Sorry, you are not allowed to edit pages as this user.' ) );
73 return new WP_Error( 'edit_others_posts', __( 'Sorry, 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', __( 'Sorry, you are not allowed to create pages as this user.' ) );
78 return new WP_Error( 'edit_others_posts', __( 'Sorry, 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', __( 'Invalid date.' ) );
165 $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
168 if ( isset( $post_data['post_category'] ) ) {
169 $category_object = get_taxonomy( 'category' );
170 if ( ! current_user_can( $category_object->cap->assign_terms ) ) {
171 unset( $post_data['post_category'] );
179 * Update an existing post with values provided in $_POST.
183 * @global wpdb $wpdb WordPress database abstraction object.
185 * @param array $post_data Optional.
186 * @return int Post ID.
188 function edit_post( $post_data = null ) {
191 if ( empty($post_data) )
192 $post_data = &$_POST;
194 // Clear out any data in internal vars.
195 unset( $post_data['filter'] );
197 $post_ID = (int) $post_data['post_ID'];
198 $post = get_post( $post_ID );
199 $post_data['post_type'] = $post->post_type;
200 $post_data['post_mime_type'] = $post->post_mime_type;
202 if ( ! empty( $post_data['post_status'] ) ) {
203 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
205 if ( 'inherit' == $post_data['post_status'] ) {
206 unset( $post_data['post_status'] );
210 $ptype = get_post_type_object($post_data['post_type']);
211 if ( !current_user_can( 'edit_post', $post_ID ) ) {
212 if ( 'page' == $post_data['post_type'] )
213 wp_die( __('Sorry, you are not allowed to edit this page.' ));
215 wp_die( __('Sorry, you are not allowed to edit this post.' ));
218 if ( post_type_supports( $ptype->name, 'revisions' ) ) {
219 $revisions = wp_get_post_revisions( $post_ID, array( 'order' => 'ASC', 'posts_per_page' => 1 ) );
220 $revision = current( $revisions );
222 // Check if the revisions have been upgraded
223 if ( $revisions && _wp_get_post_revision_version( $revision ) < 1 )
224 _wp_upgrade_revisions_of_post( $post, wp_get_post_revisions( $post_ID ) );
227 if ( isset($post_data['visibility']) ) {
228 switch ( $post_data['visibility'] ) {
230 $post_data['post_password'] = '';
233 unset( $post_data['sticky'] );
236 $post_data['post_status'] = 'private';
237 $post_data['post_password'] = '';
238 unset( $post_data['sticky'] );
243 $post_data = _wp_translate_postdata( true, $post_data );
244 if ( is_wp_error($post_data) )
245 wp_die( $post_data->get_error_message() );
248 if ( isset( $post_data['post_format'] ) )
249 set_post_format( $post_ID, $post_data['post_format'] );
251 $format_meta_urls = array( 'url', 'link_url', 'quote_source_url' );
252 foreach ( $format_meta_urls as $format_meta_url ) {
253 $keyed = '_format_' . $format_meta_url;
254 if ( isset( $post_data[ $keyed ] ) )
255 update_post_meta( $post_ID, $keyed, wp_slash( esc_url_raw( wp_unslash( $post_data[ $keyed ] ) ) ) );
258 $format_keys = array( 'quote', 'quote_source_name', 'image', 'gallery', 'audio_embed', 'video_embed' );
260 foreach ( $format_keys as $key ) {
261 $keyed = '_format_' . $key;
262 if ( isset( $post_data[ $keyed ] ) ) {
263 if ( current_user_can( 'unfiltered_html' ) )
264 update_post_meta( $post_ID, $keyed, $post_data[ $keyed ] );
266 update_post_meta( $post_ID, $keyed, wp_filter_post_kses( $post_data[ $keyed ] ) );
270 if ( 'attachment' === $post_data['post_type'] && preg_match( '#^(audio|video)/#', $post_data['post_mime_type'] ) ) {
271 $id3data = wp_get_attachment_metadata( $post_ID );
272 if ( ! is_array( $id3data ) ) {
276 foreach ( wp_get_attachment_id3_keys( $post, 'edit' ) as $key => $label ) {
277 if ( isset( $post_data[ 'id3_' . $key ] ) ) {
278 $id3data[ $key ] = sanitize_text_field( wp_unslash( $post_data[ 'id3_' . $key ] ) );
281 wp_update_attachment_metadata( $post_ID, $id3data );
285 if ( isset($post_data['meta']) && $post_data['meta'] ) {
286 foreach ( $post_data['meta'] as $key => $value ) {
287 if ( !$meta = get_post_meta_by_id( $key ) )
289 if ( $meta->post_id != $post_ID )
291 if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $meta->meta_key ) )
293 if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
295 update_meta( $key, $value['key'], $value['value'] );
299 if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
300 foreach ( $post_data['deletemeta'] as $key => $value ) {
301 if ( !$meta = get_post_meta_by_id( $key ) )
303 if ( $meta->post_id != $post_ID )
305 if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
312 if ( 'attachment' == $post_data['post_type'] ) {
313 if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
314 $image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
315 if ( $image_alt != get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) ) {
316 $image_alt = wp_strip_all_tags( $image_alt, true );
317 // update_meta expects slashed.
318 update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
322 $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
324 /** This filter is documented in wp-admin/includes/media.php */
325 $post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
328 // Convert taxonomy input to term IDs, to avoid ambiguity.
329 if ( isset( $post_data['tax_input'] ) ) {
330 foreach ( (array) $post_data['tax_input'] as $taxonomy => $terms ) {
331 // Hierarchical taxonomy data is already sent as term IDs, so no conversion is necessary.
332 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
337 * Assume that a 'tax_input' string is a comma-separated list of term names.
338 * Some languages may use a character other than a comma as a delimiter, so we standardize on
339 * commas before parsing the list.
341 if ( ! is_array( $terms ) ) {
342 $comma = _x( ',', 'tag delimiter' );
343 if ( ',' !== $comma ) {
344 $terms = str_replace( $comma, ',', $terms );
346 $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
349 $clean_terms = array();
350 foreach ( $terms as $term ) {
351 // Empty terms are invalid input.
352 if ( empty( $term ) ) {
356 $_term = get_terms( $taxonomy, array(
359 'hide_empty' => false,
362 if ( ! empty( $_term ) ) {
363 $clean_terms[] = intval( $_term[0] );
365 // No existing term was found, so pass the string. A new term will be created.
366 $clean_terms[] = $term;
370 $post_data['tax_input'][ $taxonomy ] = $clean_terms;
374 add_meta( $post_ID );
376 update_post_meta( $post_ID, '_edit_last', get_current_user_id() );
378 $success = wp_update_post( $post_data );
379 // If the save failed, see if we can sanity check the main fields and try again
380 if ( ! $success && is_callable( array( $wpdb, 'strip_invalid_text_for_column' ) ) ) {
381 $fields = array( 'post_title', 'post_content', 'post_excerpt' );
383 foreach ( $fields as $field ) {
384 if ( isset( $post_data[ $field ] ) ) {
385 $post_data[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->posts, $field, $post_data[ $field ] );
389 wp_update_post( $post_data );
392 // Now that we have an ID we can fix any attachment anchor hrefs
393 _fix_attachment_links( $post_ID );
395 wp_set_post_lock( $post_ID );
397 if ( current_user_can( $ptype->cap->edit_others_posts ) && current_user_can( $ptype->cap->publish_posts ) ) {
398 if ( ! empty( $post_data['sticky'] ) )
399 stick_post( $post_ID );
401 unstick_post( $post_ID );
408 * Process the post data for the bulk editing of posts.
410 * Updates all bulk edited posts/pages, adding (but not removing) tags and
411 * categories. Skips pages when they would be their own parent or child.
415 * @global wpdb $wpdb WordPress database abstraction object.
417 * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
420 function bulk_edit_posts( $post_data = null ) {
423 if ( empty($post_data) )
424 $post_data = &$_POST;
426 if ( isset($post_data['post_type']) )
427 $ptype = get_post_type_object($post_data['post_type']);
429 $ptype = get_post_type_object('post');
431 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
432 if ( 'page' == $ptype->name )
433 wp_die( __('Sorry, you are not allowed to edit pages.'));
435 wp_die( __('Sorry, you are not allowed to edit posts.'));
438 if ( -1 == $post_data['_status'] ) {
439 $post_data['post_status'] = null;
440 unset($post_data['post_status']);
442 $post_data['post_status'] = $post_data['_status'];
444 unset($post_data['_status']);
446 if ( ! empty( $post_data['post_status'] ) ) {
447 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
449 if ( 'inherit' == $post_data['post_status'] ) {
450 unset( $post_data['post_status'] );
454 $post_IDs = array_map( 'intval', (array) $post_data['post'] );
457 'post_author', 'post_status', 'post_password',
458 'post_parent', 'page_template', 'comment_status',
459 'ping_status', 'keep_private', 'tax_input',
460 'post_category', 'sticky', 'post_format',
463 foreach ( $reset as $field ) {
464 if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
465 unset($post_data[$field]);
468 if ( isset($post_data['post_category']) ) {
469 if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
470 $new_cats = array_map( 'absint', $post_data['post_category'] );
472 unset($post_data['post_category']);
475 $tax_input = array();
476 if ( isset($post_data['tax_input'])) {
477 foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
480 if ( is_taxonomy_hierarchical( $tax_name ) ) {
481 $tax_input[ $tax_name ] = array_map( 'absint', $terms );
483 $comma = _x( ',', 'tag delimiter' );
484 if ( ',' !== $comma )
485 $terms = str_replace( $comma, ',', $terms );
486 $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
491 if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
492 $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
495 for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
496 $children[] = $parent;
498 foreach ( $pages as $page ) {
499 if ( $page->ID == $parent ) {
500 $parent = $page->post_parent;
507 $updated = $skipped = $locked = array();
508 $shared_post_data = $post_data;
510 foreach ( $post_IDs as $post_ID ) {
511 // Start with fresh post data with each iteration.
512 $post_data = $shared_post_data;
514 $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
516 if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( 'edit_post', $post_ID ) ) {
517 $skipped[] = $post_ID;
521 if ( wp_check_post_lock( $post_ID ) ) {
522 $locked[] = $post_ID;
526 $post = get_post( $post_ID );
527 $tax_names = get_object_taxonomies( $post );
528 foreach ( $tax_names as $tax_name ) {
529 $taxonomy_obj = get_taxonomy($tax_name);
530 if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
531 $new_terms = $tax_input[$tax_name];
533 $new_terms = array();
535 if ( $taxonomy_obj->hierarchical )
536 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
538 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
540 $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
543 if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
544 $cats = (array) wp_get_post_categories($post_ID);
545 $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
546 unset( $post_data['tax_input']['category'] );
549 $post_data['post_type'] = $post->post_type;
550 $post_data['post_mime_type'] = $post->post_mime_type;
551 $post_data['guid'] = $post->guid;
553 foreach ( array( 'comment_status', 'ping_status', 'post_author' ) as $field ) {
554 if ( ! isset( $post_data[ $field ] ) ) {
555 $post_data[ $field ] = $post->$field;
559 $post_data['ID'] = $post_ID;
560 $post_data['post_ID'] = $post_ID;
562 $post_data = _wp_translate_postdata( true, $post_data );
563 if ( is_wp_error( $post_data ) ) {
564 $skipped[] = $post_ID;
568 $updated[] = wp_update_post( $post_data );
570 if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
571 if ( 'sticky' == $post_data['sticky'] )
572 stick_post( $post_ID );
574 unstick_post( $post_ID );
577 if ( isset( $post_data['post_format'] ) )
578 set_post_format( $post_ID, $post_data['post_format'] );
581 return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
585 * Default post information to use when populating the "Write Post" form.
589 * @param string $post_type Optional. A post type string. Default 'post'.
590 * @param bool $create_in_db Optional. Whether to insert the post into database. Default false.
591 * @return WP_Post Post object containing all the default post data as attributes
593 function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
595 if ( !empty( $_REQUEST['post_title'] ) )
596 $post_title = esc_html( wp_unslash( $_REQUEST['post_title'] ));
599 if ( !empty( $_REQUEST['content'] ) )
600 $post_content = esc_html( wp_unslash( $_REQUEST['content'] ));
603 if ( !empty( $_REQUEST['excerpt'] ) )
604 $post_excerpt = esc_html( wp_unslash( $_REQUEST['excerpt'] ));
606 if ( $create_in_db ) {
607 $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
608 $post = get_post( $post_id );
609 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
610 set_post_format( $post, get_option( 'default_post_format' ) );
612 $post = new stdClass;
614 $post->post_author = '';
615 $post->post_date = '';
616 $post->post_date_gmt = '';
617 $post->post_password = '';
618 $post->post_name = '';
619 $post->post_type = $post_type;
620 $post->post_status = 'draft';
623 $post->comment_status = get_default_comment_status( $post_type );
624 $post->ping_status = get_default_comment_status( $post_type, 'pingback' );
625 $post->post_pingback = get_option( 'default_pingback_flag' );
626 $post->post_category = get_option( 'default_category' );
627 $post->page_template = 'default';
628 $post->post_parent = 0;
629 $post->menu_order = 0;
630 $post = new WP_Post( $post );
634 * Filters the default post content initially used in the "Write Post" form.
638 * @param string $post_content Default post content.
639 * @param WP_Post $post Post object.
641 $post->post_content = apply_filters( 'default_content', $post_content, $post );
644 * Filters the default post title initially used in the "Write Post" form.
648 * @param string $post_title Default post title.
649 * @param WP_Post $post Post object.
651 $post->post_title = apply_filters( 'default_title', $post_title, $post );
654 * Filters the default post excerpt initially used in the "Write Post" form.
658 * @param string $post_excerpt Default post excerpt.
659 * @param WP_Post $post Post object.
661 $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
667 * Determine if a post exists based on title, content, and date
671 * @global wpdb $wpdb WordPress database abstraction object.
673 * @param string $title Post title
674 * @param string $content Optional post content
675 * @param string $date Optional post date
676 * @return int Post ID if post exists, 0 otherwise.
678 function post_exists($title, $content = '', $date = '') {
681 $post_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
682 $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
683 $post_date = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
685 $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
688 if ( !empty ( $date ) ) {
689 $query .= ' AND post_date = %s';
690 $args[] = $post_date;
693 if ( !empty ( $title ) ) {
694 $query .= ' AND post_title = %s';
695 $args[] = $post_title;
698 if ( !empty ( $content ) ) {
699 $query .= ' AND post_content = %s';
700 $args[] = $post_content;
703 if ( !empty ( $args ) )
704 return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
710 * Creates a new post from the "Write Post" form using $_POST information.
714 * @global WP_User $current_user
716 * @return int|WP_Error
718 function wp_write_post() {
719 if ( isset($_POST['post_type']) )
720 $ptype = get_post_type_object($_POST['post_type']);
722 $ptype = get_post_type_object('post');
724 if ( !current_user_can( $ptype->cap->edit_posts ) ) {
725 if ( 'page' == $ptype->name )
726 return new WP_Error( 'edit_pages', __( 'Sorry, you are not allowed to create pages on this site.' ) );
728 return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to create posts or drafts on this site.' ) );
731 $_POST['post_mime_type'] = '';
733 // Clear out any data in internal vars.
734 unset( $_POST['filter'] );
736 // Edit don't write if we have a post id.
737 if ( isset( $_POST['post_ID'] ) )
740 if ( isset($_POST['visibility']) ) {
741 switch ( $_POST['visibility'] ) {
743 $_POST['post_password'] = '';
746 unset( $_POST['sticky'] );
749 $_POST['post_status'] = 'private';
750 $_POST['post_password'] = '';
751 unset( $_POST['sticky'] );
756 $translated = _wp_translate_postdata( false );
757 if ( is_wp_error($translated) )
761 $post_ID = wp_insert_post( $_POST );
762 if ( is_wp_error( $post_ID ) )
765 if ( empty($post_ID) )
768 add_meta( $post_ID );
770 add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
772 // Now that we have an ID we can fix any attachment anchor hrefs
773 _fix_attachment_links( $post_ID );
775 wp_set_post_lock( $post_ID );
781 * Calls wp_write_post() and handles the errors.
787 function write_post() {
788 $result = wp_write_post();
789 if ( is_wp_error( $result ) )
790 wp_die( $result->get_error_message() );
800 * Add post meta data defined in $_POST superglobal for post with given ID.
804 * @param int $post_ID
807 function add_meta( $post_ID ) {
808 $post_ID = (int) $post_ID;
810 $metakeyselect = isset($_POST['metakeyselect']) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
811 $metakeyinput = isset($_POST['metakeyinput']) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
812 $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
813 if ( is_string( $metavalue ) )
814 $metavalue = trim( $metavalue );
816 if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
818 * We have a key/value pair. If both the select and the input
819 * for the key have data, the input takes precedence.
821 if ( '#NONE#' != $metakeyselect )
822 $metakey = $metakeyselect;
825 $metakey = $metakeyinput; // default
827 if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
830 $metakey = wp_slash( $metakey );
832 return add_post_meta( $post_ID, $metakey, $metavalue );
839 * Delete post meta data by meta ID.
846 function delete_meta( $mid ) {
847 return delete_metadata_by_mid( 'post' , $mid );
851 * Get a list of previously defined keys.
855 * @global wpdb $wpdb WordPress database abstraction object.
859 function get_meta_keys() {
862 $keys = $wpdb->get_col( "
866 ORDER BY meta_key" );
872 * Get post meta data by meta ID.
877 * @return object|bool
879 function get_post_meta_by_id( $mid ) {
880 return get_metadata_by_mid( 'post', $mid );
884 * Get meta data for the given post ID.
888 * @global wpdb $wpdb WordPress database abstraction object.
893 function has_meta( $postid ) {
896 return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
897 FROM $wpdb->postmeta WHERE post_id = %d
898 ORDER BY meta_key,meta_id", $postid), ARRAY_A );
902 * Update post meta data by meta ID.
906 * @param int $meta_id
907 * @param string $meta_key Expect Slashed
908 * @param string $meta_value Expect Slashed
911 function update_meta( $meta_id, $meta_key, $meta_value ) {
912 $meta_key = wp_unslash( $meta_key );
913 $meta_value = wp_unslash( $meta_value );
915 return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
923 * Replace hrefs of attachment anchors with up-to-date permalinks.
928 * @param int|object $post Post ID or post object.
929 * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
931 function _fix_attachment_links( $post ) {
932 $post = get_post( $post, ARRAY_A );
933 $content = $post['post_content'];
935 // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
936 if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ) ) )
939 // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero)
940 if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) )
943 $site_url = get_bloginfo('url');
944 $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s)
947 foreach ( $link_matches[1] as $key => $value ) {
948 if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-')
949 || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
950 || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) )
953 $quote = $url_match[1]; // the quote (single or double)
954 $url_id = (int) $url_match[2];
955 $rel_id = (int) $rel_match[1];
957 if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false )
960 $link = $link_matches[0][$key];
961 $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
963 $content = str_replace( $link, $replace, $content );
967 $post['post_content'] = $content;
968 // Escape data pulled from DB.
969 $post = add_magic_quotes($post);
971 return wp_update_post($post);
976 * Get all the possible statuses for a post_type
980 * @param string $type The post_type you want the statuses for
981 * @return array As array of all the statuses for the supplied post type
983 function get_available_post_statuses($type = 'post') {
984 $stati = wp_count_posts($type);
986 return array_keys(get_object_vars($stati));
990 * Run the wp query to fetch the posts for listing on the edit posts page
994 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
997 function wp_edit_posts_query( $q = false ) {
1000 $q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
1001 $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
1002 $post_stati = get_post_stati();
1004 if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
1005 $post_type = $q['post_type'];
1007 $post_type = 'post';
1009 $avail_post_stati = get_available_post_statuses($post_type);
1011 if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
1012 $post_status = $q['post_status'];
1016 if ( isset( $q['orderby'] ) ) {
1017 $orderby = $q['orderby'];
1018 } elseif ( isset( $q['post_status'] ) && in_array( $q['post_status'], array( 'pending', 'draft' ) ) ) {
1019 $orderby = 'modified';
1022 if ( isset( $q['order'] ) ) {
1023 $order = $q['order'];
1024 } elseif ( isset( $q['post_status'] ) && 'pending' == $q['post_status'] ) {
1028 $per_page = "edit_{$post_type}_per_page";
1029 $posts_per_page = (int) get_user_option( $per_page );
1030 if ( empty( $posts_per_page ) || $posts_per_page < 1 )
1031 $posts_per_page = 20;
1034 * Filters the number of items per page to show for a specific 'per_page' type.
1036 * The dynamic portion of the hook name, `$post_type`, refers to the post type.
1038 * Some examples of filter hooks generated here include: 'edit_attachment_per_page',
1039 * 'edit_post_per_page', 'edit_page_per_page', etc.
1043 * @param int $posts_per_page Number of posts to display per page for the given post
1046 $posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
1049 * Filters the number of posts displayed per page when specifically listing "posts".
1053 * @param int $posts_per_page Number of posts to be displayed. Default 20.
1054 * @param string $post_type The post type.
1056 $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
1058 $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
1060 // Hierarchical types require special args.
1061 if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
1062 $query['orderby'] = 'menu_order title';
1063 $query['order'] = 'asc';
1064 $query['posts_per_page'] = -1;
1065 $query['posts_per_archive_page'] = -1;
1066 $query['fields'] = 'id=>parent';
1069 if ( ! empty( $q['show_sticky'] ) )
1070 $query['post__in'] = (array) get_option( 'sticky_posts' );
1074 return $avail_post_stati;
1078 * Get all available post MIME types for a given post type.
1082 * @global wpdb $wpdb WordPress database abstraction object.
1084 * @param string $type
1087 function get_available_post_mime_types($type = 'attachment') {
1090 $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
1095 * Get the query variables for the current attachments request.
1099 * @param array|false $q Optional. Array of query variables to use to build the query or false
1100 * to use $_GET superglobal. Default false.
1101 * @return array The parsed query vars.
1103 function wp_edit_attachments_query_vars( $q = false ) {
1104 if ( false === $q ) {
1107 $q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0;
1108 $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1109 $q['post_type'] = 'attachment';
1110 $post_type = get_post_type_object( 'attachment' );
1111 $states = 'inherit';
1112 if ( current_user_can( $post_type->cap->read_private_posts ) ) {
1113 $states .= ',private';
1116 $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
1117 $q['post_status'] = isset( $q['attachment-filter'] ) && 'trash' == $q['attachment-filter'] ? 'trash' : $states;
1119 $media_per_page = (int) get_user_option( 'upload_per_page' );
1120 if ( empty( $media_per_page ) || $media_per_page < 1 ) {
1121 $media_per_page = 20;
1125 * Filters the number of items to list per page when listing media items.
1129 * @param int $media_per_page Number of media to list. Default 20.
1131 $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
1133 $post_mime_types = get_post_mime_types();
1134 if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) ) {
1135 unset($q['post_mime_type']);
1138 foreach ( array_keys( $post_mime_types ) as $type ) {
1139 if ( isset( $q['attachment-filter'] ) && "post_mime_type:$type" == $q['attachment-filter'] ) {
1140 $q['post_mime_type'] = $type;
1145 if ( isset( $q['detached'] ) || ( isset( $q['attachment-filter'] ) && 'detached' == $q['attachment-filter'] ) ) {
1146 $q['post_parent'] = 0;
1149 // Filter query clauses to include filenames.
1150 if ( isset( $q['s'] ) ) {
1151 add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
1158 * Executes a query for attachments. An array of WP_Query arguments
1159 * can be passed in, which will override the arguments set by this function.
1163 * @param array|false $q Array of query variables to use to build the query or false to use $_GET superglobal.
1166 function wp_edit_attachments_query( $q = false ) {
1167 wp( wp_edit_attachments_query_vars( $q ) );
1169 $post_mime_types = get_post_mime_types();
1170 $avail_post_mime_types = get_available_post_mime_types( 'attachment' );
1172 return array( $post_mime_types, $avail_post_mime_types );
1176 * Returns the list of classes to be used by a meta box.
1181 * @param string $page
1184 function postbox_classes( $id, $page ) {
1185 if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
1186 $classes = array( '' );
1187 } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
1188 if ( !is_array( $closed ) ) {
1189 $classes = array( '' );
1191 $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
1194 $classes = array( '' );
1198 * Filters the postbox classes for a specific screen and screen ID combo.
1200 * The dynamic portions of the hook name, `$page` and `$id`, refer to
1201 * the screen and screen ID, respectively.
1205 * @param array $classes An array of postbox classes.
1207 $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
1208 return implode( ' ', $classes );
1212 * Get a sample permalink based off of the post name.
1216 * @param int $id Post ID or post object.
1217 * @param string $title Optional. Title to override the post's current title when generating the post name. Default null.
1218 * @param string $name Optional. Name to override the post name. Default null.
1219 * @return array Array containing the sample permalink with placeholder for the post name, and the post name.
1221 function get_sample_permalink($id, $title = null, $name = null) {
1222 $post = get_post( $id );
1224 return array( '', '' );
1226 $ptype = get_post_type_object($post->post_type);
1228 $original_status = $post->post_status;
1229 $original_date = $post->post_date;
1230 $original_name = $post->post_name;
1232 // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
1233 if ( in_array( $post->post_status, array( 'draft', 'pending', 'future' ) ) ) {
1234 $post->post_status = 'publish';
1235 $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
1238 // If the user wants to set a new name -- override the current one
1239 // Note: if empty name is supplied -- use the title instead, see #6072
1240 if ( !is_null($name) )
1241 $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
1243 $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
1245 $post->filter = 'sample';
1247 $permalink = get_permalink($post, true);
1249 // Replace custom post_type Token with generic pagename token for ease of use.
1250 $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
1252 // Handle page hierarchy
1253 if ( $ptype->hierarchical ) {
1254 $uri = get_page_uri($post);
1256 $uri = untrailingslashit($uri);
1257 $uri = strrev( stristr( strrev( $uri ), '/' ) );
1258 $uri = untrailingslashit($uri);
1261 /** This filter is documented in wp-admin/edit-tag-form.php */
1262 $uri = apply_filters( 'editable_slug', $uri, $post );
1265 $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
1268 /** This filter is documented in wp-admin/edit-tag-form.php */
1269 $permalink = array( $permalink, apply_filters( 'editable_slug', $post->post_name, $post ) );
1270 $post->post_status = $original_status;
1271 $post->post_date = $original_date;
1272 $post->post_name = $original_name;
1273 unset($post->filter);
1276 * Filters the sample permalink.
1280 * @param array $permalink Array containing the sample permalink with placeholder for the post name, and the post name.
1281 * @param int $post_id Post ID.
1282 * @param string $title Post title.
1283 * @param string $name Post name (slug).
1284 * @param WP_Post $post Post object.
1286 return apply_filters( 'get_sample_permalink', $permalink, $post->ID, $title, $name, $post );
1290 * Returns the HTML of the sample permalink slug editor.
1294 * @param int $id Post ID or post object.
1295 * @param string $new_title Optional. New title. Default null.
1296 * @param string $new_slug Optional. New slug. Default null.
1297 * @return string The HTML of the sample permalink slug editor.
1299 function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1300 $post = get_post( $id );
1304 list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
1307 $preview_target = '';
1309 if ( current_user_can( 'read_post', $post->ID ) ) {
1310 if ( 'draft' === $post->post_status || empty( $post->post_name ) ) {
1311 $view_link = get_preview_post_link( $post );
1312 $preview_target = " target='wp-preview-{$post->ID}'";
1314 if ( 'publish' === $post->post_status || 'attachment' === $post->post_type ) {
1315 $view_link = get_permalink( $post );
1317 // Allow non-published (private, future) to be viewed at a pretty permalink, in case $post->post_name is set
1318 $view_link = str_replace( array( '%pagename%', '%postname%' ), $post->post_name, $permalink );
1323 // Permalinks without a post/page name placeholder don't have anything to edit
1324 if ( false === strpos( $permalink, '%postname%' ) && false === strpos( $permalink, '%pagename%' ) ) {
1325 $return = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1327 if ( false !== $view_link ) {
1328 $display_link = urldecode( $view_link );
1329 $return .= '<a id="sample-permalink" href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . esc_html( $display_link ) . "</a>\n";
1331 $return .= '<span id="sample-permalink">' . $permalink . "</span>\n";
1334 // Encourage a pretty permalink setting
1335 if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) ) {
1336 $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
1339 if ( mb_strlen( $post_name ) > 34 ) {
1340 $post_name_abridged = mb_substr( $post_name, 0, 16 ) . '…' . mb_substr( $post_name, -16 );
1342 $post_name_abridged = $post_name;
1345 $post_name_html = '<span id="editable-post-name">' . esc_html( $post_name_abridged ) . '</span>';
1346 $display_link = str_replace( array( '%pagename%', '%postname%' ), $post_name_html, esc_html( urldecode( $permalink ) ) );
1348 $return = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1349 $return .= '<span id="sample-permalink"><a href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . $display_link . "</a></span>\n";
1350 $return .= '‎'; // Fix bi-directional text display defect in RTL languages.
1351 $return .= '<span id="edit-slug-buttons"><button type="button" class="edit-slug button button-small hide-if-no-js" aria-label="' . __( 'Edit permalink' ) . '">' . __( 'Edit' ) . "</button></span>\n";
1352 $return .= '<span id="editable-post-name-full">' . esc_html( $post_name ) . "</span>\n";
1356 * Filters the sample permalink HTML markup.
1359 * @since 4.4.0 Added `$post` parameter.
1361 * @param string $return Sample permalink HTML markup.
1362 * @param int $post_id Post ID.
1363 * @param string $new_title New sample permalink title.
1364 * @param string $new_slug New sample permalink slug.
1365 * @param WP_Post $post Post object.
1367 $return = apply_filters( 'get_sample_permalink_html', $return, $post->ID, $new_title, $new_slug, $post );
1373 * Output HTML for the post thumbnail meta-box.
1377 * @param int $thumbnail_id ID of the attachment used for thumbnail
1378 * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post.
1379 * @return string html
1381 function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1382 $_wp_additional_image_sizes = wp_get_additional_image_sizes();
1384 $post = get_post( $post );
1385 $post_type_object = get_post_type_object( $post->post_type );
1386 $set_thumbnail_link = '<p class="hide-if-no-js"><a href="%s" id="set-post-thumbnail"%s class="thickbox">%s</a></p>';
1387 $upload_iframe_src = get_upload_iframe_src( 'image', $post->ID );
1389 $content = sprintf( $set_thumbnail_link,
1390 esc_url( $upload_iframe_src ),
1391 '', // Empty when there's no featured image set, `aria-describedby` attribute otherwise.
1392 esc_html( $post_type_object->labels->set_featured_image )
1395 if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1396 $size = isset( $_wp_additional_image_sizes['post-thumbnail'] ) ? 'post-thumbnail' : array( 266, 266 );
1399 * Filters the size used to display the post thumbnail image in the 'Featured Image' meta box.
1401 * Note: When a theme adds 'post-thumbnail' support, a special 'post-thumbnail'
1402 * image size is registered, which differs from the 'thumbnail' image size
1403 * managed via the Settings > Media screen. See the `$size` parameter description
1404 * for more information on default values.
1408 * @param string|array $size Post thumbnail image size to display in the meta box. Accepts any valid
1409 * image size, or an array of width and height values in pixels (in that order).
1410 * If the 'post-thumbnail' size is set, default is 'post-thumbnail'. Otherwise,
1411 * default is an array with 266 as both the height and width values.
1412 * @param int $thumbnail_id Post thumbnail attachment ID.
1413 * @param WP_Post $post The post object associated with the thumbnail.
1415 $size = apply_filters( 'admin_post_thumbnail_size', $size, $thumbnail_id, $post );
1417 $thumbnail_html = wp_get_attachment_image( $thumbnail_id, $size );
1419 if ( ! empty( $thumbnail_html ) ) {
1420 $content = sprintf( $set_thumbnail_link,
1421 esc_url( $upload_iframe_src ),
1422 ' aria-describedby="set-post-thumbnail-desc"',
1425 $content .= '<p class="hide-if-no-js howto" id="set-post-thumbnail-desc">' . __( 'Click the image to edit or update' ) . '</p>';
1426 $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail">' . esc_html( $post_type_object->labels->remove_featured_image ) . '</a></p>';
1430 $content .= '<input type="hidden" id="_thumbnail_id" name="_thumbnail_id" value="' . esc_attr( $thumbnail_id ? $thumbnail_id : '-1' ) . '" />';
1433 * Filters the admin post thumbnail HTML markup to return.
1436 * @since 3.5.0 Added the `$post_id` parameter.
1437 * @since 4.6.0 Added the `$thumbnail_id` parameter.
1439 * @param string $content Admin post thumbnail HTML markup.
1440 * @param int $post_id Post ID.
1441 * @param int $thumbnail_id Thumbnail ID.
1443 return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
1447 * Check to see if the post is currently being edited by another user.
1451 * @param int $post_id ID of the post to check for editing
1452 * @return integer False: not locked or locked by current user. Int: user ID of user with lock.
1454 function wp_check_post_lock( $post_id ) {
1455 if ( !$post = get_post( $post_id ) )
1458 if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) )
1461 $lock = explode( ':', $lock );
1463 $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1465 /** This filter is documented in wp-admin/includes/ajax-actions.php */
1466 $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
1468 if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
1474 * Mark the post as currently being edited by the current user
1478 * @param int $post_id ID of the post to being edited
1479 * @return bool|array Returns false if the post doesn't exist of there is no current user, or
1480 * an array of the lock time and the user ID.
1482 function wp_set_post_lock( $post_id ) {
1483 if ( !$post = get_post( $post_id ) )
1485 if ( 0 == ($user_id = get_current_user_id()) )
1489 $lock = "$now:$user_id";
1491 update_post_meta( $post->ID, '_edit_lock', $lock );
1492 return array( $now, $user_id );
1496 * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
1501 function _admin_notice_post_locked() {
1502 if ( ! $post = get_post() )
1506 if ( $user_id = wp_check_post_lock( $post->ID ) )
1507 $user = get_userdata( $user_id );
1512 * Filters whether to show the post locked dialog.
1514 * Returning a falsey value to the filter will short-circuit displaying the dialog.
1518 * @param bool $display Whether to display the dialog. Default true.
1519 * @param WP_User|bool $user WP_User object on success, false otherwise.
1521 if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) )
1529 if ( $locked && ( $sendback = wp_get_referer() ) &&
1530 false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
1532 $sendback_text = __('Go back');
1534 $sendback = admin_url( 'edit.php' );
1536 if ( 'post' != $post->post_type )
1537 $sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
1539 $sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
1542 $hidden = $locked ? '' : ' hidden';
1545 <div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
1546 <div class="notification-dialog-background"></div>
1547 <div class="notification-dialog">
1551 $query_args = array();
1552 if ( get_post_type_object( $post->post_type )->public ) {
1553 if ( 'publish' == $post->post_status || $user->ID != $post->post_author ) {
1554 // Latest content is in autosave
1555 $nonce = wp_create_nonce( 'post_preview_' . $post->ID );
1556 $query_args['preview_id'] = $post->ID;
1557 $query_args['preview_nonce'] = $nonce;
1561 $preview_link = get_preview_post_link( $post->ID, $query_args );
1564 * Filters whether to allow the post lock to be overridden.
1566 * Returning a falsey value to the filter will disable the ability
1567 * to override the post lock.
1571 * @param bool $override Whether to allow overriding post locks. Default true.
1572 * @param WP_Post $post Post object.
1573 * @param WP_User $user User object.
1575 $override = apply_filters( 'override_post_lock', true, $post, $user );
1576 $tab_last = $override ? '' : ' wp-tab-last';
1579 <div class="post-locked-message">
1580 <div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
1581 <p class="currently-editing wp-tab-first" tabindex="0">
1583 _e( 'This content is currently locked.' );
1585 printf( ' ' . __( 'If you take over, %s will be blocked from continuing to edit.' ), esc_html( $user->display_name ) );
1590 * Fires inside the post locked dialog before the buttons are displayed.
1594 * @param WP_Post $post Post object.
1596 do_action( 'post_locked_dialog', $post );
1599 <a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
1600 <?php if ( $preview_link ) { ?>
1601 <a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e('Preview'); ?></a>
1605 // Allow plugins to prevent some users overriding the post lock
1608 <a class="button button-primary wp-tab-last" href="<?php echo esc_url( add_query_arg( 'get-post-lock', '1', wp_nonce_url( get_edit_post_link( $post->ID, 'url' ), 'lock-post_' . $post->ID ) ) ); ?>"><?php _e('Take over'); ?></a>
1618 <div class="post-taken-over">
1619 <div class="post-locked-avatar"></div>
1620 <p class="wp-tab-first" tabindex="0">
1621 <span class="currently-editing"></span><br />
1622 <span class="locked-saving hidden"><img src="<?php echo esc_url( admin_url( 'images/spinner-2x.gif' ) ); ?>" width="16" height="16" alt="" /> <?php _e( 'Saving revision…' ); ?></span>
1623 <span class="locked-saved hidden"><?php _e('Your latest changes were saved as a revision.'); ?></span>
1627 * Fires inside the dialog displayed when a user has lost the post lock.
1631 * @param WP_Post $post Post object.
1633 do_action( 'post_lock_lost_dialog', $post );
1635 <p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
1647 * Creates autosave data for the specified post from $_POST data.
1649 * @package WordPress
1650 * @subpackage Post_Revisions
1653 * @param mixed $post_data Associative array containing the post data or int post ID.
1654 * @return mixed The autosave revision ID. WP_Error or 0 on error.
1656 function wp_create_post_autosave( $post_data ) {
1657 if ( is_numeric( $post_data ) ) {
1658 $post_id = $post_data;
1659 $post_data = $_POST;
1661 $post_id = (int) $post_data['post_ID'];
1664 $post_data = _wp_translate_postdata( true, $post_data );
1665 if ( is_wp_error( $post_data ) )
1668 $post_author = get_current_user_id();
1670 // Store one autosave per author. If there is already an autosave, overwrite it.
1671 if ( $old_autosave = wp_get_post_autosave( $post_id, $post_author ) ) {
1672 $new_autosave = _wp_post_revision_data( $post_data, true );
1673 $new_autosave['ID'] = $old_autosave->ID;
1674 $new_autosave['post_author'] = $post_author;
1676 // If the new autosave has the same content as the post, delete the autosave.
1677 $post = get_post( $post_id );
1678 $autosave_is_different = false;
1679 foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
1680 if ( normalize_whitespace( $new_autosave[ $field ] ) != normalize_whitespace( $post->$field ) ) {
1681 $autosave_is_different = true;
1686 if ( ! $autosave_is_different ) {
1687 wp_delete_post_revision( $old_autosave->ID );
1692 * Fires before an autosave is stored.
1696 * @param array $new_autosave Post array - the autosave that is about to be saved.
1698 do_action( 'wp_creating_autosave', $new_autosave );
1700 return wp_update_post( $new_autosave );
1703 // _wp_put_post_revision() expects unescaped.
1704 $post_data = wp_unslash( $post_data );
1706 // Otherwise create the new autosave as a special post revision
1707 return _wp_put_post_revision( $post_data, true );
1711 * Save draft or manually autosave for showing preview.
1713 * @package WordPress
1716 * @return str URL to redirect to show the preview
1718 function post_preview() {
1720 $post_ID = (int) $_POST['post_ID'];
1721 $_POST['ID'] = $post_ID;
1723 if ( ! $post = get_post( $post_ID ) ) {
1724 wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
1727 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1728 wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
1731 $is_autosave = false;
1733 if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'draft' == $post->post_status || 'auto-draft' == $post->post_status ) ) {
1734 $saved_post_id = edit_post();
1736 $is_autosave = true;
1738 if ( isset( $_POST['post_status'] ) && 'auto-draft' == $_POST['post_status'] )
1739 $_POST['post_status'] = 'draft';
1741 $saved_post_id = wp_create_post_autosave( $post->ID );
1744 if ( is_wp_error( $saved_post_id ) )
1745 wp_die( $saved_post_id->get_error_message() );
1747 $query_args = array();
1749 if ( $is_autosave && $saved_post_id ) {
1750 $query_args['preview_id'] = $post->ID;
1751 $query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
1753 if ( isset( $_POST['post_format'] ) ) {
1754 $query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
1757 if ( isset( $_POST['_thumbnail_id'] ) ) {
1758 $query_args['_thumbnail_id'] = ( intval( $_POST['_thumbnail_id'] ) <= 0 ) ? '-1' : intval( $_POST['_thumbnail_id'] );
1762 return get_preview_post_link( $post, $query_args );
1766 * Save a post submitted with XHR
1768 * Intended for use with heartbeat and autosave.js
1772 * @param array $post_data Associative array of the submitted post data.
1773 * @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
1774 * The ID can be the draft post_id or the autosave revision post_id.
1776 function wp_autosave( $post_data ) {
1778 if ( ! defined( 'DOING_AUTOSAVE' ) )
1779 define( 'DOING_AUTOSAVE', true );
1781 $post_id = (int) $post_data['post_id'];
1782 $post_data['ID'] = $post_data['post_ID'] = $post_id;
1784 if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
1785 return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
1788 $post = get_post( $post_id );
1790 if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1791 return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to edit this item.' ) );
1794 if ( 'auto-draft' == $post->post_status )
1795 $post_data['post_status'] = 'draft';
1797 if ( $post_data['post_type'] != 'page' && ! empty( $post_data['catslist'] ) )
1798 $post_data['post_category'] = explode( ',', $post_data['catslist'] );
1800 if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'auto-draft' == $post->post_status || 'draft' == $post->post_status ) ) {
1801 // Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked
1802 return edit_post( wp_slash( $post_data ) );
1804 // Non drafts or other users drafts are not overwritten. The autosave is stored in a special post revision for each user.
1805 return wp_create_post_autosave( wp_slash( $post_data ) );
1810 * Redirect to previous page.
1812 * @param int $post_id Optional. Post ID.
1814 function redirect_post($post_id = '') {
1815 if ( isset($_POST['save']) || isset($_POST['publish']) ) {
1816 $status = get_post_status( $post_id );
1818 if ( isset( $_POST['publish'] ) ) {
1819 switch ( $status ) {
1830 $message = 'draft' == $status ? 10 : 1;
1833 $location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) );
1834 } elseif ( isset($_POST['addmeta']) && $_POST['addmeta'] ) {
1835 $location = add_query_arg( 'message', 2, wp_get_referer() );
1836 $location = explode('#', $location);
1837 $location = $location[0] . '#postcustom';
1838 } elseif ( isset($_POST['deletemeta']) && $_POST['deletemeta'] ) {
1839 $location = add_query_arg( 'message', 3, wp_get_referer() );
1840 $location = explode('#', $location);
1841 $location = $location[0] . '#postcustom';
1843 $location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) );
1847 * Filters the post redirect destination URL.
1851 * @param string $location The destination URL.
1852 * @param int $post_id The post ID.
1854 wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) );