10 // Post Type Registration
14 * Creates the initial post types when 'init' action is fired.
20 function create_initial_post_types() {
21 register_post_type( 'post', array(
23 'name_admin_bar' => _x( 'Post', 'add new from admin bar' ),
26 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
27 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
28 'capability_type' => 'post',
29 'map_meta_cap' => true,
31 'hierarchical' => false,
34 'delete_with_user' => true,
35 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
36 'show_in_rest' => true,
37 'rest_base' => 'posts',
38 'rest_controller_class' => 'WP_REST_Posts_Controller',
41 register_post_type( 'page', array(
43 'name_admin_bar' => _x( 'Page', 'add new from admin bar' ),
46 'publicly_queryable' => false,
47 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
48 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
49 'capability_type' => 'page',
50 'map_meta_cap' => true,
51 'menu_position' => 20,
52 'hierarchical' => true,
55 'delete_with_user' => true,
56 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
57 'show_in_rest' => true,
58 'rest_base' => 'pages',
59 'rest_controller_class' => 'WP_REST_Posts_Controller',
62 register_post_type( 'attachment', array(
64 'name' => _x('Media', 'post type general name'),
65 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
66 'add_new' => _x( 'Add New', 'add new media' ),
67 'edit_item' => __( 'Edit Media' ),
68 'view_item' => __( 'View Attachment Page' ),
69 'attributes' => __( 'Attachment Attributes' ),
73 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
74 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
75 'capability_type' => 'post',
76 'capabilities' => array(
77 'create_posts' => 'upload_files',
79 'map_meta_cap' => true,
80 'hierarchical' => false,
83 'show_in_nav_menus' => false,
84 'delete_with_user' => true,
85 'supports' => array( 'title', 'author', 'comments' ),
86 'show_in_rest' => true,
87 'rest_base' => 'media',
88 'rest_controller_class' => 'WP_REST_Attachments_Controller',
90 add_post_type_support( 'attachment:audio', 'thumbnail' );
91 add_post_type_support( 'attachment:video', 'thumbnail' );
93 register_post_type( 'revision', array(
95 'name' => __( 'Revisions' ),
96 'singular_name' => __( 'Revision' ),
99 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
100 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
101 'capability_type' => 'post',
102 'map_meta_cap' => true,
103 'hierarchical' => false,
105 'query_var' => false,
106 'can_export' => false,
107 'delete_with_user' => true,
108 'supports' => array( 'author' ),
111 register_post_type( 'nav_menu_item', array(
113 'name' => __( 'Navigation Menu Items' ),
114 'singular_name' => __( 'Navigation Menu Item' ),
117 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
118 'hierarchical' => false,
120 'delete_with_user' => false,
121 'query_var' => false,
124 register_post_type( 'custom_css', array(
126 'name' => __( 'Custom CSS' ),
127 'singular_name' => __( 'Custom CSS' ),
130 'hierarchical' => false,
132 'query_var' => false,
133 'delete_with_user' => false,
134 'can_export' => true,
135 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
136 'supports' => array( 'title', 'revisions' ),
137 'capabilities' => array(
138 'delete_posts' => 'edit_theme_options',
139 'delete_post' => 'edit_theme_options',
140 'delete_published_posts' => 'edit_theme_options',
141 'delete_private_posts' => 'edit_theme_options',
142 'delete_others_posts' => 'edit_theme_options',
143 'edit_post' => 'edit_css',
144 'edit_posts' => 'edit_css',
145 'edit_others_posts' => 'edit_css',
146 'edit_published_posts' => 'edit_css',
147 'read_post' => 'read',
148 'read_private_posts' => 'read',
149 'publish_posts' => 'edit_theme_options',
153 register_post_type( 'customize_changeset', array(
155 'name' => _x( 'Changesets', 'post type general name' ),
156 'singular_name' => _x( 'Changeset', 'post type singular name' ),
157 'menu_name' => _x( 'Changesets', 'admin menu' ),
158 'name_admin_bar' => _x( 'Changeset', 'add new on admin bar' ),
159 'add_new' => _x( 'Add New', 'Customize Changeset' ),
160 'add_new_item' => __( 'Add New Changeset' ),
161 'new_item' => __( 'New Changeset' ),
162 'edit_item' => __( 'Edit Changeset' ),
163 'view_item' => __( 'View Changeset' ),
164 'all_items' => __( 'All Changesets' ),
165 'search_items' => __( 'Search Changesets' ),
166 'not_found' => __( 'No changesets found.' ),
167 'not_found_in_trash' => __( 'No changesets found in Trash.' ),
170 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
171 'map_meta_cap' => true,
172 'hierarchical' => false,
174 'query_var' => false,
175 'can_export' => false,
176 'delete_with_user' => false,
177 'supports' => array( 'title', 'author' ),
178 'capability_type' => 'customize_changeset',
179 'capabilities' => array(
180 'create_posts' => 'customize',
181 'delete_others_posts' => 'customize',
182 'delete_post' => 'customize',
183 'delete_posts' => 'customize',
184 'delete_private_posts' => 'customize',
185 'delete_published_posts' => 'customize',
186 'edit_others_posts' => 'customize',
187 'edit_post' => 'customize',
188 'edit_posts' => 'customize',
189 'edit_private_posts' => 'customize',
190 'edit_published_posts' => 'do_not_allow',
191 'publish_posts' => 'customize',
193 'read_post' => 'customize',
194 'read_private_posts' => 'customize',
198 register_post_status( 'publish', array(
199 'label' => _x( 'Published', 'post status' ),
201 '_builtin' => true, /* internal use only. */
202 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
205 register_post_status( 'future', array(
206 'label' => _x( 'Scheduled', 'post status' ),
208 '_builtin' => true, /* internal use only. */
209 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
212 register_post_status( 'draft', array(
213 'label' => _x( 'Draft', 'post status' ),
215 '_builtin' => true, /* internal use only. */
216 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
219 register_post_status( 'pending', array(
220 'label' => _x( 'Pending', 'post status' ),
222 '_builtin' => true, /* internal use only. */
223 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
226 register_post_status( 'private', array(
227 'label' => _x( 'Private', 'post status' ),
229 '_builtin' => true, /* internal use only. */
230 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
233 register_post_status( 'trash', array(
234 'label' => _x( 'Trash', 'post status' ),
236 '_builtin' => true, /* internal use only. */
237 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
238 'show_in_admin_status_list' => true,
241 register_post_status( 'auto-draft', array(
242 'label' => 'auto-draft',
244 '_builtin' => true, /* internal use only. */
247 register_post_status( 'inherit', array(
248 'label' => 'inherit',
250 '_builtin' => true, /* internal use only. */
251 'exclude_from_search' => false,
256 * Retrieve attached file path based on attachment ID.
258 * By default the path will go through the 'get_attached_file' filter, but
259 * passing a true to the $unfiltered argument of get_attached_file() will
260 * return the file path unfiltered.
262 * The function works by getting the single post meta name, named
263 * '_wp_attached_file' and returning it. This is a convenience function to
264 * prevent looking up the meta name and provide a mechanism for sending the
265 * attached filename through a filter.
269 * @param int $attachment_id Attachment ID.
270 * @param bool $unfiltered Optional. Whether to apply filters. Default false.
271 * @return string|false The file path to where the attached file should be, false otherwise.
273 function get_attached_file( $attachment_id, $unfiltered = false ) {
274 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
276 // If the file is relative, prepend upload dir.
277 if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) && ( ( $uploads = wp_get_upload_dir() ) && false === $uploads['error'] ) ) {
278 $file = $uploads['basedir'] . "/$file";
286 * Filters the attached file based on the given ID.
290 * @param string $file Path to attached file.
291 * @param int $attachment_id Attachment ID.
293 return apply_filters( 'get_attached_file', $file, $attachment_id );
297 * Update attachment file path based on attachment ID.
299 * Used to update the file path of the attachment, which uses post meta name
300 * '_wp_attached_file' to store the path of the attachment.
304 * @param int $attachment_id Attachment ID.
305 * @param string $file File path for the attachment.
306 * @return bool True on success, false on failure.
308 function update_attached_file( $attachment_id, $file ) {
309 if ( !get_post( $attachment_id ) )
313 * Filters the path to the attached file to update.
317 * @param string $file Path to the attached file to update.
318 * @param int $attachment_id Attachment ID.
320 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
322 if ( $file = _wp_relative_upload_path( $file ) )
323 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
325 return delete_post_meta( $attachment_id, '_wp_attached_file' );
329 * Return relative path to an uploaded file.
331 * The path is relative to the current upload dir.
335 * @param string $path Full path to the file.
336 * @return string Relative path on success, unchanged path on failure.
338 function _wp_relative_upload_path( $path ) {
341 $uploads = wp_get_upload_dir();
342 if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
343 $new_path = str_replace( $uploads['basedir'], '', $new_path );
344 $new_path = ltrim( $new_path, '/' );
348 * Filters the relative path to an uploaded file.
352 * @param string $new_path Relative path to the file.
353 * @param string $path Full path to the file.
355 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
359 * Retrieve all children of the post parent ID.
361 * Normally, without any enhancements, the children would apply to pages. In the
362 * context of the inner workings of WordPress, pages, posts, and attachments
363 * share the same table, so therefore the functionality could apply to any one
364 * of them. It is then noted that while this function does not work on posts, it
365 * does not mean that it won't work on posts. It is recommended that you know
366 * what context you wish to retrieve the children of.
368 * Attachments may also be made the child of a post, so if that is an accurate
369 * statement (which needs to be verified), it would then be possible to get
370 * all of the attachments for a post. Attachments have since changed since
371 * version 2.5, so this is most likely inaccurate, but serves generally as an
372 * example of what is possible.
374 * The arguments listed as defaults are for this function and also of the
375 * get_posts() function. The arguments are combined with the get_children defaults
376 * and are then passed to the get_posts() function, which accepts additional arguments.
377 * You can replace the defaults in this function, listed below and the additional
378 * arguments listed in the get_posts() function.
380 * The 'post_parent' is the most important argument and important attention
381 * needs to be paid to the $args parameter. If you pass either an object or an
382 * integer (number), then just the 'post_parent' is grabbed and everything else
383 * is lost. If you don't specify any arguments, then it is assumed that you are
384 * in The Loop and the post parent will be grabbed for from the current post.
386 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
387 * is the amount of posts to retrieve that has a default of '-1', which is
388 * used to get all of the posts. Giving a number higher than 0 will only
389 * retrieve that amount of posts.
391 * The 'post_type' and 'post_status' arguments can be used to choose what
392 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
393 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
394 * argument will accept any post status within the write administration panels.
399 * @todo Check validity of description.
401 * @global WP_Post $post
403 * @param mixed $args Optional. User defined arguments for replacing the defaults. Default empty.
404 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
405 * a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT.
406 * @return array Array of children, where the type of each element is determined by $output parameter.
407 * Empty array on failure.
409 function get_children( $args = '', $output = OBJECT ) {
411 if ( empty( $args ) ) {
412 if ( isset( $GLOBALS['post'] ) ) {
413 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
417 } elseif ( is_object( $args ) ) {
418 $args = array('post_parent' => (int) $args->post_parent );
419 } elseif ( is_numeric( $args ) ) {
420 $args = array('post_parent' => (int) $args);
424 'numberposts' => -1, 'post_type' => 'any',
425 'post_status' => 'any', 'post_parent' => 0,
428 $r = wp_parse_args( $args, $defaults );
430 $children = get_posts( $r );
435 if ( ! empty( $r['fields'] ) )
438 update_post_cache($children);
440 foreach ( $children as $key => $child )
441 $kids[$child->ID] = $children[$key];
443 if ( $output == OBJECT ) {
445 } elseif ( $output == ARRAY_A ) {
447 foreach ( (array) $kids as $kid ) {
448 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
451 } elseif ( $output == ARRAY_N ) {
453 foreach ( (array) $kids as $kid ) {
454 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
463 * Get extended entry info (<!--more-->).
465 * There should not be any space after the second dash and before the word
466 * 'more'. There can be text or space(s) after the word 'more', but won't be
469 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
470 * the `<!--more-->`. The 'extended' key has the content after the
471 * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
475 * @param string $post Post content.
476 * @return array Post before ('main'), after ('extended'), and custom read more ('more_text').
478 function get_extended( $post ) {
479 //Match the new style more links.
480 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
481 list($main, $extended) = explode($matches[0], $post, 2);
482 $more_text = $matches[1];
489 // leading and trailing whitespace.
490 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
491 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
492 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
494 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
498 * Retrieves post data given a post ID or post object.
500 * See sanitize_post() for optional $filter values. Also, the parameter
501 * `$post`, must be given as a variable, since it is passed by reference.
505 * @global WP_Post $post
507 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
508 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
509 * a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT.
510 * @param string $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
511 * or 'display'. Default 'raw'.
512 * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
513 * When $output is OBJECT, a `WP_Post` instance is returned.
515 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
516 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
517 $post = $GLOBALS['post'];
519 if ( $post instanceof WP_Post ) {
521 } elseif ( is_object( $post ) ) {
522 if ( empty( $post->filter ) ) {
523 $_post = sanitize_post( $post, 'raw' );
524 $_post = new WP_Post( $_post );
525 } elseif ( 'raw' == $post->filter ) {
526 $_post = new WP_Post( $post );
528 $_post = WP_Post::get_instance( $post->ID );
531 $_post = WP_Post::get_instance( $post );
537 $_post = $_post->filter( $filter );
539 if ( $output == ARRAY_A )
540 return $_post->to_array();
541 elseif ( $output == ARRAY_N )
542 return array_values( $_post->to_array() );
548 * Retrieve ancestors of a post.
552 * @param int|WP_Post $post Post ID or post object.
553 * @return array Ancestor IDs or empty array if none are found.
555 function get_post_ancestors( $post ) {
556 $post = get_post( $post );
558 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
561 $ancestors = array();
563 $id = $ancestors[] = $post->post_parent;
565 while ( $ancestor = get_post( $id ) ) {
566 // Loop detection: If the ancestor has been seen before, break.
567 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
570 $id = $ancestors[] = $ancestor->post_parent;
577 * Retrieve data from a post field based on Post ID.
579 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
580 * etc and based off of the post object property or key names.
582 * The context values are based off of the taxonomy filter functions and
583 * supported values are found within those functions.
586 * @since 4.5.0 The `$post` parameter was made optional.
588 * @see sanitize_post_field()
590 * @param string $field Post field name.
591 * @param int|WP_Post $post Optional. Post ID or post object. Defaults to current post.
592 * @param string $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
593 * or 'display'. Default 'display'.
594 * @return string The value of the post field on success, empty string on failure.
596 function get_post_field( $field, $post = null, $context = 'display' ) {
597 $post = get_post( $post );
602 if ( !isset($post->$field) )
605 return sanitize_post_field($field, $post->$field, $post->ID, $context);
609 * Retrieve the mime type of an attachment based on the ID.
611 * This function can be used with any post type, but it makes more sense with
616 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
617 * @return string|false The mime type on success, false on failure.
619 function get_post_mime_type( $ID = '' ) {
620 $post = get_post($ID);
622 if ( is_object($post) )
623 return $post->post_mime_type;
629 * Retrieve the post status based on the Post ID.
631 * If the post ID is of an attachment, then the parent post status will be given
636 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
637 * @return string|false Post status on success, false on failure.
639 function get_post_status( $ID = '' ) {
640 $post = get_post($ID);
642 if ( !is_object($post) )
645 if ( 'attachment' == $post->post_type ) {
646 if ( 'private' == $post->post_status )
649 // Unattached attachments are assumed to be published.
650 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
653 // Inherit status from the parent.
654 if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) {
655 $parent_post_status = get_post_status( $post->post_parent );
656 if ( 'trash' == $parent_post_status ) {
657 return get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
659 return $parent_post_status;
666 * Filters the post status.
670 * @param string $post_status The post status.
671 * @param WP_Post $post The post object.
673 return apply_filters( 'get_post_status', $post->post_status, $post );
677 * Retrieve all of the WordPress supported post statuses.
679 * Posts have a limited set of valid status values, this provides the
680 * post_status values and descriptions.
684 * @return array List of post statuses.
686 function get_post_statuses() {
688 'draft' => __( 'Draft' ),
689 'pending' => __( 'Pending Review' ),
690 'private' => __( 'Private' ),
691 'publish' => __( 'Published' )
698 * Retrieve all of the WordPress support page statuses.
700 * Pages have a limited set of valid status values, this provides the
701 * post_status values and descriptions.
705 * @return array List of page statuses.
707 function get_page_statuses() {
709 'draft' => __( 'Draft' ),
710 'private' => __( 'Private' ),
711 'publish' => __( 'Published' )
718 * Register a post status. Do not use before init.
720 * A simple function for creating or modifying a post status based on the
721 * parameters given. The function will accept an array (second optional
722 * parameter), along with a string for the post status name.
724 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
727 * @global array $wp_post_statuses Inserts new post status object into the list
729 * @param string $post_status Name of the post status.
730 * @param array|string $args {
731 * Optional. Array or string of post status arguments.
733 * @type bool|string $label A descriptive name for the post status marked
734 * for translation. Defaults to value of $post_status.
735 * @type bool|array $label_count Descriptive text to use for nooped plurals.
736 * Default array of $label, twice
737 * @type bool $exclude_from_search Whether to exclude posts with this post status
738 * from search results. Default is value of $internal.
739 * @type bool $_builtin Whether the status is built-in. Core-use only.
741 * @type bool $public Whether posts of this status should be shown
742 * in the front end of the site. Default false.
743 * @type bool $internal Whether the status is for internal use only.
745 * @type bool $protected Whether posts with this status should be protected.
747 * @type bool $private Whether posts with this status should be private.
749 * @type bool $publicly_queryable Whether posts with this status should be publicly-
750 * queryable. Default is value of $public.
751 * @type bool $show_in_admin_all_list Whether to include posts in the edit listing for
752 * their post type. Default is value of $internal.
753 * @type bool $show_in_admin_status_list Show in the list of statuses with post counts at
754 * the top of the edit listings,
755 * e.g. All (12) | Published (9) | My Custom Status (2)
756 * Default is value of $internal.
760 function register_post_status( $post_status, $args = array() ) {
761 global $wp_post_statuses;
763 if (!is_array($wp_post_statuses))
764 $wp_post_statuses = array();
766 // Args prefixed with an underscore are reserved for internal use.
769 'label_count' => false,
770 'exclude_from_search' => null,
776 'publicly_queryable' => null,
777 'show_in_admin_status_list' => null,
778 'show_in_admin_all_list' => null,
780 $args = wp_parse_args($args, $defaults);
781 $args = (object) $args;
783 $post_status = sanitize_key($post_status);
784 $args->name = $post_status;
786 // Set various defaults.
787 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
788 $args->internal = true;
790 if ( null === $args->public )
791 $args->public = false;
793 if ( null === $args->private )
794 $args->private = false;
796 if ( null === $args->protected )
797 $args->protected = false;
799 if ( null === $args->internal )
800 $args->internal = false;
802 if ( null === $args->publicly_queryable )
803 $args->publicly_queryable = $args->public;
805 if ( null === $args->exclude_from_search )
806 $args->exclude_from_search = $args->internal;
808 if ( null === $args->show_in_admin_all_list )
809 $args->show_in_admin_all_list = !$args->internal;
811 if ( null === $args->show_in_admin_status_list )
812 $args->show_in_admin_status_list = !$args->internal;
814 if ( false === $args->label )
815 $args->label = $post_status;
817 if ( false === $args->label_count )
818 $args->label_count = array( $args->label, $args->label );
820 $wp_post_statuses[$post_status] = $args;
826 * Retrieve a post status object by name.
830 * @global array $wp_post_statuses List of post statuses.
832 * @see register_post_status()
834 * @param string $post_status The name of a registered post status.
835 * @return object|null A post status object.
837 function get_post_status_object( $post_status ) {
838 global $wp_post_statuses;
840 if ( empty($wp_post_statuses[$post_status]) )
843 return $wp_post_statuses[$post_status];
847 * Get a list of post statuses.
851 * @global array $wp_post_statuses List of post statuses.
853 * @see register_post_status()
855 * @param array|string $args Optional. Array or string of post status arguments to compare against
856 * properties of the global `$wp_post_statuses objects`. Default empty array.
857 * @param string $output Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
858 * @param string $operator Optional. The logical operation to perform. 'or' means only one element
859 * from the array needs to match; 'and' means all elements must match.
861 * @return array A list of post status names or objects.
863 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
864 global $wp_post_statuses;
866 $field = ('names' == $output) ? 'name' : false;
868 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
872 * Whether the post type is hierarchical.
874 * A false return value might also mean that the post type does not exist.
878 * @see get_post_type_object()
880 * @param string $post_type Post type name
881 * @return bool Whether post type is hierarchical.
883 function is_post_type_hierarchical( $post_type ) {
884 if ( ! post_type_exists( $post_type ) )
887 $post_type = get_post_type_object( $post_type );
888 return $post_type->hierarchical;
892 * Check if a post type is registered.
896 * @see get_post_type_object()
898 * @param string $post_type Post type name.
899 * @return bool Whether post type is registered.
901 function post_type_exists( $post_type ) {
902 return (bool) get_post_type_object( $post_type );
906 * Retrieves the post type of the current post or of a given post.
910 * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
911 * @return string|false Post type on success, false on failure.
913 function get_post_type( $post = null ) {
914 if ( $post = get_post( $post ) )
915 return $post->post_type;
921 * Retrieves a post type object by name.
924 * @since 4.6.0 Object returned is now an instance of WP_Post_Type.
926 * @global array $wp_post_types List of post types.
928 * @see register_post_type()
930 * @param string $post_type The name of a registered post type.
931 * @return WP_Post_Type|null WP_Post_Type object if it exists, null otherwise.
933 function get_post_type_object( $post_type ) {
934 global $wp_post_types;
936 if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
940 return $wp_post_types[ $post_type ];
944 * Get a list of all registered post type objects.
948 * @global array $wp_post_types List of post types.
950 * @see register_post_type() for accepted arguments.
952 * @param array|string $args Optional. An array of key => value arguments to match against
953 * the post type objects. Default empty array.
954 * @param string $output Optional. The type of output to return. Accepts post type 'names'
955 * or 'objects'. Default 'names'.
956 * @param string $operator Optional. The logical operation to perform. 'or' means only one
957 * element from the array needs to match; 'and' means all elements
958 * must match; 'not' means no elements may match. Default 'and'.
959 * @return array A list of post type names or objects.
961 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
962 global $wp_post_types;
964 $field = ('names' == $output) ? 'name' : false;
966 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
970 * Registers a post type.
972 * Note: Post type registrations should not be hooked before the
973 * {@see 'init'} action. Also, any taxonomy connections should be
974 * registered via the `$taxonomies` argument to ensure consistency
975 * when hooks such as {@see 'parse_query'} or {@see 'pre_get_posts'}
978 * Post types can support any number of built-in core features such
979 * as meta boxes, custom fields, post thumbnails, post statuses,
980 * comments, and more. See the `$supports` argument for a complete
981 * list of supported features.
984 * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
985 * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing
986 * screen and post editing screen.
987 * @since 4.6.0 Post type object returned is now an instance of WP_Post_Type.
988 * @since 4.7.0 Introduced `show_in_rest`, 'rest_base' and 'rest_controller_class'
989 * arguments to register the post type in REST API.
991 * @global array $wp_post_types List of post types.
993 * @param string $post_type Post type key. Must not exceed 20 characters and may
994 * only contain lowercase alphanumeric characters, dashes,
995 * and underscores. See sanitize_key().
996 * @param array|string $args {
997 * Array or string of arguments for registering a post type.
999 * @type string $label Name of the post type shown in the menu. Usually plural.
1000 * Default is value of $labels['name'].
1001 * @type array $labels An array of labels for this post type. If not set, post
1002 * labels are inherited for non-hierarchical types and page
1003 * labels for hierarchical ones. See get_post_type_labels() for a full
1004 * list of supported labels.
1005 * @type string $description A short descriptive summary of what the post type is.
1007 * @type bool $public Whether a post type is intended for use publicly either via
1008 * the admin interface or by front-end users. While the default
1009 * settings of $exclude_from_search, $publicly_queryable, $show_ui,
1010 * and $show_in_nav_menus are inherited from public, each does not
1011 * rely on this relationship and controls a very specific intention.
1013 * @type bool $hierarchical Whether the post type is hierarchical (e.g. page). Default false.
1014 * @type bool $exclude_from_search Whether to exclude posts with this post type from front end search
1015 * results. Default is the opposite value of $public.
1016 * @type bool $publicly_queryable Whether queries can be performed on the front end for the post type
1017 * as part of parse_request(). Endpoints would include:
1018 * * ?post_type={post_type_key}
1019 * * ?{post_type_key}={single_post_slug}
1020 * * ?{post_type_query_var}={single_post_slug}
1021 * If not set, the default is inherited from $public.
1022 * @type bool $show_ui Whether to generate and allow a UI for managing this post type in the
1023 * admin. Default is value of $public.
1024 * @type bool $show_in_menu Where to show the post type in the admin menu. To work, $show_ui
1025 * must be true. If true, the post type is shown in its own top level
1026 * menu. If false, no menu is shown. If a string of an existing top
1027 * level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
1028 * type will be placed as a sub-menu of that.
1029 * Default is value of $show_ui.
1030 * @type bool $show_in_nav_menus Makes this post type available for selection in navigation menus.
1031 * Default is value $public.
1032 * @type bool $show_in_admin_bar Makes this post type available via the admin bar. Default is value
1034 * @type bool $show_in_rest Whether to add the post type route in the REST API 'wp/v2' namespace.
1035 * @type string $rest_base To change the base url of REST API route. Default is $post_type.
1036 * @type string $rest_controller_class REST API Controller class name. Default is 'WP_REST_Posts_Controller'.
1037 * @type int $menu_position The position in the menu order the post type should appear. To work,
1038 * $show_in_menu must be true. Default null (at the bottom).
1039 * @type string $menu_icon The url to the icon to be used for this menu. Pass a base64-encoded
1040 * SVG using a data URI, which will be colored to match the color scheme
1041 * -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
1042 * of a Dashicons helper class to use a font icon, e.g.
1043 * 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
1044 * so an icon can be added via CSS. Defaults to use the posts icon.
1045 * @type string $capability_type The string to use to build the read, edit, and delete capabilities.
1046 * May be passed as an array to allow for alternative plurals when using
1047 * this argument as a base to construct the capabilities, e.g.
1048 * array('story', 'stories'). Default 'post'.
1049 * @type array $capabilities Array of capabilities for this post type. $capability_type is used
1050 * as a base to construct capabilities by default.
1051 * See get_post_type_capabilities().
1052 * @type bool $map_meta_cap Whether to use the internal default meta capability handling.
1054 * @type array $supports Core feature(s) the post type supports. Serves as an alias for calling
1055 * add_post_type_support() directly. Core features include 'title',
1056 * 'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt',
1057 * 'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'.
1058 * Additionally, the 'revisions' feature dictates whether the post type
1059 * will store revisions, and the 'comments' feature dictates whether the
1060 * comments count will show on the edit screen. Defaults is an array
1061 * containing 'title' and 'editor'.
1062 * @type callable $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
1063 * edit form. Do remove_meta_box() and add_meta_box() calls in the
1064 * callback. Default null.
1065 * @type array $taxonomies An array of taxonomy identifiers that will be registered for the
1066 * post type. Taxonomies can be registered later with register_taxonomy()
1067 * or register_taxonomy_for_object_type().
1068 * Default empty array.
1069 * @type bool|string $has_archive Whether there should be post type archives, or if a string, the
1070 * archive slug to use. Will generate the proper rewrite rules if
1071 * $rewrite is enabled. Default false.
1072 * @type bool|array $rewrite {
1073 * Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
1074 * Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
1075 * passed with any of these keys:
1077 * @type string $slug Customize the permastruct slug. Defaults to $post_type key.
1078 * @type bool $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
1080 * @type bool $feeds Whether the feed permastruct should be built for this post type.
1081 * Default is value of $has_archive.
1082 * @type bool $pages Whether the permastruct should provide for pagination. Default true.
1083 * @type const $ep_mask Endpoint mask to assign. If not specified and permalink_epmask is set,
1084 * inherits from $permalink_epmask. If not specified and permalink_epmask
1085 * is not set, defaults to EP_PERMALINK.
1087 * @type string|bool $query_var Sets the query_var key for this post type. Defaults to $post_type
1088 * key. If false, a post type cannot be loaded at
1089 * ?{query_var}={post_slug}. If specified as a string, the query
1090 * ?{query_var_string}={post_slug} will be valid.
1091 * @type bool $can_export Whether to allow this post type to be exported. Default true.
1092 * @type bool $delete_with_user Whether to delete posts of this type when deleting a user. If true,
1093 * posts of this type belonging to the user will be moved to trash
1094 * when then user is deleted. If false, posts of this type belonging
1095 * to the user will *not* be trashed or deleted. If not set (the default),
1096 * posts are trashed if post_type_supports('author'). Otherwise posts
1097 * are not trashed or deleted. Default null.
1098 * @type bool $_builtin FOR INTERNAL USE ONLY! True if this post type is a native or
1099 * "built-in" post_type. Default false.
1100 * @type string $_edit_link FOR INTERNAL USE ONLY! URL segment to use for edit link of
1101 * this post type. Default 'post.php?post=%d'.
1103 * @return WP_Post_Type|WP_Error The registered post type object, or an error object.
1105 function register_post_type( $post_type, $args = array() ) {
1106 global $wp_post_types;
1108 if ( ! is_array( $wp_post_types ) ) {
1109 $wp_post_types = array();
1112 // Sanitize post type name
1113 $post_type = sanitize_key( $post_type );
1115 if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1116 _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2.0' );
1117 return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1120 $post_type_object = new WP_Post_Type( $post_type, $args );
1121 $post_type_object->add_supports();
1122 $post_type_object->add_rewrite_rules();
1123 $post_type_object->register_meta_boxes();
1125 $wp_post_types[ $post_type ] = $post_type_object;
1127 $post_type_object->add_hooks();
1128 $post_type_object->register_taxonomies();
1131 * Fires after a post type is registered.
1134 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1136 * @param string $post_type Post type.
1137 * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1139 do_action( 'registered_post_type', $post_type, $post_type_object );
1141 return $post_type_object;
1145 * Unregisters a post type.
1147 * Can not be used to unregister built-in post types.
1151 * @global array $wp_post_types List of post types.
1153 * @param string $post_type Post type to unregister.
1154 * @return bool|WP_Error True on success, WP_Error on failure or if the post type doesn't exist.
1156 function unregister_post_type( $post_type ) {
1157 global $wp_post_types;
1159 if ( ! post_type_exists( $post_type ) ) {
1160 return new WP_Error( 'invalid_post_type', __( 'Invalid post type.' ) );
1163 $post_type_object = get_post_type_object( $post_type );
1165 // Do not allow unregistering internal post types.
1166 if ( $post_type_object->_builtin ) {
1167 return new WP_Error( 'invalid_post_type', __( 'Unregistering a built-in post type is not allowed' ) );
1170 $post_type_object->remove_supports();
1171 $post_type_object->remove_rewrite_rules();
1172 $post_type_object->unregister_meta_boxes();
1173 $post_type_object->remove_hooks();
1174 $post_type_object->unregister_taxonomies();
1176 unset( $wp_post_types[ $post_type ] );
1179 * Fires after a post type was unregistered.
1183 * @param string $post_type Post type key.
1185 do_action( 'unregistered_post_type', $post_type );
1191 * Build an object with all post type capabilities out of a post type object
1193 * Post type capabilities use the 'capability_type' argument as a base, if the
1194 * capability is not set in the 'capabilities' argument array or if the
1195 * 'capabilities' argument is not supplied.
1197 * The capability_type argument can optionally be registered as an array, with
1198 * the first value being singular and the second plural, e.g. array('story, 'stories')
1199 * Otherwise, an 's' will be added to the value for the plural form. After
1200 * registration, capability_type will always be a string of the singular value.
1202 * By default, seven keys are accepted as part of the capabilities array:
1204 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1205 * generally mapped to corresponding primitive capabilities depending on the
1206 * context, which would be the post being edited/read/deleted and the user or
1207 * role being checked. Thus these capabilities would generally not be granted
1208 * directly to users or roles.
1210 * - edit_posts - Controls whether objects of this post type can be edited.
1211 * - edit_others_posts - Controls whether objects of this type owned by other users
1212 * can be edited. If the post type does not support an author, then this will
1213 * behave like edit_posts.
1214 * - publish_posts - Controls publishing objects of this post type.
1215 * - read_private_posts - Controls whether private objects can be read.
1217 * These four primitive capabilities are checked in core in various locations.
1218 * There are also seven other primitive capabilities which are not referenced
1219 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1220 * meta capabilities and translates them into one or more primitive capabilities
1221 * that must then be checked against the user or role, depending on the context.
1223 * - read - Controls whether objects of this post type can be read.
1224 * - delete_posts - Controls whether objects of this post type can be deleted.
1225 * - delete_private_posts - Controls whether private objects can be deleted.
1226 * - delete_published_posts - Controls whether published objects can be deleted.
1227 * - delete_others_posts - Controls whether objects owned by other users can be
1228 * can be deleted. If the post type does not support an author, then this will
1229 * behave like delete_posts.
1230 * - edit_private_posts - Controls whether private objects can be edited.
1231 * - edit_published_posts - Controls whether published objects can be edited.
1233 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1234 * only assigned by default if the post type is registered with the 'map_meta_cap'
1235 * argument set to true (default is false).
1239 * @see register_post_type()
1240 * @see map_meta_cap()
1242 * @param object $args Post type registration arguments.
1243 * @return object object with all the capabilities as member variables.
1245 function get_post_type_capabilities( $args ) {
1246 if ( ! is_array( $args->capability_type ) )
1247 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1249 // Singular base for meta capabilities, plural base for primitive capabilities.
1250 list( $singular_base, $plural_base ) = $args->capability_type;
1252 $default_capabilities = array(
1253 // Meta capabilities
1254 'edit_post' => 'edit_' . $singular_base,
1255 'read_post' => 'read_' . $singular_base,
1256 'delete_post' => 'delete_' . $singular_base,
1257 // Primitive capabilities used outside of map_meta_cap():
1258 'edit_posts' => 'edit_' . $plural_base,
1259 'edit_others_posts' => 'edit_others_' . $plural_base,
1260 'publish_posts' => 'publish_' . $plural_base,
1261 'read_private_posts' => 'read_private_' . $plural_base,
1264 // Primitive capabilities used within map_meta_cap():
1265 if ( $args->map_meta_cap ) {
1266 $default_capabilities_for_mapping = array(
1268 'delete_posts' => 'delete_' . $plural_base,
1269 'delete_private_posts' => 'delete_private_' . $plural_base,
1270 'delete_published_posts' => 'delete_published_' . $plural_base,
1271 'delete_others_posts' => 'delete_others_' . $plural_base,
1272 'edit_private_posts' => 'edit_private_' . $plural_base,
1273 'edit_published_posts' => 'edit_published_' . $plural_base,
1275 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1278 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1280 // Post creation capability simply maps to edit_posts by default:
1281 if ( ! isset( $capabilities['create_posts'] ) )
1282 $capabilities['create_posts'] = $capabilities['edit_posts'];
1284 // Remember meta capabilities for future reference.
1285 if ( $args->map_meta_cap )
1286 _post_type_meta_capabilities( $capabilities );
1288 return (object) $capabilities;
1292 * Store or return a list of post type meta caps for map_meta_cap().
1297 * @global array $post_type_meta_caps Used to store meta capabilities.
1299 * @param array $capabilities Post type meta capabilities.
1301 function _post_type_meta_capabilities( $capabilities = null ) {
1302 global $post_type_meta_caps;
1304 foreach ( $capabilities as $core => $custom ) {
1305 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) ) {
1306 $post_type_meta_caps[ $custom ] = $core;
1312 * Builds an object with all post type labels out of a post type object.
1314 * Accepted keys of the label array in the post type object:
1316 * - `name` - General name for the post type, usually plural. The same and overridden
1317 * by `$post_type_object->label`. Default is 'Posts' / 'Pages'.
1318 * - `singular_name` - Name for one object of this post type. Default is 'Post' / 'Page'.
1319 * - `add_new` - Default is 'Add New' for both hierarchical and non-hierarchical types.
1320 * When internationalizing this string, please use a {@link https://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context}
1321 * matching your post type. Example: `_x( 'Add New', 'product', 'textdomain' );`.
1322 * - `add_new_item` - Label for adding a new singular item. Default is 'Add New Post' / 'Add New Page'.
1323 * - `edit_item` - Label for editing a singular item. Default is 'Edit Post' / 'Edit Page'.
1324 * - `new_item` - Label for the new item page title. Default is 'New Post' / 'New Page'.
1325 * - `view_item` - Label for viewing a singular item. Default is 'View Post' / 'View Page'.
1326 * - `view_items` - Label for viewing post type archives. Default is 'View Posts' / 'View Pages'.
1327 * - `search_items` - Label for searching plural items. Default is 'Search Posts' / 'Search Pages'.
1328 * - `not_found` - Label used when no items are found. Default is 'No posts found' / 'No pages found'.
1329 * - `not_found_in_trash` - Label used when no items are in the trash. Default is 'No posts found in Trash' /
1330 * 'No pages found in Trash'.
1331 * - `parent_item_colon` - Label used to prefix parents of hierarchical items. Not used on non-hierarchical
1332 * post types. Default is 'Parent Page:'.
1333 * - `all_items` - Label to signify all items in a submenu link. Default is 'All Posts' / 'All Pages'.
1334 * - `archives` - Label for archives in nav menus. Default is 'Post Archives' / 'Page Archives'.
1335 * - `attributes` - Label for the attributes meta box. Default is 'Post Attributes' / 'Page Attributes'.
1336 * - `insert_into_item` - Label for the media frame button. Default is 'Insert into post' / 'Insert into page'.
1337 * - `uploaded_to_this_item` - Label for the media frame filter. Default is 'Uploaded to this post' /
1338 * 'Uploaded to this page'.
1339 * - `featured_image` - Label for the Featured Image meta box title. Default is 'Featured Image'.
1340 * - `set_featured_image` - Label for setting the featured image. Default is 'Set featured image'.
1341 * - `remove_featured_image` - Label for removing the featured image. Default is 'Remove featured image'.
1342 * - `use_featured_image` - Label in the media frame for using a featured image. Default is 'Use as featured image'.
1343 * - `menu_name` - Label for the menu name. Default is the same as `name`.
1344 * - `filter_items_list` - Label for the table views hidden heading. Default is 'Filter posts list' /
1345 * 'Filter pages list'.
1346 * - `items_list_navigation` - Label for the table pagination hidden heading. Default is 'Posts list navigation' /
1347 * 'Pages list navigation'.
1348 * - `items_list` - Label for the table hidden heading. Default is 'Posts list' / 'Pages list'.
1350 * Above, the first default value is for non-hierarchical post types (like posts)
1351 * and the second one is for hierarchical post types (like pages).
1353 * Note: To set labels used in post type admin notices, see the {@see 'post_updated_messages'} filter.
1356 * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
1357 * and `use_featured_image` labels.
1358 * @since 4.4.0 Added the `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
1359 * `items_list_navigation`, and `items_list` labels.
1360 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1361 * @since 4.7.0 Added the `view_items` and `attributes` labels.
1365 * @param object|WP_Post_Type $post_type_object Post type object.
1366 * @return object Object with all the labels as member variables.
1368 function get_post_type_labels( $post_type_object ) {
1369 $nohier_vs_hier_defaults = array(
1370 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1371 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1372 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1373 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1374 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1375 'new_item' => array( __('New Post'), __('New Page') ),
1376 'view_item' => array( __('View Post'), __('View Page') ),
1377 'view_items' => array( __('View Posts'), __('View Pages') ),
1378 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1379 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1380 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1381 'parent_item_colon' => array( null, __('Parent Page:') ),
1382 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ),
1383 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ),
1384 'attributes' => array( __( 'Post Attributes' ), __( 'Page Attributes' ) ),
1385 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ),
1386 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ),
1387 'featured_image' => array( __( 'Featured Image' ), __( 'Featured Image' ) ),
1388 'set_featured_image' => array( __( 'Set featured image' ), __( 'Set featured image' ) ),
1389 'remove_featured_image' => array( __( 'Remove featured image' ), __( 'Remove featured image' ) ),
1390 'use_featured_image' => array( __( 'Use as featured image' ), __( 'Use as featured image' ) ),
1391 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ),
1392 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ),
1393 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ),
1395 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1397 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1399 $post_type = $post_type_object->name;
1401 $default_labels = clone $labels;
1404 * Filters the labels of a specific post type.
1406 * The dynamic portion of the hook name, `$post_type`, refers to
1407 * the post type slug.
1411 * @see get_post_type_labels() for the full list of labels.
1413 * @param object $labels Object with labels for the post type as member variables.
1415 $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
1417 // Ensure that the filtered labels contain all required default values.
1418 $labels = (object) array_merge( (array) $default_labels, (array) $labels );
1424 * Build an object with custom-something object (post type, taxonomy) labels
1425 * out of a custom-something object
1430 * @param object $object A custom-something object.
1431 * @param array $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
1432 * @return object Object containing labels for the given custom-something object.
1434 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1435 $object->labels = (array) $object->labels;
1437 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1438 $object->labels['name'] = $object->label;
1440 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1441 $object->labels['singular_name'] = $object->labels['name'];
1443 if ( ! isset( $object->labels['name_admin_bar'] ) )
1444 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1446 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1447 $object->labels['menu_name'] = $object->labels['name'];
1449 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1450 $object->labels['all_items'] = $object->labels['menu_name'];
1452 if ( !isset( $object->labels['archives'] ) && isset( $object->labels['all_items'] ) ) {
1453 $object->labels['archives'] = $object->labels['all_items'];
1456 $defaults = array();
1457 foreach ( $nohier_vs_hier_defaults as $key => $value ) {
1458 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1460 $labels = array_merge( $defaults, $object->labels );
1461 $object->labels = (object) $object->labels;
1463 return (object) $labels;
1467 * Add submenus for post types.
1472 function _add_post_type_submenus() {
1473 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1474 $ptype_obj = get_post_type_object( $ptype );
1476 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1478 add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
1483 * Register support of certain features for a post type.
1485 * All core features are directly associated with a functional area of the edit
1486 * screen, such as the editor or a meta box. Features include: 'title', 'editor',
1487 * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
1488 * 'thumbnail', 'custom-fields', and 'post-formats'.
1490 * Additionally, the 'revisions' feature dictates whether the post type will
1491 * store revisions, and the 'comments' feature dictates whether the comments
1492 * count will show on the edit screen.
1496 * @global array $_wp_post_type_features
1498 * @param string $post_type The post type for which to add the feature.
1499 * @param string|array $feature The feature being added, accepts an array of
1500 * feature strings or a single string.
1502 function add_post_type_support( $post_type, $feature ) {
1503 global $_wp_post_type_features;
1505 $features = (array) $feature;
1506 foreach ($features as $feature) {
1507 if ( func_num_args() == 2 )
1508 $_wp_post_type_features[$post_type][$feature] = true;
1510 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1515 * Remove support for a feature from a post type.
1519 * @global array $_wp_post_type_features
1521 * @param string $post_type The post type for which to remove the feature.
1522 * @param string $feature The feature being removed.
1524 function remove_post_type_support( $post_type, $feature ) {
1525 global $_wp_post_type_features;
1527 unset( $_wp_post_type_features[ $post_type ][ $feature ] );
1531 * Get all the post type features
1535 * @global array $_wp_post_type_features
1537 * @param string $post_type The post type.
1538 * @return array Post type supports list.
1540 function get_all_post_type_supports( $post_type ) {
1541 global $_wp_post_type_features;
1543 if ( isset( $_wp_post_type_features[$post_type] ) )
1544 return $_wp_post_type_features[$post_type];
1550 * Check a post type's support for a given feature.
1554 * @global array $_wp_post_type_features
1556 * @param string $post_type The post type being checked.
1557 * @param string $feature The feature being checked.
1558 * @return bool Whether the post type supports the given feature.
1560 function post_type_supports( $post_type, $feature ) {
1561 global $_wp_post_type_features;
1563 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1567 * Retrieves a list of post type names that support a specific feature.
1571 * @global array $_wp_post_type_features Post type features
1573 * @param array|string $feature Single feature or an array of features the post types should support.
1574 * @param string $operator Optional. The logical operation to perform. 'or' means
1575 * only one element from the array needs to match; 'and'
1576 * means all elements must match; 'not' means no elements may
1577 * match. Default 'and'.
1578 * @return array A list of post type names.
1580 function get_post_types_by_support( $feature, $operator = 'and' ) {
1581 global $_wp_post_type_features;
1583 $features = array_fill_keys( (array) $feature, true );
1585 return array_keys( wp_filter_object_list( $_wp_post_type_features, $features, $operator ) );
1589 * Update the post type for the post ID.
1591 * The page or post cache will be cleaned for the post ID.
1595 * @global wpdb $wpdb WordPress database abstraction object.
1597 * @param int $post_id Optional. Post ID to change post type. Default 0.
1598 * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
1599 * name a few. Default 'post'.
1600 * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
1602 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1605 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1606 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1608 clean_post_cache( $post_id );
1614 * Determines whether a post type is considered "viewable".
1616 * For built-in post types such as posts and pages, the 'public' value will be evaluated.
1617 * For all others, the 'publicly_queryable' value will be used.
1620 * @since 4.5.0 Added the ability to pass a post type name in addition to object.
1621 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1623 * @param string|WP_Post_Type $post_type Post type name or object.
1624 * @return bool Whether the post type should be considered viewable.
1626 function is_post_type_viewable( $post_type ) {
1627 if ( is_scalar( $post_type ) ) {
1628 $post_type = get_post_type_object( $post_type );
1629 if ( ! $post_type ) {
1634 return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
1638 * Retrieve list of latest posts or posts matching criteria.
1640 * The defaults are as follows:
1644 * @see WP_Query::parse_query()
1646 * @param array $args {
1647 * Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all
1648 * available arguments.
1650 * @type int $numberposts Total number of posts to retrieve. Is an alias of $posts_per_page
1651 * in WP_Query. Accepts -1 for all. Default 5.
1652 * @type int|string $category Category ID or comma-separated list of IDs (this or any children).
1653 * Is an alias of $cat in WP_Query. Default 0.
1654 * @type array $include An array of post IDs to retrieve, sticky posts will be included.
1655 * Is an alias of $post__in in WP_Query. Default empty array.
1656 * @type array $exclude An array of post IDs not to retrieve. Default empty array.
1657 * @type bool $suppress_filters Whether to suppress filters. Default true.
1659 * @return array List of posts.
1661 function get_posts( $args = null ) {
1664 'category' => 0, 'orderby' => 'date',
1665 'order' => 'DESC', 'include' => array(),
1666 'exclude' => array(), 'meta_key' => '',
1667 'meta_value' =>'', 'post_type' => 'post',
1668 'suppress_filters' => true
1671 $r = wp_parse_args( $args, $defaults );
1672 if ( empty( $r['post_status'] ) )
1673 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1674 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1675 $r['posts_per_page'] = $r['numberposts'];
1676 if ( ! empty($r['category']) )
1677 $r['cat'] = $r['category'];
1678 if ( ! empty($r['include']) ) {
1679 $incposts = wp_parse_id_list( $r['include'] );
1680 $r['posts_per_page'] = count($incposts); // only the number of posts included
1681 $r['post__in'] = $incposts;
1682 } elseif ( ! empty($r['exclude']) )
1683 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1685 $r['ignore_sticky_posts'] = true;
1686 $r['no_found_rows'] = true;
1688 $get_posts = new WP_Query;
1689 return $get_posts->query($r);
1694 // Post meta functions
1698 * Add meta data field to a post.
1700 * Post meta data is called "Custom Fields" on the Administration Screen.
1704 * @param int $post_id Post ID.
1705 * @param string $meta_key Metadata name.
1706 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1707 * @param bool $unique Optional. Whether the same key should not be added.
1709 * @return int|false Meta ID on success, false on failure.
1711 function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
1712 // Make sure meta is added to the post, not a revision.
1713 if ( $the_post = wp_is_post_revision($post_id) )
1714 $post_id = $the_post;
1716 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1720 * Remove metadata matching criteria from a post.
1722 * You can match based on the key, or key and value. Removing based on key and
1723 * value, will keep from removing duplicate metadata with the same key. It also
1724 * allows removing all metadata matching key, if needed.
1728 * @param int $post_id Post ID.
1729 * @param string $meta_key Metadata name.
1730 * @param mixed $meta_value Optional. Metadata value. Must be serializable if
1731 * non-scalar. Default empty.
1732 * @return bool True on success, false on failure.
1734 function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
1735 // Make sure meta is added to the post, not a revision.
1736 if ( $the_post = wp_is_post_revision($post_id) )
1737 $post_id = $the_post;
1739 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1743 * Retrieve post meta field for a post.
1747 * @param int $post_id Post ID.
1748 * @param string $key Optional. The meta key to retrieve. By default, returns
1749 * data for all keys. Default empty.
1750 * @param bool $single Optional. Whether to return a single value. Default false.
1751 * @return mixed Will be an array if $single is false. Will be value of meta data
1752 * field if $single is true.
1754 function get_post_meta( $post_id, $key = '', $single = false ) {
1755 return get_metadata('post', $post_id, $key, $single);
1759 * Update post meta field based on post ID.
1761 * Use the $prev_value parameter to differentiate between meta fields with the
1762 * same key and post ID.
1764 * If the meta field for the post does not exist, it will be added.
1768 * @param int $post_id Post ID.
1769 * @param string $meta_key Metadata key.
1770 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1771 * @param mixed $prev_value Optional. Previous value to check before removing.
1773 * @return int|bool Meta ID if the key didn't exist, true on successful update,
1776 function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
1777 // Make sure meta is added to the post, not a revision.
1778 if ( $the_post = wp_is_post_revision($post_id) )
1779 $post_id = $the_post;
1781 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1785 * Delete everything from post meta matching meta key.
1789 * @param string $post_meta_key Key to search for when deleting.
1790 * @return bool Whether the post meta key was deleted from the database.
1792 function delete_post_meta_by_key( $post_meta_key ) {
1793 return delete_metadata( 'post', null, $post_meta_key, '', true );
1797 * Retrieve post meta fields, based on post ID.
1799 * The post meta fields are retrieved from the cache where possible,
1800 * so the function is optimized to be called more than once.
1804 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1805 * @return array Post meta for the given post.
1807 function get_post_custom( $post_id = 0 ) {
1808 $post_id = absint( $post_id );
1810 $post_id = get_the_ID();
1812 return get_post_meta( $post_id );
1816 * Retrieve meta field names for a post.
1818 * If there are no meta fields, then nothing (null) will be returned.
1822 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1823 * @return array|void Array of the keys, if retrieved.
1825 function get_post_custom_keys( $post_id = 0 ) {
1826 $custom = get_post_custom( $post_id );
1828 if ( !is_array($custom) )
1831 if ( $keys = array_keys($custom) )
1836 * Retrieve values for a custom post field.
1838 * The parameters must not be considered optional. All of the post meta fields
1839 * will be retrieved and only the meta field key values returned.
1843 * @param string $key Optional. Meta field key. Default empty.
1844 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1845 * @return array|null Meta field values.
1847 function get_post_custom_values( $key = '', $post_id = 0 ) {
1851 $custom = get_post_custom($post_id);
1853 return isset($custom[$key]) ? $custom[$key] : null;
1857 * Check if post is sticky.
1859 * Sticky posts should remain at the top of The Loop. If the post ID is not
1860 * given, then The Loop ID for the current post will be used.
1864 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1865 * @return bool Whether post is sticky.
1867 function is_sticky( $post_id = 0 ) {
1868 $post_id = absint( $post_id );
1871 $post_id = get_the_ID();
1873 $stickies = get_option( 'sticky_posts' );
1875 if ( ! is_array( $stickies ) )
1878 if ( in_array( $post_id, $stickies ) )
1885 * Sanitize every post field.
1887 * If the context is 'raw', then the post object or array will get minimal
1888 * sanitization of the integer fields.
1892 * @see sanitize_post_field()
1894 * @param object|WP_Post|array $post The Post Object or Array
1895 * @param string $context Optional. How to sanitize post fields.
1896 * Accepts 'raw', 'edit', 'db', or 'display'.
1897 * Default 'display'.
1898 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the
1899 * same type as $post).
1901 function sanitize_post( $post, $context = 'display' ) {
1902 if ( is_object($post) ) {
1903 // Check if post already filtered for this context.
1904 if ( isset($post->filter) && $context == $post->filter )
1906 if ( !isset($post->ID) )
1908 foreach ( array_keys(get_object_vars($post)) as $field )
1909 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1910 $post->filter = $context;
1911 } elseif ( is_array( $post ) ) {
1912 // Check if post already filtered for this context.
1913 if ( isset($post['filter']) && $context == $post['filter'] )
1915 if ( !isset($post['ID']) )
1917 foreach ( array_keys($post) as $field )
1918 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1919 $post['filter'] = $context;
1925 * Sanitize post field based on context.
1927 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and
1928 * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
1929 * are treated like 'display' when calling filters.
1932 * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
1934 * @param string $field The Post Object field name.
1935 * @param mixed $value The Post Object value.
1936 * @param int $post_id Post ID.
1937 * @param string $context Optional. How to sanitize post fields. Looks for 'raw', 'edit',
1938 * 'db', 'display', 'attribute' and 'js'. Default 'display'.
1939 * @return mixed Sanitized value.
1941 function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
1942 $int_fields = array('ID', 'post_parent', 'menu_order');
1943 if ( in_array($field, $int_fields) )
1944 $value = (int) $value;
1946 // Fields which contain arrays of integers.
1947 $array_int_fields = array( 'ancestors' );
1948 if ( in_array($field, $array_int_fields) ) {
1949 $value = array_map( 'absint', $value);
1953 if ( 'raw' == $context )
1957 if ( false !== strpos($field, 'post_') ) {
1959 $field_no_prefix = str_replace('post_', '', $field);
1962 if ( 'edit' == $context ) {
1963 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1968 * Filters the value of a specific post field to edit.
1970 * The dynamic portion of the hook name, `$field`, refers to the post
1975 * @param mixed $value Value of the post field.
1976 * @param int $post_id Post ID.
1978 $value = apply_filters( "edit_{$field}", $value, $post_id );
1981 * Filters the value of a specific post field to edit.
1983 * The dynamic portion of the hook name, `$field_no_prefix`, refers to
1984 * the post field name.
1988 * @param mixed $value Value of the post field.
1989 * @param int $post_id Post ID.
1991 $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
1993 $value = apply_filters( "edit_post_{$field}", $value, $post_id );
1996 if ( in_array($field, $format_to_edit) ) {
1997 if ( 'post_content' == $field )
1998 $value = format_to_edit($value, user_can_richedit());
2000 $value = format_to_edit($value);
2002 $value = esc_attr($value);
2004 } elseif ( 'db' == $context ) {
2008 * Filters the value of a specific post field before saving.
2010 * The dynamic portion of the hook name, `$field`, refers to the post
2015 * @param mixed $value Value of the post field.
2017 $value = apply_filters( "pre_{$field}", $value );
2020 * Filters the value of a specific field before saving.
2022 * The dynamic portion of the hook name, `$field_no_prefix`, refers
2023 * to the post field name.
2027 * @param mixed $value Value of the post field.
2029 $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
2031 $value = apply_filters( "pre_post_{$field}", $value );
2034 * Filters the value of a specific post field before saving.
2036 * The dynamic portion of the hook name, `$field`, refers to the post
2041 * @param mixed $value Value of the post field.
2043 $value = apply_filters( "{$field}_pre", $value );
2047 // Use display filters by default.
2051 * Filters the value of a specific post field for display.
2053 * The dynamic portion of the hook name, `$field`, refers to the post
2058 * @param mixed $value Value of the prefixed post field.
2059 * @param int $post_id Post ID.
2060 * @param string $context Context for how to sanitize the field. Possible
2061 * values include 'raw', 'edit', 'db', 'display',
2062 * 'attribute' and 'js'.
2064 $value = apply_filters( $field, $value, $post_id, $context );
2066 $value = apply_filters( "post_{$field}", $value, $post_id, $context );
2069 if ( 'attribute' == $context ) {
2070 $value = esc_attr( $value );
2071 } elseif ( 'js' == $context ) {
2072 $value = esc_js( $value );
2080 * Make a post sticky.
2082 * Sticky posts should be displayed at the top of the front page.
2086 * @param int $post_id Post ID.
2088 function stick_post( $post_id ) {
2089 $stickies = get_option('sticky_posts');
2091 if ( !is_array($stickies) )
2092 $stickies = array($post_id);
2094 if ( ! in_array($post_id, $stickies) )
2095 $stickies[] = $post_id;
2097 $updated = update_option( 'sticky_posts', $stickies );
2101 * Fires once a post has been added to the sticky list.
2105 * @param int $post_id ID of the post that was stuck.
2107 do_action( 'post_stuck', $post_id );
2114 * Sticky posts should be displayed at the top of the front page.
2118 * @param int $post_id Post ID.
2120 function unstick_post( $post_id ) {
2121 $stickies = get_option('sticky_posts');
2123 if ( !is_array($stickies) )
2126 if ( ! in_array($post_id, $stickies) )
2129 $offset = array_search($post_id, $stickies);
2130 if ( false === $offset )
2133 array_splice($stickies, $offset, 1);
2135 $updated = update_option( 'sticky_posts', $stickies );
2139 * Fires once a post has been removed from the sticky list.
2143 * @param int $post_id ID of the post that was unstuck.
2145 do_action( 'post_unstuck', $post_id );
2150 * Return the cache key for wp_count_posts() based on the passed arguments.
2154 * @param string $type Optional. Post type to retrieve count Default 'post'.
2155 * @param string $perm Optional. 'readable' or empty. Default empty.
2156 * @return string The cache key.
2158 function _count_posts_cache_key( $type = 'post', $perm = '' ) {
2159 $cache_key = 'posts-' . $type;
2160 if ( 'readable' == $perm && is_user_logged_in() ) {
2161 $post_type_object = get_post_type_object( $type );
2162 if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2163 $cache_key .= '_' . $perm . '_' . get_current_user_id();
2170 * Count number of posts of a post type and if user has permissions to view.
2172 * This function provides an efficient method of finding the amount of post's
2173 * type a blog has. Another method is to count the amount of items in
2174 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2175 * when developing for 2.5+, use this function instead.
2177 * The $perm parameter checks for 'readable' value and if the user can read
2178 * private posts, it will display that for the user that is signed in.
2182 * @global wpdb $wpdb WordPress database abstraction object.
2184 * @param string $type Optional. Post type to retrieve count. Default 'post'.
2185 * @param string $perm Optional. 'readable' or empty. Default empty.
2186 * @return object Number of posts for each status.
2188 function wp_count_posts( $type = 'post', $perm = '' ) {
2191 if ( ! post_type_exists( $type ) )
2192 return new stdClass;
2194 $cache_key = _count_posts_cache_key( $type, $perm );
2196 $counts = wp_cache_get( $cache_key, 'counts' );
2197 if ( false !== $counts ) {
2198 /** This filter is documented in wp-includes/post.php */
2199 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2202 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2203 if ( 'readable' == $perm && is_user_logged_in() ) {
2204 $post_type_object = get_post_type_object($type);
2205 if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2206 $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
2207 get_current_user_id()
2211 $query .= ' GROUP BY post_status';
2213 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2214 $counts = array_fill_keys( get_post_stati(), 0 );
2216 foreach ( $results as $row ) {
2217 $counts[ $row['post_status'] ] = $row['num_posts'];
2220 $counts = (object) $counts;
2221 wp_cache_set( $cache_key, $counts, 'counts' );
2224 * Modify returned post counts by status for the current post type.
2228 * @param object $counts An object containing the current post_type's post
2230 * @param string $type Post type.
2231 * @param string $perm The permission to determine if the posts are 'readable'
2232 * by the current user.
2234 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2238 * Count number of attachments for the mime type(s).
2240 * If you set the optional mime_type parameter, then an array will still be
2241 * returned, but will only have the item you are looking for. It does not give
2242 * you the number of attachments that are children of a post. You can get that
2243 * by counting the number of children that post has.
2247 * @global wpdb $wpdb WordPress database abstraction object.
2249 * @param string|array $mime_type Optional. Array or comma-separated list of
2250 * MIME patterns. Default empty.
2251 * @return object An object containing the attachment counts by mime type.
2253 function wp_count_attachments( $mime_type = '' ) {
2256 $and = wp_post_mime_type_where( $mime_type );
2257 $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
2260 foreach ( (array) $count as $row ) {
2261 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2263 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2266 * Modify returned attachment counts by mime type.
2270 * @param object $counts An object containing the attachment counts by
2272 * @param string $mime_type The mime type pattern used to filter the attachments
2275 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2279 * Get default post mime types.
2283 * @return array List of post mime types.
2285 function get_post_mime_types() {
2286 $post_mime_types = array( // array( adj, noun )
2287 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2288 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2289 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2293 * Filters the default list of post mime types.
2297 * @param array $post_mime_types Default list of post mime types.
2299 return apply_filters( 'post_mime_types', $post_mime_types );
2303 * Check a MIME-Type against a list.
2305 * If the wildcard_mime_types parameter is a string, it must be comma separated
2306 * list. If the real_mime_types is a string, it is also comma separated to
2311 * @param string|array $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
2312 * or flash (same as *flash*).
2313 * @param string|array $real_mime_types Real post mime type values.
2314 * @return array array(wildcard=>array(real types)).
2316 function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
2318 if ( is_string( $wildcard_mime_types ) ) {
2319 $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
2321 if ( is_string( $real_mime_types ) ) {
2322 $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
2325 $patternses = array();
2326 $wild = '[-._a-z0-9]*';
2328 foreach ( (array) $wildcard_mime_types as $type ) {
2329 $mimes = array_map( 'trim', explode( ',', $type ) );
2330 foreach ( $mimes as $mime ) {
2331 $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
2332 $patternses[][$type] = "^$regex$";
2333 if ( false === strpos( $mime, '/' ) ) {
2334 $patternses[][$type] = "^$regex/";
2335 $patternses[][$type] = $regex;
2339 asort( $patternses );
2341 foreach ( $patternses as $patterns ) {
2342 foreach ( $patterns as $type => $pattern ) {
2343 foreach ( (array) $real_mime_types as $real ) {
2344 if ( preg_match( "#$pattern#", $real ) && ( empty( $matches[$type] ) || false === array_search( $real, $matches[$type] ) ) ) {
2345 $matches[$type][] = $real;
2354 * Convert MIME types into SQL.
2358 * @param string|array $post_mime_types List of mime types or comma separated string
2360 * @param string $table_alias Optional. Specify a table alias, if needed.
2362 * @return string The SQL AND clause for mime searching.
2364 function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
2366 $wildcards = array('', '%', '%/%');
2367 if ( is_string($post_mime_types) )
2368 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2372 foreach ( (array) $post_mime_types as $mime_type ) {
2373 $mime_type = preg_replace('/\s/', '', $mime_type);
2374 $slashpos = strpos($mime_type, '/');
2375 if ( false !== $slashpos ) {
2376 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2377 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2378 if ( empty($mime_subgroup) )
2379 $mime_subgroup = '*';
2381 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2382 $mime_pattern = "$mime_group/$mime_subgroup";
2384 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2385 if ( false === strpos($mime_pattern, '*') )
2386 $mime_pattern .= '/*';
2389 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2391 if ( in_array( $mime_type, $wildcards ) )
2394 if ( false !== strpos($mime_pattern, '%') )
2395 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2397 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2399 if ( !empty($wheres) )
2400 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2405 * Trash or delete a post or page.
2407 * When the post and page is permanently deleted, everything that is tied to
2408 * it is deleted also. This includes comments, post meta fields, and terms
2409 * associated with the post.
2411 * The post or page is moved to trash instead of permanently deleted unless
2412 * trash is disabled, item is already in the trash, or $force_delete is true.
2416 * @global wpdb $wpdb WordPress database abstraction object.
2417 * @see wp_delete_attachment()
2418 * @see wp_trash_post()
2420 * @param int $postid Optional. Post ID. Default 0.
2421 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
2423 * @return array|false|WP_Post False on failure.
2425 function wp_delete_post( $postid = 0, $force_delete = false ) {
2428 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2431 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2432 return wp_trash_post( $postid );
2434 if ( $post->post_type == 'attachment' )
2435 return wp_delete_attachment( $postid, $force_delete );
2438 * Filters whether a post deletion should take place.
2442 * @param bool $delete Whether to go forward with deletion.
2443 * @param WP_Post $post Post object.
2444 * @param bool $force_delete Whether to bypass the trash.
2446 $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
2447 if ( null !== $check ) {
2452 * Fires before a post is deleted, at the start of wp_delete_post().
2456 * @see wp_delete_post()
2458 * @param int $postid Post ID.
2460 do_action( 'before_delete_post', $postid );
2462 delete_post_meta($postid,'_wp_trash_meta_status');
2463 delete_post_meta($postid,'_wp_trash_meta_time');
2465 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2467 $parent_data = array( 'post_parent' => $post->post_parent );
2468 $parent_where = array( 'post_parent' => $postid );
2470 if ( is_post_type_hierarchical( $post->post_type ) ) {
2471 // Point children of this page to its parent, also clean the cache of affected children.
2472 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2473 $children = $wpdb->get_results( $children_query );
2475 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2479 // Do raw query. wp_get_post_revisions() is filtered.
2480 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2481 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2482 foreach ( $revision_ids as $revision_id )
2483 wp_delete_post_revision( $revision_id );
2485 // Point all attachments to this post up one level.
2486 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2488 wp_defer_comment_counting( true );
2490 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2491 foreach ( $comment_ids as $comment_id ) {
2492 wp_delete_comment( $comment_id, true );
2495 wp_defer_comment_counting( false );
2497 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2498 foreach ( $post_meta_ids as $mid )
2499 delete_metadata_by_mid( 'post', $mid );
2502 * Fires immediately before a post is deleted from the database.
2506 * @param int $postid Post ID.
2508 do_action( 'delete_post', $postid );
2509 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2515 * Fires immediately after a post is deleted from the database.
2519 * @param int $postid Post ID.
2521 do_action( 'deleted_post', $postid );
2523 clean_post_cache( $post );
2525 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2526 foreach ( $children as $child )
2527 clean_post_cache( $child );
2530 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2533 * Fires after a post is deleted, at the conclusion of wp_delete_post().
2537 * @see wp_delete_post()
2539 * @param int $postid Post ID.
2541 do_action( 'after_delete_post', $postid );
2547 * Reset the page_on_front, show_on_front, and page_for_post settings when
2548 * a linked page is deleted or trashed.
2550 * Also ensures the post is no longer sticky.
2555 * @param int $post_id Post ID.
2557 function _reset_front_page_settings_for_post( $post_id ) {
2558 $post = get_post( $post_id );
2559 if ( 'page' == $post->post_type ) {
2561 * If the page is defined in option page_on_front or post_for_posts,
2562 * adjust the corresponding options.
2564 if ( get_option( 'page_on_front' ) == $post->ID ) {
2565 update_option( 'show_on_front', 'posts' );
2566 update_option( 'page_on_front', 0 );
2568 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2569 delete_option( 'page_for_posts', 0 );
2572 unstick_post( $post->ID );
2576 * Move a post or page to the Trash
2578 * If trash is disabled, the post or page is permanently deleted.
2582 * @see wp_delete_post()
2584 * @param int $post_id Optional. Post ID. Default is ID of the global $post
2585 * if EMPTY_TRASH_DAYS equals true.
2586 * @return false|array|WP_Post|null Post data array, otherwise false.
2588 function wp_trash_post( $post_id = 0 ) {
2589 if ( !EMPTY_TRASH_DAYS )
2590 return wp_delete_post($post_id, true);
2592 if ( !$post = get_post($post_id, ARRAY_A) )
2595 if ( $post['post_status'] == 'trash' )
2599 * Fires before a post is sent to the trash.
2603 * @param int $post_id Post ID.
2605 do_action( 'wp_trash_post', $post_id );
2607 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2608 add_post_meta($post_id,'_wp_trash_meta_time', time());
2610 $post['post_status'] = 'trash';
2611 wp_insert_post( wp_slash( $post ) );
2613 wp_trash_post_comments($post_id);
2616 * Fires after a post is sent to the trash.
2620 * @param int $post_id Post ID.
2622 do_action( 'trashed_post', $post_id );
2628 * Restore a post or page from the Trash.
2632 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2633 * @return WP_Post|false WP_Post object. False on failure.
2635 function wp_untrash_post( $post_id = 0 ) {
2636 if ( !$post = get_post($post_id, ARRAY_A) )
2639 if ( $post['post_status'] != 'trash' )
2643 * Fires before a post is restored from the trash.
2647 * @param int $post_id Post ID.
2649 do_action( 'untrash_post', $post_id );
2651 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2653 $post['post_status'] = $post_status;
2655 delete_post_meta($post_id, '_wp_trash_meta_status');
2656 delete_post_meta($post_id, '_wp_trash_meta_time');
2658 wp_insert_post( wp_slash( $post ) );
2660 wp_untrash_post_comments($post_id);
2663 * Fires after a post is restored from the trash.
2667 * @param int $post_id Post ID.
2669 do_action( 'untrashed_post', $post_id );
2675 * Moves comments for a post to the trash.
2679 * @global wpdb $wpdb WordPress database abstraction object.
2681 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2682 * @return mixed|void False on failure.
2684 function wp_trash_post_comments( $post = null ) {
2687 $post = get_post($post);
2691 $post_id = $post->ID;
2694 * Fires before comments are sent to the trash.
2698 * @param int $post_id Post ID.
2700 do_action( 'trash_post_comments', $post_id );
2702 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2703 if ( empty($comments) )
2706 // Cache current status for each comment.
2707 $statuses = array();
2708 foreach ( $comments as $comment )
2709 $statuses[$comment->comment_ID] = $comment->comment_approved;
2710 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2712 // Set status for all comments to post-trashed.
2713 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2715 clean_comment_cache( array_keys($statuses) );
2718 * Fires after comments are sent to the trash.
2722 * @param int $post_id Post ID.
2723 * @param array $statuses Array of comment statuses.
2725 do_action( 'trashed_post_comments', $post_id, $statuses );
2731 * Restore comments for a post from the trash.
2735 * @global wpdb $wpdb WordPress database abstraction object.
2737 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2740 function wp_untrash_post_comments( $post = null ) {
2743 $post = get_post($post);
2747 $post_id = $post->ID;
2749 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2751 if ( empty($statuses) )
2755 * Fires before comments are restored for a post from the trash.
2759 * @param int $post_id Post ID.
2761 do_action( 'untrash_post_comments', $post_id );
2763 // Restore each comment to its original status.
2764 $group_by_status = array();
2765 foreach ( $statuses as $comment_id => $comment_status )
2766 $group_by_status[$comment_status][] = $comment_id;
2768 foreach ( $group_by_status as $status => $comments ) {
2769 // Sanity check. This shouldn't happen.
2770 if ( 'post-trashed' == $status ) {
2773 $comments_in = implode( ', ', array_map( 'intval', $comments ) );
2774 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
2777 clean_comment_cache( array_keys($statuses) );
2779 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2782 * Fires after comments are restored for a post from the trash.
2786 * @param int $post_id Post ID.
2788 do_action( 'untrashed_post_comments', $post_id );
2792 * Retrieve the list of categories for a post.
2794 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2795 * away from the complexity of the taxonomy layer.
2799 * @see wp_get_object_terms()
2801 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2802 * global $post. Default 0.
2803 * @param array $args Optional. Category arguments. See wp_get_object_terms(). Default empty.
2804 * @return array List of categories. If the `$fields` argument passed via `$args` is 'all' or
2805 * 'all_with_object_id', an array of WP_Term objects will be returned. If `$fields`
2806 * is 'ids', an array of category ids. If `$fields` is 'names', an array of category names.
2808 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2809 $post_id = (int) $post_id;
2811 $defaults = array('fields' => 'ids');
2812 $args = wp_parse_args( $args, $defaults );
2814 $cats = wp_get_object_terms($post_id, 'category', $args);
2819 * Retrieve the tags for a post.
2821 * There is only one default for this function, called 'fields' and by default
2822 * is set to 'all'. There are other defaults that can be overridden in
2823 * wp_get_object_terms().
2827 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2828 * global $post. Default 0.
2829 * @param array $args Optional. Overwrite the defaults
2830 * @return array List of post tags.
2832 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2833 return wp_get_post_terms( $post_id, 'post_tag', $args);
2837 * Retrieve the terms for a post.
2839 * There is only one default for this function, called 'fields' and by default
2840 * is set to 'all'. There are other defaults that can be overridden in
2841 * wp_get_object_terms().
2845 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2846 * global $post. Default 0.
2847 * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
2848 * @param array $args Optional. wp_get_object_terms() arguments. Default empty array.
2849 * @return array|WP_Error List of post terms or empty array if no terms were found. WP_Error object
2850 * if `$taxonomy` doesn't exist.
2852 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2853 $post_id = (int) $post_id;
2855 $defaults = array('fields' => 'all');
2856 $args = wp_parse_args( $args, $defaults );
2858 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2864 * Retrieve a number of recent posts.
2870 * @param array $args Optional. Arguments to retrieve posts. Default empty array.
2871 * @param string $output Optional. The required return type. One of OBJECT or ARRAY_A, which correspond to
2872 * a WP_Post object or an associative array, respectively. Default ARRAY_A.
2873 * @return array|false Array of recent posts, where the type of each element is determined by $output parameter.
2874 * Empty array on failure.
2876 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2878 if ( is_numeric( $args ) ) {
2879 _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2880 $args = array( 'numberposts' => absint( $args ) );
2883 // Set default arguments.
2885 'numberposts' => 10, 'offset' => 0,
2886 'category' => 0, 'orderby' => 'post_date',
2887 'order' => 'DESC', 'include' => '',
2888 'exclude' => '', 'meta_key' => '',
2889 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2890 'suppress_filters' => true
2893 $r = wp_parse_args( $args, $defaults );
2895 $results = get_posts( $r );
2897 // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
2898 if ( ARRAY_A == $output ){
2899 foreach ( $results as $key => $result ) {
2900 $results[$key] = get_object_vars( $result );
2902 return $results ? $results : array();
2905 return $results ? $results : false;
2910 * Insert or update a post.
2912 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2914 * You can set the post date manually, by setting the values for 'post_date'
2915 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2916 * setting the value for 'comment_status' key.
2919 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
2920 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
2922 * @see sanitize_post()
2923 * @global wpdb $wpdb WordPress database abstraction object.
2925 * @param array $postarr {
2926 * An array of elements that make up a post to update or insert.
2928 * @type int $ID The post ID. If equal to something other than 0,
2929 * the post with that ID will be updated. Default 0.
2930 * @type int $post_author The ID of the user who added the post. Default is
2931 * the current user ID.
2932 * @type string $post_date The date of the post. Default is the current time.
2933 * @type string $post_date_gmt The date of the post in the GMT timezone. Default is
2934 * the value of `$post_date`.
2935 * @type mixed $post_content The post content. Default empty.
2936 * @type string $post_content_filtered The filtered post content. Default empty.
2937 * @type string $post_title The post title. Default empty.
2938 * @type string $post_excerpt The post excerpt. Default empty.
2939 * @type string $post_status The post status. Default 'draft'.
2940 * @type string $post_type The post type. Default 'post'.
2941 * @type string $comment_status Whether the post can accept comments. Accepts 'open' or 'closed'.
2942 * Default is the value of 'default_comment_status' option.
2943 * @type string $ping_status Whether the post can accept pings. Accepts 'open' or 'closed'.
2944 * Default is the value of 'default_ping_status' option.
2945 * @type string $post_password The password to access the post. Default empty.
2946 * @type string $post_name The post name. Default is the sanitized post title
2947 * when creating a new post.
2948 * @type string $to_ping Space or carriage return-separated list of URLs to ping.
2950 * @type string $pinged Space or carriage return-separated list of URLs that have
2951 * been pinged. Default empty.
2952 * @type string $post_modified The date when the post was last modified. Default is
2954 * @type string $post_modified_gmt The date when the post was last modified in the GMT
2955 * timezone. Default is the current time.
2956 * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
2957 * @type int $menu_order The order the post should be displayed in. Default 0.
2958 * @type string $post_mime_type The mime type of the post. Default empty.
2959 * @type string $guid Global Unique ID for referencing the post. Default empty.
2960 * @type array $post_category Array of category names, slugs, or IDs.
2961 * Defaults to value of the 'default_category' option.
2962 * @type array $tax_input Array of taxonomy terms keyed by their taxonomy name. Default empty.
2963 * @type array $meta_input Array of post meta values keyed by their post meta key. Default empty.
2965 * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
2966 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2968 function wp_insert_post( $postarr, $wp_error = false ) {
2971 $user_id = get_current_user_id();
2974 'post_author' => $user_id,
2975 'post_content' => '',
2976 'post_content_filtered' => '',
2978 'post_excerpt' => '',
2979 'post_status' => 'draft',
2980 'post_type' => 'post',
2981 'comment_status' => '',
2982 'ping_status' => '',
2983 'post_password' => '',
2993 $postarr = wp_parse_args($postarr, $defaults);
2995 unset( $postarr[ 'filter' ] );
2997 $postarr = sanitize_post($postarr, 'db');
2999 // Are we updating or creating?
3002 $guid = $postarr['guid'];
3004 if ( ! empty( $postarr['ID'] ) ) {
3007 // Get the post ID and GUID.
3008 $post_ID = $postarr['ID'];
3009 $post_before = get_post( $post_ID );
3010 if ( is_null( $post_before ) ) {
3012 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3017 $guid = get_post_field( 'guid', $post_ID );
3018 $previous_status = get_post_field('post_status', $post_ID );
3020 $previous_status = 'new';
3023 $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
3025 $post_title = $postarr['post_title'];
3026 $post_content = $postarr['post_content'];
3027 $post_excerpt = $postarr['post_excerpt'];
3028 if ( isset( $postarr['post_name'] ) ) {
3029 $post_name = $postarr['post_name'];
3030 } elseif ( $update ) {
3031 // For an update, don't modify the post_name if it wasn't supplied as an argument.
3032 $post_name = $post_before->post_name;
3035 $maybe_empty = 'attachment' !== $post_type
3036 && ! $post_content && ! $post_title && ! $post_excerpt
3037 && post_type_supports( $post_type, 'editor' )
3038 && post_type_supports( $post_type, 'title' )
3039 && post_type_supports( $post_type, 'excerpt' );
3042 * Filters whether the post should be considered "empty".
3044 * The post is considered "empty" if both:
3045 * 1. The post type supports the title, editor, and excerpt fields
3046 * 2. The title, editor, and excerpt fields are all empty
3048 * Returning a truthy value to the filter will effectively short-circuit
3049 * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
3050 * will be returned instead.
3054 * @param bool $maybe_empty Whether the post should be considered "empty".
3055 * @param array $postarr Array of post data.
3057 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
3059 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
3065 $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
3066 if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash', 'auto-draft' ), true ) ) {
3067 $post_status = 'inherit';
3070 if ( ! empty( $postarr['post_category'] ) ) {
3071 // Filter out empty terms.
3072 $post_category = array_filter( $postarr['post_category'] );
3075 // Make sure we set a valid category.
3076 if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
3077 // 'post' requires at least one category.
3078 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3079 $post_category = array( get_option('default_category') );
3081 $post_category = array();
3085 // Don't allow contributors to set the post slug for pending review posts.
3086 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
3091 * Create a valid post name. Drafts and pending posts are allowed to have
3092 * an empty post name.
3094 if ( empty($post_name) ) {
3095 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3096 $post_name = sanitize_title($post_title);
3101 // On updates, we need to check to see if it's using the old, fixed sanitization context.
3102 $check_name = sanitize_title( $post_name, '', 'old-save' );
3103 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
3104 $post_name = $check_name;
3105 } else { // new post, or slug has changed.
3106 $post_name = sanitize_title($post_name);
3111 * If the post date is empty (due to having been new or a draft) and status
3112 * is not 'draft' or 'pending', set date to now.
3114 if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
3115 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3116 $post_date = current_time( 'mysql' );
3118 $post_date = get_date_from_gmt( $postarr['post_date_gmt'] );
3121 $post_date = $postarr['post_date'];
3124 // Validate the date.
3125 $mm = substr( $post_date, 5, 2 );
3126 $jj = substr( $post_date, 8, 2 );
3127 $aa = substr( $post_date, 0, 4 );
3128 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
3129 if ( ! $valid_date ) {
3131 return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
3137 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3138 if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3139 $post_date_gmt = get_gmt_from_date( $post_date );
3141 $post_date_gmt = '0000-00-00 00:00:00';
3144 $post_date_gmt = $postarr['post_date_gmt'];
3147 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
3148 $post_modified = current_time( 'mysql' );
3149 $post_modified_gmt = current_time( 'mysql', 1 );
3151 $post_modified = $post_date;
3152 $post_modified_gmt = $post_date_gmt;
3155 if ( 'attachment' !== $post_type ) {
3156 if ( 'publish' == $post_status ) {
3157 $now = gmdate('Y-m-d H:i:59');
3158 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
3159 $post_status = 'future';
3161 } elseif ( 'future' == $post_status ) {
3162 $now = gmdate('Y-m-d H:i:59');
3163 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) {
3164 $post_status = 'publish';
3170 if ( empty( $postarr['comment_status'] ) ) {
3172 $comment_status = 'closed';
3174 $comment_status = get_default_comment_status( $post_type );
3177 $comment_status = $postarr['comment_status'];
3180 // These variables are needed by compact() later.
3181 $post_content_filtered = $postarr['post_content_filtered'];
3182 $post_author = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
3183 $ping_status = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
3184 $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
3185 $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
3186 $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
3189 * The 'wp_insert_post_parent' filter expects all variables to be present.
3190 * Previously, these variables would have already been extracted
3192 if ( isset( $postarr['menu_order'] ) ) {
3193 $menu_order = (int) $postarr['menu_order'];
3198 $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
3199 if ( 'private' == $post_status ) {
3200 $post_password = '';
3203 if ( isset( $postarr['post_parent'] ) ) {
3204 $post_parent = (int) $postarr['post_parent'];
3210 * Filters the post parent -- used to check for and prevent hierarchy loops.
3214 * @param int $post_parent Post parent ID.
3215 * @param int $post_ID Post ID.
3216 * @param array $new_postarr Array of parsed post data.
3217 * @param array $postarr Array of sanitized, but otherwise unmodified post data.
3219 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
3222 * If the post is being untrashed and it has a desired slug stored in post meta,
3225 if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
3226 $desired_post_slug = get_post_meta( $post_ID, '_wp_desired_post_slug', true );
3227 if ( $desired_post_slug ) {
3228 delete_post_meta( $post_ID, '_wp_desired_post_slug' );
3229 $post_name = $desired_post_slug;
3233 // If a trashed post has the desired slug, change it and let this post have it.
3234 if ( 'trash' !== $post_status && $post_name ) {
3235 wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID );
3238 // When trashing an existing post, change its slug to allow non-trashed posts to use it.
3239 if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
3240 $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_ID );
3243 $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
3246 $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
3248 // Expected_slashed (everything!).
3249 $data = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' );
3251 $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
3253 foreach ( $emoji_fields as $emoji_field ) {
3254 if ( isset( $data[ $emoji_field ] ) ) {
3255 $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
3256 if ( 'utf8' === $charset ) {
3257 $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
3262 if ( 'attachment' === $post_type ) {
3264 * Filters attachment post data before it is updated in or added to the database.
3268 * @param array $data An array of sanitized attachment post data.
3269 * @param array $postarr An array of unsanitized attachment post data.
3271 $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
3274 * Filters slashed post data just before it is inserted into the database.
3278 * @param array $data An array of slashed post data.
3279 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3281 $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
3283 $data = wp_unslash( $data );
3284 $where = array( 'ID' => $post_ID );
3288 * Fires immediately before an existing post is updated in the database.
3292 * @param int $post_ID Post ID.
3293 * @param array $data Array of unslashed post data.
3295 do_action( 'pre_post_update', $post_ID, $data );
3296 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
3298 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
3304 // If there is a suggested ID, use it if not already present.
3305 if ( ! empty( $import_id ) ) {
3306 $import_id = (int) $import_id;
3307 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3308 $data['ID'] = $import_id;
3311 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
3313 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
3318 $post_ID = (int) $wpdb->insert_id;
3320 // Use the newly generated $post_ID.
3321 $where = array( 'ID' => $post_ID );
3324 if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
3325 $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_ID ), $post_ID, $data['post_status'], $post_type, $post_parent );
3326 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
3327 clean_post_cache( $post_ID );
3330 if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
3331 wp_set_post_categories( $post_ID, $post_category );
3334 if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
3335 wp_set_post_tags( $post_ID, $postarr['tags_input'] );
3338 // New-style support for all custom taxonomies.
3339 if ( ! empty( $postarr['tax_input'] ) ) {
3340 foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
3341 $taxonomy_obj = get_taxonomy($taxonomy);
3342 if ( ! $taxonomy_obj ) {
3343 /* translators: %s: taxonomy name */
3344 _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
3348 // array = hierarchical, string = non-hierarchical.
3349 if ( is_array( $tags ) ) {
3350 $tags = array_filter($tags);
3352 if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
3353 wp_set_post_terms( $post_ID, $tags, $taxonomy );
3358 if ( ! empty( $postarr['meta_input'] ) ) {
3359 foreach ( $postarr['meta_input'] as $field => $value ) {
3360 update_post_meta( $post_ID, $field, $value );
3364 $current_guid = get_post_field( 'guid', $post_ID );
3367 if ( ! $update && '' == $current_guid ) {
3368 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
3371 if ( 'attachment' === $postarr['post_type'] ) {
3372 if ( ! empty( $postarr['file'] ) ) {
3373 update_attached_file( $post_ID, $postarr['file'] );
3376 if ( ! empty( $postarr['context'] ) ) {
3377 add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
3381 // Set or remove featured image.
3382 if ( isset( $postarr['_thumbnail_id'] ) ) {
3383 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
3384 if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
3385 if ( wp_attachment_is( 'audio', $post_ID ) ) {
3386 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3387 } elseif ( wp_attachment_is( 'video', $post_ID ) ) {
3388 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3392 if ( $thumbnail_support ) {
3393 $thumbnail_id = intval( $postarr['_thumbnail_id'] );
3394 if ( -1 === $thumbnail_id ) {
3395 delete_post_thumbnail( $post_ID );
3397 set_post_thumbnail( $post_ID, $thumbnail_id );
3402 clean_post_cache( $post_ID );
3404 $post = get_post( $post_ID );
3406 if ( ! empty( $postarr['page_template'] ) ) {
3407 $post->page_template = $postarr['page_template'];
3408 $page_templates = wp_get_theme()->get_page_templates( $post );
3409 if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
3411 return new WP_Error( 'invalid_page_template', __( 'Invalid page template.' ) );
3413 update_post_meta( $post_ID, '_wp_page_template', 'default' );
3415 update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
3419 if ( 'attachment' !== $postarr['post_type'] ) {
3420 wp_transition_post_status( $data['post_status'], $previous_status, $post );
3424 * Fires once an existing attachment has been updated.
3428 * @param int $post_ID Attachment ID.
3430 do_action( 'edit_attachment', $post_ID );
3431 $post_after = get_post( $post_ID );
3434 * Fires once an existing attachment has been updated.
3438 * @param int $post_ID Post ID.
3439 * @param WP_Post $post_after Post object following the update.
3440 * @param WP_Post $post_before Post object before the update.
3442 do_action( 'attachment_updated', $post_ID, $post_after, $post_before );
3446 * Fires once an attachment has been added.
3450 * @param int $post_ID Attachment ID.
3452 do_action( 'add_attachment', $post_ID );
3460 * Fires once an existing post has been updated.
3464 * @param int $post_ID Post ID.
3465 * @param WP_Post $post Post object.
3467 do_action( 'edit_post', $post_ID, $post );
3468 $post_after = get_post($post_ID);
3471 * Fires once an existing post has been updated.
3475 * @param int $post_ID Post ID.
3476 * @param WP_Post $post_after Post object following the update.
3477 * @param WP_Post $post_before Post object before the update.
3479 do_action( 'post_updated', $post_ID, $post_after, $post_before);
3483 * Fires once a post has been saved.
3485 * The dynamic portion of the hook name, `$post->post_type`, refers to
3486 * the post type slug.
3490 * @param int $post_ID Post ID.
3491 * @param WP_Post $post Post object.
3492 * @param bool $update Whether this is an existing post being updated or not.
3494 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
3497 * Fires once a post has been saved.
3501 * @param int $post_ID Post ID.
3502 * @param WP_Post $post Post object.
3503 * @param bool $update Whether this is an existing post being updated or not.
3505 do_action( 'save_post', $post_ID, $post, $update );
3508 * Fires once a post has been saved.
3512 * @param int $post_ID Post ID.
3513 * @param WP_Post $post Post object.
3514 * @param bool $update Whether this is an existing post being updated or not.
3516 do_action( 'wp_insert_post', $post_ID, $post, $update );
3522 * Update a post with new post data.
3524 * The date does not have to be set for drafts. You can set the date and it will
3525 * not be overridden.
3529 * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
3530 * objects are not. Default array.
3531 * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
3532 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
3534 function wp_update_post( $postarr = array(), $wp_error = false ) {
3535 if ( is_object($postarr) ) {
3536 // Non-escaped post was passed.
3537 $postarr = get_object_vars($postarr);
3538 $postarr = wp_slash($postarr);
3541 // First, get all of the original fields.
3542 $post = get_post($postarr['ID'], ARRAY_A);
3544 if ( is_null( $post ) ) {
3546 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3550 // Escape data pulled from DB.
3551 $post = wp_slash($post);
3553 // Passed post category list overwrites existing category list if not empty.
3554 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3555 && 0 != count($postarr['post_category']) )
3556 $post_cats = $postarr['post_category'];
3558 $post_cats = $post['post_category'];
3560 // Drafts shouldn't be assigned a date unless explicitly done so by the user.
3561 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3562 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3565 $clear_date = false;
3567 // Merge old and new fields with new fields overwriting old ones.
3568 $postarr = array_merge($post, $postarr);
3569 $postarr['post_category'] = $post_cats;
3570 if ( $clear_date ) {
3571 $postarr['post_date'] = current_time('mysql');
3572 $postarr['post_date_gmt'] = '';
3575 if ($postarr['post_type'] == 'attachment')
3576 return wp_insert_attachment($postarr);
3578 return wp_insert_post( $postarr, $wp_error );
3582 * Publish a post by transitioning the post status.
3586 * @global wpdb $wpdb WordPress database abstraction object.
3588 * @param int|WP_Post $post Post ID or post object.
3590 function wp_publish_post( $post ) {
3593 if ( ! $post = get_post( $post ) )
3596 if ( 'publish' == $post->post_status )
3599 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3601 clean_post_cache( $post->ID );
3603 $old_status = $post->post_status;
3604 $post->post_status = 'publish';
3605 wp_transition_post_status( 'publish', $old_status, $post );
3607 /** This action is documented in wp-includes/post.php */
3608 do_action( 'edit_post', $post->ID, $post );
3610 /** This action is documented in wp-includes/post.php */
3611 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3613 /** This action is documented in wp-includes/post.php */
3614 do_action( 'save_post', $post->ID, $post, true );
3616 /** This action is documented in wp-includes/post.php */
3617 do_action( 'wp_insert_post', $post->ID, $post, true );
3621 * Publish future post and make sure post ID has future post status.
3623 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3624 * from publishing drafts, etc.
3628 * @param int|WP_Post $post_id Post ID or post object.
3630 function check_and_publish_future_post( $post_id ) {
3631 $post = get_post($post_id);
3636 if ( 'future' != $post->post_status )
3639 $time = strtotime( $post->post_date_gmt . ' GMT' );
3641 // Uh oh, someone jumped the gun!
3642 if ( $time > time() ) {
3643 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3644 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3648 // wp_publish_post() returns no meaningful value.
3649 wp_publish_post( $post_id );
3653 * Computes a unique slug for the post, when given the desired slug and some post details.
3657 * @global wpdb $wpdb WordPress database abstraction object.
3658 * @global WP_Rewrite $wp_rewrite
3660 * @param string $slug The desired slug (post_name).
3661 * @param int $post_ID Post ID.
3662 * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
3663 * @param string $post_type Post type.
3664 * @param int $post_parent Post parent ID.
3665 * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3667 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3668 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3671 global $wpdb, $wp_rewrite;
3673 $original_slug = $slug;
3675 $feeds = $wp_rewrite->feeds;
3676 if ( ! is_array( $feeds ) )
3679 if ( 'attachment' == $post_type ) {
3680 // Attachment slugs must be unique across all types.
3681 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3682 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3685 * Filters whether the post slug would make a bad attachment slug.
3689 * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
3690 * @param string $slug The post slug.
3692 if ( $post_name_check || in_array( $slug, $feeds ) || 'embed' === $slug || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3695 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3696 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3698 } while ( $post_name_check );
3699 $slug = $alt_post_name;
3701 } elseif ( is_post_type_hierarchical( $post_type ) ) {
3702 if ( 'nav_menu_item' == $post_type )
3706 * Page slugs must be unique within their own trees. Pages are in a separate
3707 * namespace than posts so page slugs are allowed to overlap post slugs.
3709 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1";
3710 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
3713 * Filters whether the post slug would make a bad hierarchical post slug.
3717 * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
3718 * @param string $slug The post slug.
3719 * @param string $post_type Post type.
3720 * @param int $post_parent Post parent ID.
3722 if ( $post_name_check || in_array( $slug, $feeds ) || 'embed' === $slug || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
3725 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3726 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
3728 } while ( $post_name_check );
3729 $slug = $alt_post_name;
3732 // Post slugs must be unique across all posts.
3733 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3734 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3736 // Prevent new post slugs that could result in URLs that conflict with date archives.
3737 $post = get_post( $post_ID );
3738 $conflicts_with_date_archive = false;
3739 if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) && $slug_num = intval( $slug ) ) {
3740 $permastructs = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
3741 $postname_index = array_search( '%postname%', $permastructs );
3744 * Potential date clashes are as follows:
3746 * - Any integer in the first permastruct position could be a year.
3747 * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
3748 * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
3750 if ( 0 === $postname_index ||
3751 ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
3752 ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
3754 $conflicts_with_date_archive = true;
3759 * Filters whether the post slug would be bad as a flat slug.
3763 * @param bool $bad_slug Whether the post slug would be bad as a flat slug.
3764 * @param string $slug The post slug.
3765 * @param string $post_type Post type.
3767 if ( $post_name_check || in_array( $slug, $feeds ) || 'embed' === $slug || $conflicts_with_date_archive || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3770 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3771 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3773 } while ( $post_name_check );
3774 $slug = $alt_post_name;
3779 * Filters the unique post slug.
3783 * @param string $slug The post slug.
3784 * @param int $post_ID Post ID.
3785 * @param string $post_status The post status.
3786 * @param string $post_type Post type.
3787 * @param int $post_parent Post parent ID
3788 * @param string $original_slug The original post slug.
3790 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3794 * Truncate a post slug.
3799 * @see utf8_uri_encode()
3801 * @param string $slug The slug to truncate.
3802 * @param int $length Optional. Max length of the slug. Default 200 (characters).
3803 * @return string The truncated slug.
3805 function _truncate_post_slug( $slug, $length = 200 ) {
3806 if ( strlen( $slug ) > $length ) {
3807 $decoded_slug = urldecode( $slug );
3808 if ( $decoded_slug === $slug )
3809 $slug = substr( $slug, 0, $length );
3811 $slug = utf8_uri_encode( $decoded_slug, $length );
3814 return rtrim( $slug, '-' );
3818 * Add tags to a post.
3820 * @see wp_set_post_tags()
3824 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3825 * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
3826 * separated by commas. Default empty.
3827 * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3829 function wp_add_post_tags( $post_id = 0, $tags = '' ) {
3830 return wp_set_post_tags($post_id, $tags, true);
3834 * Set the tags for a post.
3838 * @see wp_set_object_terms()
3840 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3841 * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
3842 * separated by commas. Default empty.
3843 * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
3844 * replace the tags with the new tags. Default false.
3845 * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
3847 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3848 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3852 * Set the terms for a post.
3856 * @see wp_set_object_terms()
3858 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3859 * @param string|array $tags Optional. An array of terms to set for the post, or a string of terms
3860 * separated by commas. Default empty.
3861 * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
3862 * @param bool $append Optional. If true, don't delete existing terms, just add on. If false,
3863 * replace the terms with the new terms. Default false.
3864 * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
3866 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3867 $post_id = (int) $post_id;
3875 if ( ! is_array( $tags ) ) {
3876 $comma = _x( ',', 'tag delimiter' );
3877 if ( ',' !== $comma )
3878 $tags = str_replace( $comma, ',', $tags );
3879 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3883 * Hierarchical taxonomies must always pass IDs rather than names so that
3884 * children with the same names but different parents aren't confused.
3886 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3887 $tags = array_unique( array_map( 'intval', $tags ) );
3890 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3894 * Set categories for a post.
3896 * If the post categories parameter is not set, then the default category is
3901 * @param int $post_ID Optional. The Post ID. Does not default to the ID
3902 * of the global $post. Default 0.
3903 * @param array|int $post_categories Optional. List of categories or ID of category.
3904 * Default empty array.
3905 * @param bool $append If true, don't delete existing categories, just add on.
3906 * If false, replace the categories with the new categories.
3907 * @return array|false|WP_Error Array of term taxonomy IDs of affected categories. WP_Error or false on failure.
3909 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3910 $post_ID = (int) $post_ID;
3911 $post_type = get_post_type( $post_ID );
3912 $post_status = get_post_status( $post_ID );
3913 // If $post_categories isn't already an array, make it one:
3914 $post_categories = (array) $post_categories;
3915 if ( empty( $post_categories ) ) {
3916 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3917 $post_categories = array( get_option('default_category') );
3920 $post_categories = array();
3922 } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) {
3926 return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3930 * Fires actions related to the transitioning of a post's status.
3932 * When a post is saved, the post status is "transitioned" from one status to another,
3933 * though this does not always mean the status has actually changed before and after
3934 * the save. This function fires a number of action hooks related to that transition:
3935 * the generic {@see 'transition_post_status'} action, as well as the dynamic hooks
3936 * {@see '$old_status_to_$new_status'} and {@see '$new_status_$post->post_type'}. Note
3937 * that the function does not transition the post object in the database.
3939 * For instance: When publishing a post for the first time, the post status may transition
3940 * from 'draft' – or some other status – to 'publish'. However, if a post is already
3941 * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
3942 * before and after the transition.
3946 * @param string $new_status Transition to this post status.
3947 * @param string $old_status Previous post status.
3948 * @param WP_Post $post Post data.
3950 function wp_transition_post_status( $new_status, $old_status, $post ) {
3952 * Fires when a post is transitioned from one status to another.
3956 * @param string $new_status New post status.
3957 * @param string $old_status Old post status.
3958 * @param WP_Post $post Post object.
3960 do_action( 'transition_post_status', $new_status, $old_status, $post );
3963 * Fires when a post is transitioned from one status to another.
3965 * The dynamic portions of the hook name, `$new_status` and `$old status`,
3966 * refer to the old and new post statuses, respectively.
3970 * @param WP_Post $post Post object.
3972 do_action( "{$old_status}_to_{$new_status}", $post );
3975 * Fires when a post is transitioned from one status to another.
3977 * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
3978 * refer to the new post status and post type, respectively.
3980 * Please note: When this action is hooked using a particular post status (like
3981 * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
3982 * first transitioned to that status from something else, as well as upon
3983 * subsequent post updates (old and new status are both the same).
3985 * Therefore, if you are looking to only fire a callback when a post is first
3986 * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
3990 * @param int $post_id Post ID.
3991 * @param WP_Post $post Post object.
3993 do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
3997 // Comment, trackback, and pingback functions.
4001 * Add a URL to those already pinged.
4004 * @since 4.7.0 $post_id can be a WP_Post object.
4005 * @since 4.7.0 $uri can be an array of URIs.
4007 * @global wpdb $wpdb WordPress database abstraction object.
4009 * @param int|WP_Post $post_id Post object or ID.
4010 * @param string|array $uri Ping URI or array of URIs.
4011 * @return int|false How many rows were updated.
4013 function add_ping( $post_id, $uri ) {
4016 $post = get_post( $post_id );
4021 $pung = trim( $post->pinged );
4022 $pung = preg_split( '/\s/', $pung );
4024 if ( is_array( $uri ) ) {
4025 $pung = array_merge( $pung, $uri );
4030 $new = implode("\n", $pung);
4033 * Filters the new ping URL to add for the given post.
4037 * @param string $new New ping URL to add.
4039 $new = apply_filters( 'add_ping', $new );
4041 $return = $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post->ID ) );
4042 clean_post_cache( $post->ID );
4047 * Retrieve enclosures already enclosed for a post.
4051 * @param int $post_id Post ID.
4052 * @return array List of enclosures.
4054 function get_enclosed( $post_id ) {
4055 $custom_fields = get_post_custom( $post_id );
4057 if ( !is_array( $custom_fields ) )
4060 foreach ( $custom_fields as $key => $val ) {
4061 if ( 'enclosure' != $key || !is_array( $val ) )
4063 foreach ( $val as $enc ) {
4064 $enclosure = explode( "\n", $enc );
4065 $pung[] = trim( $enclosure[ 0 ] );
4070 * Filters the list of enclosures already enclosed for the given post.
4074 * @param array $pung Array of enclosures for the given post.
4075 * @param int $post_id Post ID.
4077 return apply_filters( 'get_enclosed', $pung, $post_id );
4081 * Retrieve URLs already pinged for a post.
4085 * @since 4.7.0 $post_id can be a WP_Post object.
4087 * @param int|WP_Post $post_id Post ID or object.
4090 function get_pung( $post_id ) {
4091 $post = get_post( $post_id );
4096 $pung = trim( $post->pinged );
4097 $pung = preg_split( '/\s/', $pung );
4100 * Filters the list of already-pinged URLs for the given post.
4104 * @param array $pung Array of URLs already pinged for the given post.
4106 return apply_filters( 'get_pung', $pung );
4110 * Retrieve URLs that need to be pinged.
4113 * @since 4.7.0 $post_id can be a WP_Post object.
4115 * @param int|WP_Post $post_id Post Object or ID
4118 function get_to_ping( $post_id ) {
4119 $post = get_post( $post_id );
4125 $to_ping = sanitize_trackback_urls( $post->to_ping );
4126 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
4129 * Filters the list of URLs yet to ping for the given post.
4133 * @param array $to_ping List of URLs yet to ping.
4135 return apply_filters( 'get_to_ping', $to_ping );
4139 * Do trackbacks for a list of URLs.
4143 * @param string $tb_list Comma separated list of URLs.
4144 * @param int $post_id Post ID.
4146 function trackback_url_list( $tb_list, $post_id ) {
4147 if ( ! empty( $tb_list ) ) {
4149 $postdata = get_post( $post_id, ARRAY_A );
4152 $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
4154 if ( strlen( $excerpt ) > 255 ) {
4155 $excerpt = substr( $excerpt, 0, 252 ) . '…';
4158 $trackback_urls = explode( ',', $tb_list );
4159 foreach ( (array) $trackback_urls as $tb_url ) {
4160 $tb_url = trim( $tb_url );
4161 trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
4171 * Get a list of page IDs.
4175 * @global wpdb $wpdb WordPress database abstraction object.
4177 * @return array List of page IDs.
4179 function get_all_page_ids() {
4182 $page_ids = wp_cache_get('all_page_ids', 'posts');
4183 if ( ! is_array( $page_ids ) ) {
4184 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
4185 wp_cache_add('all_page_ids', $page_ids, 'posts');
4192 * Retrieves page data given a page ID or page object.
4194 * Use get_post() instead of get_page().
4197 * @deprecated 3.5.0 Use get_post()
4199 * @param mixed $page Page object or page ID. Passed by reference.
4200 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
4201 * a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT.
4202 * @param string $filter Optional. How the return value should be filtered. Accepts 'raw',
4203 * 'edit', 'db', 'display'. Default 'raw'.
4204 * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
4206 function get_page( $page, $output = OBJECT, $filter = 'raw') {
4207 return get_post( $page, $output, $filter );
4211 * Retrieves a page given its path.
4215 * @global wpdb $wpdb WordPress database abstraction object.
4217 * @param string $page_path Page path.
4218 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
4219 * a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT.
4220 * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4221 * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
4223 function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
4226 $last_changed = wp_cache_get_last_changed( 'posts' );
4228 $hash = md5( $page_path . serialize( $post_type ) );
4229 $cache_key = "get_page_by_path:$hash:$last_changed";
4230 $cached = wp_cache_get( $cache_key, 'posts' );
4231 if ( false !== $cached ) {
4232 // Special case: '0' is a bad `$page_path`.
4233 if ( '0' === $cached || 0 === $cached ) {
4236 return get_post( $cached, $output );
4240 $page_path = rawurlencode(urldecode($page_path));
4241 $page_path = str_replace('%2F', '/', $page_path);
4242 $page_path = str_replace('%20', ' ', $page_path);
4243 $parts = explode( '/', trim( $page_path, '/' ) );
4244 $parts = esc_sql( $parts );
4245 $parts = array_map( 'sanitize_title_for_query', $parts );
4247 $in_string = "'" . implode( "','", $parts ) . "'";
4249 if ( is_array( $post_type ) ) {
4250 $post_types = $post_type;
4252 $post_types = array( $post_type, 'attachment' );
4255 $post_types = esc_sql( $post_types );
4256 $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
4258 SELECT ID, post_name, post_parent, post_type
4260 WHERE post_name IN ($in_string)
4261 AND post_type IN ($post_type_in_string)
4264 $pages = $wpdb->get_results( $sql, OBJECT_K );
4266 $revparts = array_reverse( $parts );
4269 foreach ( (array) $pages as $page ) {
4270 if ( $page->post_name == $revparts[0] ) {
4275 * Loop through the given path parts from right to left,
4276 * ensuring each matches the post ancestry.
4278 while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
4280 $parent = $pages[ $p->post_parent ];
4281 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
4286 if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
4287 $foundid = $page->ID;
4288 if ( $page->post_type == $post_type )
4294 // We cache misses as well as hits.
4295 wp_cache_set( $cache_key, $foundid, 'posts' );
4298 return get_post( $foundid, $output );
4303 * Retrieve a page given its title.
4307 * @global wpdb $wpdb WordPress database abstraction object.
4309 * @param string $page_title Page title
4310 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
4311 * a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT.
4312 * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4313 * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
4315 function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
4318 if ( is_array( $post_type ) ) {
4319 $post_type = esc_sql( $post_type );
4320 $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
4321 $sql = $wpdb->prepare( "
4324 WHERE post_title = %s
4325 AND post_type IN ($post_type_in_string)
4328 $sql = $wpdb->prepare( "
4331 WHERE post_title = %s
4333 ", $page_title, $post_type );
4336 $page = $wpdb->get_var( $sql );
4339 return get_post( $page, $output );
4344 * Identify descendants of a given page ID in a list of page objects.
4346 * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
4350 * @param int $page_id Page ID.
4351 * @param array $pages List of page objects from which descendants should be identified.
4352 * @return array List of page children.
4354 function get_page_children( $page_id, $pages ) {
4355 // Build a hash of ID -> children.
4356 $children = array();
4357 foreach ( (array) $pages as $page ) {
4358 $children[ intval( $page->post_parent ) ][] = $page;
4361 $page_list = array();
4363 // Start the search by looking at immediate children.
4364 if ( isset( $children[ $page_id ] ) ) {
4365 // Always start at the end of the stack in order to preserve original `$pages` order.
4366 $to_look = array_reverse( $children[ $page_id ] );
4368 while ( $to_look ) {
4369 $p = array_pop( $to_look );
4371 if ( isset( $children[ $p->ID ] ) ) {
4372 foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
4373 // Append to the `$to_look` stack to descend the tree.
4374 $to_look[] = $child;
4384 * Order the pages with children under parents in a flat list.
4386 * It uses auxiliary structure to hold parent-children relationships and
4387 * runs in O(N) complexity
4391 * @param array $pages Posts array, passed by reference.
4392 * @param int $page_id Optional. Parent page ID. Default 0.
4393 * @return array A list arranged by hierarchy. Children immediately follow their parents.
4395 function get_page_hierarchy( &$pages, $page_id = 0 ) {
4396 if ( empty( $pages ) ) {
4400 $children = array();
4401 foreach ( (array) $pages as $p ) {
4402 $parent_id = intval( $p->post_parent );
4403 $children[ $parent_id ][] = $p;
4407 _page_traverse_name( $page_id, $children, $result );
4413 * Traverse and return all the nested children post names of a root page.
4415 * $children contains parent-children relations
4419 * @see _page_traverse_name()
4421 * @param int $page_id Page ID.
4422 * @param array $children Parent-children relations, passed by reference.
4423 * @param array $result Result, passed by reference.
4425 function _page_traverse_name( $page_id, &$children, &$result ){
4426 if ( isset( $children[ $page_id ] ) ){
4427 foreach ( (array)$children[ $page_id ] as $child ) {
4428 $result[ $child->ID ] = $child->post_name;
4429 _page_traverse_name( $child->ID, $children, $result );
4435 * Build the URI path for a page.
4437 * Sub pages will be in the "directory" under the parent page post name.
4440 * @since 4.6.0 Converted the `$page` parameter to optional.
4442 * @param WP_Post|object|int $page Optional. Page ID or WP_Post object. Default is global $post.
4443 * @return string|false Page URI, false on error.
4445 function get_page_uri( $page = 0 ) {
4446 if ( ! $page instanceof WP_Post ) {
4447 $page = get_post( $page );
4453 $uri = $page->post_name;
4455 foreach ( $page->ancestors as $parent ) {
4456 $parent = get_post( $parent );
4457 if ( $parent && $parent->post_name ) {
4458 $uri = $parent->post_name . '/' . $uri;
4463 * Filters the URI for a page.
4467 * @param string $uri Page URI.
4468 * @param WP_Post $page Page object.
4470 return apply_filters( 'get_page_uri', $uri, $page );
4474 * Retrieve a list of pages.
4476 * @global wpdb $wpdb WordPress database abstraction object.
4480 * @param array|string $args {
4481 * Optional. Array or string of arguments to retrieve pages.
4483 * @type int $child_of Page ID to return child and grandchild pages of. Note: The value
4484 * of `$hierarchical` has no bearing on whether `$child_of` returns
4485 * hierarchical results. Default 0, or no restriction.
4486 * @type string $sort_order How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
4487 * @type string $sort_column What columns to sort pages by, comma-separated. Accepts 'post_author',
4488 * 'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
4489 * 'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
4490 * 'post_' can be omitted for any values that start with it.
4491 * Default 'post_title'.
4492 * @type bool $hierarchical Whether to return pages hierarchically. If false in conjunction with
4493 * `$child_of` also being false, both arguments will be disregarded.
4495 * @type array $exclude Array of page IDs to exclude. Default empty array.
4496 * @type array $include Array of page IDs to include. Cannot be used with `$child_of`,
4497 * `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
4498 * Default empty array.
4499 * @type string $meta_key Only include pages with this meta key. Default empty.
4500 * @type string $meta_value Only include pages with this meta value. Requires `$meta_key`.
4502 * @type string $authors A comma-separated list of author IDs. Default empty.
4503 * @type int $parent Page ID to return direct children of. Default -1, or no restriction.
4504 * @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude.
4505 * Default empty array.
4506 * @type int $number The number of pages to return. Default 0, or all pages.
4507 * @type int $offset The number of pages to skip before returning. Requires `$number`.
4509 * @type string $post_type The post type to query. Default 'page'.
4510 * @type string|array $post_status A comma-separated list or array of post statuses to include.
4511 * Default 'publish'.
4513 * @return array|false List of pages matching defaults or `$args`.
4515 function get_pages( $args = array() ) {
4520 'sort_order' => 'ASC',
4521 'sort_column' => 'post_title',
4522 'hierarchical' => 1,
4523 'exclude' => array(),
4524 'include' => array(),
4529 'exclude_tree' => array(),
4532 'post_type' => 'page',
4533 'post_status' => 'publish',
4536 $r = wp_parse_args( $args, $defaults );
4538 $number = (int) $r['number'];
4539 $offset = (int) $r['offset'];
4540 $child_of = (int) $r['child_of'];
4541 $hierarchical = $r['hierarchical'];
4542 $exclude = $r['exclude'];
4543 $meta_key = $r['meta_key'];
4544 $meta_value = $r['meta_value'];
4545 $parent = $r['parent'];
4546 $post_status = $r['post_status'];
4548 // Make sure the post type is hierarchical.
4549 $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
4550 if ( ! in_array( $r['post_type'], $hierarchical_post_types ) ) {
4554 if ( $parent > 0 && ! $child_of ) {
4555 $hierarchical = false;
4558 // Make sure we have a valid post status.
4559 if ( ! is_array( $post_status ) ) {
4560 $post_status = explode( ',', $post_status );
4562 if ( array_diff( $post_status, get_post_stati() ) ) {
4566 // $args can be whatever, only use the args defined in defaults to compute the key.
4567 $key = md5( serialize( wp_array_slice_assoc( $r, array_keys( $defaults ) ) ) );
4568 $last_changed = wp_cache_get_last_changed( 'posts' );
4570 $cache_key = "get_pages:$key:$last_changed";
4571 if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
4572 // Convert to WP_Post instances.
4573 $pages = array_map( 'get_post', $cache );
4574 /** This filter is documented in wp-includes/post.php */
4575 $pages = apply_filters( 'get_pages', $pages, $r );
4580 if ( ! empty( $r['include'] ) ) {
4581 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
4586 $hierarchical = false;
4587 $incpages = wp_parse_id_list( $r['include'] );
4588 if ( ! empty( $incpages ) ) {
4589 $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
4594 if ( ! empty( $exclude ) ) {
4595 $expages = wp_parse_id_list( $exclude );
4596 if ( ! empty( $expages ) ) {
4597 $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
4602 if ( ! empty( $r['authors'] ) ) {
4603 $post_authors = preg_split( '/[\s,]+/', $r['authors'] );
4605 if ( ! empty( $post_authors ) ) {
4606 foreach ( $post_authors as $post_author ) {
4607 //Do we have an author id or an author login?
4608 if ( 0 == intval($post_author) ) {
4609 $post_author = get_user_by('login', $post_author);
4610 if ( empty( $post_author ) ) {
4613 if ( empty( $post_author->ID ) ) {
4616 $post_author = $post_author->ID;
4619 if ( '' == $author_query ) {
4620 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
4622 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
4625 if ( '' != $author_query ) {
4626 $author_query = " AND ($author_query)";
4632 $where = "$exclusions $inclusions ";
4633 if ( '' !== $meta_key || '' !== $meta_value ) {
4634 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
4636 // meta_key and meta_value might be slashed
4637 $meta_key = wp_unslash($meta_key);
4638 $meta_value = wp_unslash($meta_value);
4639 if ( '' !== $meta_key ) {
4640 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
4642 if ( '' !== $meta_value ) {
4643 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
4648 if ( is_array( $parent ) ) {
4649 $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
4650 if ( ! empty( $post_parent__in ) ) {
4651 $where .= " AND post_parent IN ($post_parent__in)";
4653 } elseif ( $parent >= 0 ) {
4654 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
4657 if ( 1 == count( $post_status ) ) {
4658 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $r['post_type'], reset( $post_status ) );
4660 $post_status = implode( "', '", $post_status );
4661 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $r['post_type'] );
4664 $orderby_array = array();
4665 $allowed_keys = array( 'author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
4666 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
4667 'ID', 'rand', 'comment_count' );
4669 foreach ( explode( ',', $r['sort_column'] ) as $orderby ) {
4670 $orderby = trim( $orderby );
4671 if ( ! in_array( $orderby, $allowed_keys ) ) {
4675 switch ( $orderby ) {
4679 $orderby = "$wpdb->posts.ID";
4682 $orderby = 'RAND()';
4684 case 'comment_count':
4685 $orderby = "$wpdb->posts.comment_count";
4688 if ( 0 === strpos( $orderby, 'post_' ) ) {
4689 $orderby = "$wpdb->posts." . $orderby;
4691 $orderby = "$wpdb->posts.post_" . $orderby;
4695 $orderby_array[] = $orderby;
4698 $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
4700 $sort_order = strtoupper( $r['sort_order'] );
4701 if ( '' !== $sort_order && ! in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) {
4702 $sort_order = 'ASC';
4705 $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
4706 $query .= $author_query;
4707 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
4709 if ( ! empty( $number ) ) {
4710 $query .= ' LIMIT ' . $offset . ',' . $number;
4713 $pages = $wpdb->get_results($query);
4715 if ( empty($pages) ) {
4716 /** This filter is documented in wp-includes/post.php */
4717 $pages = apply_filters( 'get_pages', array(), $r );
4721 // Sanitize before caching so it'll only get done once.
4722 $num_pages = count($pages);
4723 for ($i = 0; $i < $num_pages; $i++) {
4724 $pages[$i] = sanitize_post($pages[$i], 'raw');
4728 update_post_cache( $pages );
4730 if ( $child_of || $hierarchical ) {
4731 $pages = get_page_children($child_of, $pages);
4734 if ( ! empty( $r['exclude_tree'] ) ) {
4735 $exclude = wp_parse_id_list( $r['exclude_tree'] );
4736 foreach ( $exclude as $id ) {
4737 $children = get_page_children( $id, $pages );
4738 foreach ( $children as $child ) {
4739 $exclude[] = $child->ID;
4743 $num_pages = count( $pages );
4744 for ( $i = 0; $i < $num_pages; $i++ ) {
4745 if ( in_array( $pages[$i]->ID, $exclude ) ) {
4746 unset( $pages[$i] );
4751 $page_structure = array();
4752 foreach ( $pages as $page ) {
4753 $page_structure[] = $page->ID;
4756 wp_cache_set( $cache_key, $page_structure, 'posts' );
4758 // Convert to WP_Post instances
4759 $pages = array_map( 'get_post', $pages );
4762 * Filters the retrieved list of pages.
4766 * @param array $pages List of pages to retrieve.
4767 * @param array $r Array of get_pages() arguments.
4769 return apply_filters( 'get_pages', $pages, $r );
4773 // Attachment functions
4777 * Check if the attachment URI is local one and is really an attachment.
4781 * @param string $url URL to check
4782 * @return bool True on success, false on failure.
4784 function is_local_attachment($url) {
4785 if (strpos($url, home_url()) === false)
4787 if (strpos($url, home_url('/?attachment_id=')) !== false)
4789 if ( $id = url_to_postid($url) ) {
4790 $post = get_post($id);
4791 if ( 'attachment' == $post->post_type )
4798 * Insert an attachment.
4800 * If you set the 'ID' in the $args parameter, it will mean that you are
4801 * updating and attempt to update the attachment. You can also set the
4802 * attachment name or title by setting the key 'post_name' or 'post_title'.
4804 * You can set the dates for the attachment manually by setting the 'post_date'
4805 * and 'post_date_gmt' keys' values.
4807 * By default, the comments will use the default settings for whether the
4808 * comments are allowed. You can close them manually or keep them open by
4809 * setting the value for the 'comment_status' key.
4812 * @since 4.7.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
4814 * @see wp_insert_post()
4816 * @param string|array $args Arguments for inserting an attachment.
4817 * @param string $file Optional. Filename.
4818 * @param int $parent Optional. Parent post ID.
4819 * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
4820 * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
4822 function wp_insert_attachment( $args, $file = false, $parent = 0, $wp_error = false ) {
4828 $data = wp_parse_args( $args, $defaults );
4830 if ( ! empty( $parent ) ) {
4831 $data['post_parent'] = $parent;
4834 $data['post_type'] = 'attachment';
4836 return wp_insert_post( $data, $wp_error );
4840 * Trash or delete an attachment.
4842 * When an attachment is permanently deleted, the file will also be removed.
4843 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4844 * with the attachment (except the main post).
4846 * The attachment is moved to the trash instead of permanently deleted unless trash
4847 * for media is disabled, item is already in the trash, or $force_delete is true.
4851 * @global wpdb $wpdb WordPress database abstraction object.
4853 * @param int $post_id Attachment ID.
4854 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
4856 * @return mixed False on failure. Post data on success.
4858 function wp_delete_attachment( $post_id, $force_delete = false ) {
4861 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4864 if ( 'attachment' != $post->post_type )
4867 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4868 return wp_trash_post( $post_id );
4870 delete_post_meta($post_id, '_wp_trash_meta_status');
4871 delete_post_meta($post_id, '_wp_trash_meta_time');
4873 $meta = wp_get_attachment_metadata( $post_id );
4874 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4875 $file = get_attached_file( $post_id );
4877 if ( is_multisite() )
4878 delete_transient( 'dirsize_cache' );
4881 * Fires before an attachment is deleted, at the start of wp_delete_attachment().
4885 * @param int $post_id Attachment ID.
4887 do_action( 'delete_attachment', $post_id );
4889 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4890 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4892 // Delete all for any posts.
4893 delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
4895 wp_defer_comment_counting( true );
4897 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4898 foreach ( $comment_ids as $comment_id ) {
4899 wp_delete_comment( $comment_id, true );
4902 wp_defer_comment_counting( false );
4904 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4905 foreach ( $post_meta_ids as $mid )
4906 delete_metadata_by_mid( 'post', $mid );
4908 /** This action is documented in wp-includes/post.php */
4909 do_action( 'delete_post', $post_id );
4910 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4914 /** This action is documented in wp-includes/post.php */
4915 do_action( 'deleted_post', $post_id );
4917 $uploadpath = wp_get_upload_dir();
4919 if ( ! empty($meta['thumb']) ) {
4920 // Don't delete the thumb if another attachment uses it.
4921 if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', $post_id)) ) {
4922 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4923 /** This filter is documented in wp-includes/functions.php */
4924 $thumbfile = apply_filters( 'wp_delete_file', $thumbfile );
4925 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4929 // Remove intermediate and backup images if there are any.
4930 if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
4931 foreach ( $meta['sizes'] as $size => $sizeinfo ) {
4932 $intermediate_file = str_replace( basename( $file ), $sizeinfo['file'], $file );
4933 /** This filter is documented in wp-includes/functions.php */
4934 $intermediate_file = apply_filters( 'wp_delete_file', $intermediate_file );
4935 @ unlink( path_join( $uploadpath['basedir'], $intermediate_file ) );
4939 if ( is_array($backup_sizes) ) {
4940 foreach ( $backup_sizes as $size ) {
4941 $del_file = path_join( dirname($meta['file']), $size['file'] );
4942 /** This filter is documented in wp-includes/functions.php */
4943 $del_file = apply_filters( 'wp_delete_file', $del_file );
4944 @ unlink( path_join($uploadpath['basedir'], $del_file) );
4948 wp_delete_file( $file );
4950 clean_post_cache( $post );
4956 * Retrieve attachment meta field for attachment ID.
4960 * @param int $post_id Attachment ID. Default 0.
4961 * @param bool $unfiltered Optional. If true, filters are not run. Default false.
4962 * @return mixed Attachment meta field. False on failure.
4964 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4965 $post_id = (int) $post_id;
4966 if ( !$post = get_post( $post_id ) )
4969 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4975 * Filters the attachment meta data.
4979 * @param array|bool $data Array of meta data for the given attachment, or false
4980 * if the object does not exist.
4981 * @param int $post_id Attachment ID.
4983 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4987 * Update metadata for an attachment.
4991 * @param int $post_id Attachment ID.
4992 * @param array $data Attachment data.
4993 * @return int|bool False if $post is invalid.
4995 function wp_update_attachment_metadata( $post_id, $data ) {
4996 $post_id = (int) $post_id;
4997 if ( !$post = get_post( $post_id ) )
5001 * Filters the updated attachment meta data.
5005 * @param array $data Array of updated attachment meta data.
5006 * @param int $post_id Attachment ID.
5008 if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
5009 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
5011 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
5015 * Retrieve the URL for an attachment.
5019 * @global string $pagenow
5021 * @param int $post_id Optional. Attachment ID. Default 0.
5022 * @return string|false Attachment URL, otherwise false.
5024 function wp_get_attachment_url( $post_id = 0 ) {
5025 $post_id = (int) $post_id;
5026 if ( !$post = get_post( $post_id ) )
5029 if ( 'attachment' != $post->post_type )
5033 // Get attached file.
5034 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true ) ) {
5035 // Get upload directory.
5036 if ( ( $uploads = wp_get_upload_dir() ) && false === $uploads['error'] ) {
5037 // Check that the upload base exists in the file location.
5038 if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
5039 // Replace file location with url location.
5040 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
5041 } elseif ( false !== strpos($file, 'wp-content/uploads') ) {
5042 // Get the directory name relative to the basedir (back compat for pre-2.7 uploads)
5043 $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . basename( $file );
5045 // It's a newly-uploaded file, therefore $file is relative to the basedir.
5046 $url = $uploads['baseurl'] . "/$file";
5052 * If any of the above options failed, Fallback on the GUID as used pre-2.7,
5053 * not recommended to rely upon this.
5055 if ( empty($url) ) {
5056 $url = get_the_guid( $post->ID );
5059 // On SSL front end, URLs should be HTTPS.
5060 if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) {
5061 $url = set_url_scheme( $url );
5065 * Filters the attachment URL.
5069 * @param string $url URL for the given attachment.
5070 * @param int $post_id Attachment ID.
5072 $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
5074 if ( empty( $url ) )
5081 * Retrieves the caption for an attachment.
5085 * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
5086 * @return string|false False on failure. Attachment caption on success.
5088 function wp_get_attachment_caption( $post_id = 0 ) {
5089 $post_id = (int) $post_id;
5090 if ( ! $post = get_post( $post_id ) ) {
5094 if ( 'attachment' !== $post->post_type ) {
5098 $caption = $post->post_excerpt;
5101 * Filters the attachment caption.
5105 * @param string $caption Caption for the given attachment.
5106 * @param int $post_id Attachment ID.
5108 return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
5112 * Retrieve thumbnail for an attachment.
5116 * @param int $post_id Optional. Attachment ID. Default 0.
5117 * @return string|false False on failure. Thumbnail file path on success.
5119 function wp_get_attachment_thumb_file( $post_id = 0 ) {
5120 $post_id = (int) $post_id;
5121 if ( !$post = get_post( $post_id ) )
5123 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
5126 $file = get_attached_file( $post->ID );
5128 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) {
5130 * Filters the attachment thumbnail file path.
5134 * @param string $thumbfile File path to the attachment thumbnail.
5135 * @param int $post_id Attachment ID.
5137 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
5143 * Retrieve URL for an attachment thumbnail.
5147 * @param int $post_id Optional. Attachment ID. Default 0.
5148 * @return string|false False on failure. Thumbnail URL on success.
5150 function wp_get_attachment_thumb_url( $post_id = 0 ) {
5151 $post_id = (int) $post_id;
5152 if ( !$post = get_post( $post_id ) )
5154 if ( !$url = wp_get_attachment_url( $post->ID ) )
5157 $sized = image_downsize( $post_id, 'thumbnail' );
5161 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
5164 $url = str_replace(basename($url), basename($thumb), $url);
5167 * Filters the attachment thumbnail URL.
5171 * @param string $url URL for the attachment thumbnail.
5172 * @param int $post_id Attachment ID.
5174 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
5178 * Verifies an attachment is of a given type.
5182 * @param string $type Attachment type. Accepts 'image', 'audio', or 'video'.
5183 * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
5184 * @return bool True if one of the accepted types, false otherwise.
5186 function wp_attachment_is( $type, $post = null ) {
5187 if ( ! $post = get_post( $post ) ) {
5191 if ( ! $file = get_attached_file( $post->ID ) ) {
5195 if ( 0 === strpos( $post->post_mime_type, $type . '/' ) ) {
5199 $check = wp_check_filetype( $file );
5200 if ( empty( $check['ext'] ) ) {
5204 $ext = $check['ext'];
5206 if ( 'import' !== $post->post_mime_type ) {
5207 return $type === $ext;
5212 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
5213 return in_array( $ext, $image_exts );
5216 return in_array( $ext, wp_get_audio_extensions() );
5219 return in_array( $ext, wp_get_video_extensions() );
5222 return $type === $ext;
5227 * Checks if the attachment is an image.
5230 * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
5231 * allowed WP_Post object to be passed.
5233 * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
5234 * @return bool Whether the attachment is an image.
5236 function wp_attachment_is_image( $post = null ) {
5237 return wp_attachment_is( 'image', $post );
5241 * Retrieve the icon for a MIME type.
5245 * @param string|int $mime MIME type or attachment ID.
5246 * @return string|false Icon, false otherwise.
5248 function wp_mime_type_icon( $mime = 0 ) {
5249 if ( !is_numeric($mime) )
5250 $icon = wp_cache_get("mime_type_icon_$mime");
5253 if ( empty($icon) ) {
5254 $post_mimes = array();
5255 if ( is_numeric($mime) ) {
5256 $mime = (int) $mime;
5257 if ( $post = get_post( $mime ) ) {
5258 $post_id = (int) $post->ID;
5259 $file = get_attached_file( $post_id );
5260 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $file);
5261 if ( !empty($ext) ) {
5262 $post_mimes[] = $ext;
5263 if ( $ext_type = wp_ext2type( $ext ) )
5264 $post_mimes[] = $ext_type;
5266 $mime = $post->post_mime_type;
5271 $post_mimes[] = $mime;
5274 $icon_files = wp_cache_get('icon_files');
5276 if ( !is_array($icon_files) ) {
5278 * Filters the icon directory path.
5282 * @param string $path Icon directory absolute path.
5284 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
5287 * Filters the icon directory URI.
5291 * @param string $uri Icon directory URI.
5293 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
5296 * Filters the list of icon directory URIs.
5300 * @param array $uris List of icon directory URIs.
5302 $dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
5303 $icon_files = array();
5305 $keys = array_keys( $dirs );
5306 $dir = array_shift( $keys );
5307 $uri = array_shift($dirs);
5308 if ( $dh = opendir($dir) ) {
5309 while ( false !== $file = readdir($dh) ) {
5310 $file = basename($file);
5311 if ( substr($file, 0, 1) == '.' )
5313 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
5314 if ( is_dir("$dir/$file") )
5315 $dirs["$dir/$file"] = "$uri/$file";
5318 $icon_files["$dir/$file"] = "$uri/$file";
5323 wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
5327 // Icon basename - extension = MIME wildcard.
5328 foreach ( $icon_files as $file => $uri )
5329 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
5331 if ( ! empty($mime) ) {
5332 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
5333 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
5334 $post_mimes[] = str_replace('/', '_', $mime);
5337 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
5338 $matches['default'] = array('default');
5340 foreach ( $matches as $match => $wilds ) {
5341 foreach ( $wilds as $wild ) {
5342 if ( ! isset( $types[ $wild ] ) ) {
5346 $icon = $types[ $wild ];
5347 if ( ! is_numeric( $mime ) ) {
5348 wp_cache_add( "mime_type_icon_$mime", $icon );
5356 * Filters the mime type icon.
5360 * @param string $icon Path to the mime type icon.
5361 * @param string $mime Mime type.
5362 * @param int $post_id Attachment ID. Will equal 0 if the function passed
5365 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
5369 * Check for changed slugs for published post objects and save the old slug.
5371 * The function is used when a post object of any type is updated,
5372 * by comparing the current and previous post objects.
5374 * If the slug was changed and not already part of the old slugs then it will be
5375 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
5378 * The most logically usage of this function is redirecting changed post objects, so
5379 * that those that linked to an changed post will be redirected to the new post.
5383 * @param int $post_id Post ID.
5384 * @param WP_Post $post The Post Object
5385 * @param WP_Post $post_before The Previous Post Object
5387 function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
5388 // Don't bother if it hasn't changed.
5389 if ( $post->post_name == $post_before->post_name ) {
5393 // We're only concerned with published, non-hierarchical objects.
5394 if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
5398 $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
5400 // If we haven't added this old slug before, add it now.
5401 if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs ) ) {
5402 add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
5405 // If the new slug was used previously, delete it from the list.
5406 if ( in_array( $post->post_name, $old_slugs ) ) {
5407 delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
5412 * Retrieve the private post SQL based on capability.
5414 * This function provides a standardized way to appropriately select on the
5415 * post_status of a post type. The function will return a piece of SQL code
5416 * that can be added to a WHERE clause; this SQL is constructed to allow all
5417 * published posts, and all private posts to which the user has access.
5420 * @since 4.3.0 Added the ability to pass an array to `$post_type`.
5422 * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
5423 * @return string SQL code that can be added to a where clause.
5425 function get_private_posts_cap_sql( $post_type ) {
5426 return get_posts_by_author_sql( $post_type, false );
5430 * Retrieve the post SQL based on capability, author, and type.
5433 * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
5435 * @see get_private_posts_cap_sql()
5436 * @global wpdb $wpdb WordPress database abstraction object.
5438 * @param array|string $post_type Single post type or an array of post types.
5439 * @param bool $full Optional. Returns a full WHERE statement instead of just
5440 * an 'andalso' term. Default true.
5441 * @param int $post_author Optional. Query posts having a single author ID. Default null.
5442 * @param bool $public_only Optional. Only return public posts. Skips cap checks for
5443 * $current_user. Default false.
5444 * @return string SQL WHERE code that can be added to a query.
5446 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
5449 if ( is_array( $post_type ) ) {
5450 $post_types = $post_type;
5452 $post_types = array( $post_type );
5455 $post_type_clauses = array();
5456 foreach ( $post_types as $post_type ) {
5457 $post_type_obj = get_post_type_object( $post_type );
5458 if ( ! $post_type_obj ) {
5463 * Filters the capability to read private posts for a custom post type
5464 * when generating SQL for getting posts by author.
5467 * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
5469 * @param string $cap Capability.
5471 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
5472 $cap = current_user_can( $post_type_obj->cap->read_private_posts );
5475 // Only need to check the cap if $public_only is false.
5476 $post_status_sql = "post_status = 'publish'";
5477 if ( false === $public_only ) {
5479 // Does the user have the capability to view private posts? Guess so.
5480 $post_status_sql .= " OR post_status = 'private'";
5481 } elseif ( is_user_logged_in() ) {
5482 // Users can view their own private posts.
5483 $id = get_current_user_id();
5484 if ( null === $post_author || ! $full ) {
5485 $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
5486 } elseif ( $id == (int) $post_author ) {
5487 $post_status_sql .= " OR post_status = 'private'";
5492 $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
5495 if ( empty( $post_type_clauses ) ) {
5496 return $full ? 'WHERE 1 = 0' : '1 = 0';
5499 $sql = '( '. implode( ' OR ', $post_type_clauses ) . ' )';
5501 if ( null !== $post_author ) {
5502 $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
5506 $sql = 'WHERE ' . $sql;
5513 * Retrieve the date that the last post was published.
5515 * The server timezone is the default and is the difference between GMT and
5516 * server time. The 'blog' value is the date when the last post was posted. The
5517 * 'gmt' is when the last post was posted in GMT formatted date.
5520 * @since 4.4.0 The `$post_type` argument was added.
5522 * @param string $timezone Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
5523 * 'server' uses the server's internal timezone.
5524 * 'blog' uses the `post_modified` field, which proxies to the timezone set for the site.
5525 * 'gmt' uses the `post_modified_gmt` field.
5527 * @param string $post_type Optional. The post type to check. Default 'any'.
5528 * @return string The date of the last post.
5530 function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
5532 * Filters the date the last post was published.
5536 * @param string $date Date the last post was published.
5537 * @param string $timezone Location to use for getting the post published date.
5538 * See get_lastpostdate() for accepted `$timezone` values.
5540 return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date', $post_type ), $timezone );
5544 * Get the timestamp of the last time any post was modified.
5546 * The server timezone is the default and is the difference between GMT and
5547 * server time. The 'blog' value is just when the last post was modified. The
5548 * 'gmt' is when the last post was modified in GMT time.
5551 * @since 4.4.0 The `$post_type` argument was added.
5553 * @param string $timezone Optional. The timezone for the timestamp. See get_lastpostdate()
5554 * for information on accepted values.
5556 * @param string $post_type Optional. The post type to check. Default 'any'.
5557 * @return string The timestamp.
5559 function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
5561 * Pre-filter the return value of get_lastpostmodified() before the query is run.
5565 * @param string $lastpostmodified Date the last post was modified.
5566 * Returning anything other than false will short-circuit the function.
5567 * @param string $timezone Location to use for getting the post modified date.
5568 * See get_lastpostdate() for accepted `$timezone` values.
5569 * @param string $post_type The post type to check.
5571 $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
5572 if ( false !== $lastpostmodified ) {
5573 return $lastpostmodified;
5576 $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
5578 $lastpostdate = get_lastpostdate($timezone);
5579 if ( $lastpostdate > $lastpostmodified ) {
5580 $lastpostmodified = $lastpostdate;
5584 * Filters the date the last post was modified.
5588 * @param string $lastpostmodified Date the last post was modified.
5589 * @param string $timezone Location to use for getting the post modified date.
5590 * See get_lastpostdate() for accepted `$timezone` values.
5592 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
5596 * Get the timestamp of the last time any post was modified or published.
5599 * @since 4.4.0 The `$post_type` argument was added.
5602 * @global wpdb $wpdb WordPress database abstraction object.
5604 * @param string $timezone The timezone for the timestamp. See get_lastpostdate().
5605 * for information on accepted values.
5606 * @param string $field Post field to check. Accepts 'date' or 'modified'.
5607 * @param string $post_type Optional. The post type to check. Default 'any'.
5608 * @return string|false The timestamp.
5610 function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
5613 if ( ! in_array( $field, array( 'date', 'modified' ) ) ) {
5617 $timezone = strtolower( $timezone );
5619 $key = "lastpost{$field}:$timezone";
5620 if ( 'any' !== $post_type ) {
5621 $key .= ':' . sanitize_key( $post_type );
5624 $date = wp_cache_get( $key, 'timeinfo' );
5625 if ( false !== $date ) {
5629 if ( 'any' === $post_type ) {
5630 $post_types = get_post_types( array( 'public' => true ) );
5631 array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
5632 $post_types = "'" . implode( "', '", $post_types ) . "'";
5634 $post_types = "'" . sanitize_key( $post_type ) . "'";
5637 switch ( $timezone ) {
5639 $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
5642 $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
5645 $add_seconds_server = date( 'Z' );
5646 $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
5651 wp_cache_set( $key, $date, 'timeinfo' );
5660 * Updates posts in cache.
5664 * @param array $posts Array of post objects, passed by reference.
5666 function update_post_cache( &$posts ) {
5670 foreach ( $posts as $post )
5671 wp_cache_add( $post->ID, $post, 'posts' );
5675 * Will clean the post in the cache.
5677 * Cleaning means delete from the cache of the post. Will call to clean the term
5678 * object cache associated with the post ID.
5680 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
5681 * wp_suspend_cache_invalidation().
5685 * @global bool $_wp_suspend_cache_invalidation
5687 * @param int|WP_Post $post Post ID or post object to remove from the cache.
5689 function clean_post_cache( $post ) {
5690 global $_wp_suspend_cache_invalidation;
5692 if ( ! empty( $_wp_suspend_cache_invalidation ) )
5695 $post = get_post( $post );
5696 if ( empty( $post ) )
5699 wp_cache_delete( $post->ID, 'posts' );
5700 wp_cache_delete( $post->ID, 'post_meta' );
5702 clean_object_term_cache( $post->ID, $post->post_type );
5704 wp_cache_delete( 'wp_get_archives', 'general' );
5707 * Fires immediately after the given post's cache is cleaned.
5711 * @param int $post_id Post ID.
5712 * @param WP_Post $post Post object.
5714 do_action( 'clean_post_cache', $post->ID, $post );
5716 if ( 'page' == $post->post_type ) {
5717 wp_cache_delete( 'all_page_ids', 'posts' );
5720 * Fires immediately after the given page's cache is cleaned.
5724 * @param int $post_id Post ID.
5726 do_action( 'clean_page_cache', $post->ID );
5729 wp_cache_set( 'last_changed', microtime(), 'posts' );
5733 * Call major cache updating functions for list of Post objects.
5737 * @param array $posts Array of Post objects
5738 * @param string $post_type Optional. Post type. Default 'post'.
5739 * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
5740 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
5742 function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
5743 // No point in doing all this work if we didn't match any posts.
5747 update_post_cache($posts);
5749 $post_ids = array();
5750 foreach ( $posts as $post )
5751 $post_ids[] = $post->ID;
5756 if ( $update_term_cache ) {
5757 if ( is_array($post_type) ) {
5758 $ptypes = $post_type;
5759 } elseif ( 'any' == $post_type ) {
5761 // Just use the post_types in the supplied posts.
5762 foreach ( $posts as $post ) {
5763 $ptypes[] = $post->post_type;
5765 $ptypes = array_unique($ptypes);
5767 $ptypes = array($post_type);
5770 if ( ! empty($ptypes) )
5771 update_object_term_cache($post_ids, $ptypes);
5774 if ( $update_meta_cache )
5775 update_postmeta_cache($post_ids);
5779 * Updates metadata cache for list of post IDs.
5781 * Performs SQL query to retrieve the metadata for the post IDs and updates the
5782 * metadata cache for the posts. Therefore, the functions, which call this
5783 * function, do not need to perform SQL queries on their own.
5787 * @param array $post_ids List of post IDs.
5788 * @return array|false Returns false if there is nothing to update or an array
5791 function update_postmeta_cache( $post_ids ) {
5792 return update_meta_cache('post', $post_ids);
5796 * Will clean the attachment in the cache.
5798 * Cleaning means delete from the cache. Optionally will clean the term
5799 * object cache associated with the attachment ID.
5801 * This function will not run if $_wp_suspend_cache_invalidation is not empty.
5805 * @global bool $_wp_suspend_cache_invalidation
5807 * @param int $id The attachment ID in the cache to clean.
5808 * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
5810 function clean_attachment_cache( $id, $clean_terms = false ) {
5811 global $_wp_suspend_cache_invalidation;
5813 if ( !empty($_wp_suspend_cache_invalidation) )
5818 wp_cache_delete($id, 'posts');
5819 wp_cache_delete($id, 'post_meta');
5822 clean_object_term_cache($id, 'attachment');
5825 * Fires after the given attachment's cache is cleaned.
5829 * @param int $id Attachment ID.
5831 do_action( 'clean_attachment_cache', $id );
5839 * Hook for managing future post transitions to published.
5844 * @see wp_clear_scheduled_hook()
5845 * @global wpdb $wpdb WordPress database abstraction object.
5847 * @param string $new_status New post status.
5848 * @param string $old_status Previous post status.
5849 * @param WP_Post $post Post object.
5851 function _transition_post_status( $new_status, $old_status, $post ) {
5854 if ( $old_status != 'publish' && $new_status == 'publish' ) {
5855 // Reset GUID if transitioning to publish and it is empty.
5856 if ( '' == get_the_guid($post->ID) )
5857 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
5860 * Fires when a post's status is transitioned from private to published.
5863 * @deprecated 2.3.0 Use 'private_to_publish' instead.
5865 * @param int $post_id Post ID.
5867 do_action('private_to_published', $post->ID);
5870 // If published posts changed clear the lastpostmodified cache.
5871 if ( 'publish' == $new_status || 'publish' == $old_status) {
5872 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
5873 wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
5874 wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
5875 wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
5879 if ( $new_status !== $old_status ) {
5880 wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
5881 wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
5884 // Always clears the hook in case the post status bounced from future to draft.
5885 wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
5889 * Hook used to schedule publication for a post marked for the future.
5891 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
5896 * @param int $deprecated Not used. Can be set to null. Never implemented. Not marked
5897 * as deprecated with _deprecated_argument() as it conflicts with
5898 * wp_transition_post_status() and the default filter for _future_post_hook().
5899 * @param WP_Post $post Post object.
5901 function _future_post_hook( $deprecated, $post ) {
5902 wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
5903 wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
5907 * Hook to schedule pings and enclosures when a post is published.
5909 * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
5914 * @param int $post_id The ID in the database table of the post being published.
5916 function _publish_post_hook( $post_id ) {
5917 if ( defined( 'XMLRPC_REQUEST' ) ) {
5919 * Fires when _publish_post_hook() is called during an XML-RPC request.
5923 * @param int $post_id Post ID.
5925 do_action( 'xmlrpc_publish_post', $post_id );
5928 if ( defined('WP_IMPORTING') )
5931 if ( get_option('default_pingback_flag') )
5932 add_post_meta( $post_id, '_pingme', '1' );
5933 add_post_meta( $post_id, '_encloseme', '1' );
5935 wp_schedule_single_event(time(), 'do_pings');
5939 * Return the post's parent's post_ID
5943 * @param int $post_ID
5945 * @return int|false Post parent ID, otherwise false.
5947 function wp_get_post_parent_id( $post_ID ) {
5948 $post = get_post( $post_ID );
5949 if ( !$post || is_wp_error( $post ) )
5951 return (int) $post->post_parent;
5955 * Check the given subset of the post hierarchy for hierarchy loops.
5957 * Prevents loops from forming and breaks those that it finds. Attached
5958 * to the {@see 'wp_insert_post_parent'} filter.
5962 * @see wp_find_hierarchy_loop()
5964 * @param int $post_parent ID of the parent for the post we're checking.
5965 * @param int $post_ID ID of the post we're checking.
5966 * @return int The new post_parent for the post, 0 otherwise.
5968 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
5969 // Nothing fancy here - bail.
5970 if ( !$post_parent )
5973 // New post can't cause a loop.
5974 if ( empty( $post_ID ) )
5975 return $post_parent;
5977 // Can't be its own parent.
5978 if ( $post_parent == $post_ID )
5981 // Now look for larger loops.
5982 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
5983 return $post_parent; // No loop
5985 // Setting $post_parent to the given value causes a loop.
5986 if ( isset( $loop[$post_ID] ) )
5989 // There's a loop, but it doesn't contain $post_ID. Break the loop.
5990 foreach ( array_keys( $loop ) as $loop_member )
5991 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
5993 return $post_parent;
5997 * Set a post thumbnail.
6001 * @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
6002 * @param int $thumbnail_id Thumbnail to attach.
6003 * @return int|bool True on success, false on failure.
6005 function set_post_thumbnail( $post, $thumbnail_id ) {
6006 $post = get_post( $post );
6007 $thumbnail_id = absint( $thumbnail_id );
6008 if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
6009 if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
6010 return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
6012 return delete_post_meta( $post->ID, '_thumbnail_id' );
6018 * Remove a post thumbnail.
6022 * @param int|WP_Post $post Post ID or post object where thumbnail should be removed from.
6023 * @return bool True on success, false on failure.
6025 function delete_post_thumbnail( $post ) {
6026 $post = get_post( $post );
6028 return delete_post_meta( $post->ID, '_thumbnail_id' );
6033 * Delete auto-drafts for new posts that are > 7 days old.
6037 * @global wpdb $wpdb WordPress database abstraction object.
6039 function wp_delete_auto_drafts() {
6042 // Cleanup old auto-drafts more than 7 days old.
6043 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
6044 foreach ( (array) $old_posts as $delete ) {
6046 wp_delete_post( $delete, true );
6051 * Queues posts for lazy-loading of term meta.
6055 * @param array $posts Array of WP_Post objects.
6057 function wp_queue_posts_for_term_meta_lazyload( $posts ) {
6058 $post_type_taxonomies = $term_ids = array();
6059 foreach ( $posts as $post ) {
6060 if ( ! ( $post instanceof WP_Post ) ) {
6064 if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
6065 $post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
6068 foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
6069 // Term cache should already be primed by `update_post_term_cache()`.
6070 $terms = get_object_term_cache( $post->ID, $taxonomy );
6071 if ( false !== $terms ) {
6072 foreach ( $terms as $term ) {
6073 if ( ! isset( $term_ids[ $term->term_id ] ) ) {
6074 $term_ids[] = $term->term_id;
6082 $lazyloader = wp_metadata_lazyloader();
6083 $lazyloader->queue_objects( 'term', $term_ids );
6088 * Update the custom taxonomies' term counts when a post's status is changed.
6090 * For example, default posts term counts (for custom taxonomies) don't include
6091 * private / draft posts.
6096 * @param string $new_status New post status.
6097 * @param string $old_status Old post status.
6098 * @param WP_Post $post Post object.
6100 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
6101 // Update counts for the post's terms.
6102 foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
6103 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
6104 wp_update_term_count( $tt_ids, $taxonomy );
6109 * Adds any posts from the given ids to the cache that do not already exist in cache
6114 * @see update_post_caches()
6116 * @global wpdb $wpdb WordPress database abstraction object.
6118 * @param array $ids ID list.
6119 * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
6120 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
6122 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
6125 $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
6126 if ( !empty( $non_cached_ids ) ) {
6127 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
6129 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
6134 * Adds a suffix if any trashed posts have a given slug.
6136 * Store its desired (i.e. current) slug so it can try to reclaim it
6137 * if the post is untrashed.
6144 * @param string $post_name Slug.
6145 * @param string $post_ID Optional. Post ID that should be ignored. Default 0.
6147 function wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID = 0 ) {
6148 $trashed_posts_with_desired_slug = get_posts( array(
6149 'name' => $post_name,
6150 'post_status' => 'trash',
6151 'post_type' => 'any',
6153 'post__not_in' => array( $post_ID )
6156 if ( ! empty( $trashed_posts_with_desired_slug ) ) {
6157 foreach ( $trashed_posts_with_desired_slug as $_post ) {
6158 wp_add_trashed_suffix_to_post_name_for_post( $_post );
6164 * Adds a trashed suffix for a given post.
6166 * Store its desired (i.e. current) slug so it can try to reclaim it
6167 * if the post is untrashed.
6174 * @param WP_Post $post The post.
6175 * @return string New slug for the post.
6177 function wp_add_trashed_suffix_to_post_name_for_post( $post ) {
6180 $post = get_post( $post );
6182 if ( '__trashed' === substr( $post->post_name, -9 ) ) {
6183 return $post->post_name;
6185 add_post_meta( $post->ID, '_wp_desired_post_slug', $post->post_name );
6186 $post_name = _truncate_post_slug( $post->post_name, 191 ) . '__trashed';
6187 $wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), array( 'ID' => $post->ID ) );
6188 clean_post_cache( $post->ID );
6193 * Filter the SQL clauses of an attachment query to include filenames.
6198 * @global wpdb $wpdb WordPress database abstraction object.
6200 * @param array $clauses An array including WHERE, GROUP BY, JOIN, ORDER BY,
6201 * DISTINCT, fields (SELECT), and LIMITS clauses.
6202 * @return array The modified clauses.
6204 function _filter_query_attachment_filenames( $clauses ) {
6206 remove_filter( 'posts_clauses', __FUNCTION__ );
6208 // Add a LEFT JOIN of the postmeta table so we don't trample existing JOINs.
6209 $clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} AS sq1 ON ( {$wpdb->posts}.ID = sq1.post_id AND sq1.meta_key = '_wp_attached_file' )";
6211 $clauses['groupby'] = "{$wpdb->posts}.ID";
6213 $clauses['where'] = preg_replace(
6214 "/\({$wpdb->posts}.post_content (NOT LIKE|LIKE) (\'[^']+\')\)/",
6215 "$0 OR ( sq1.meta_value $1 $2 )",
6216 $clauses['where'] );