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 on 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' ),
38 register_post_type( 'page', array(
40 'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
43 'publicly_queryable' => false,
44 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
45 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
46 'capability_type' => 'page',
47 'map_meta_cap' => true,
48 'menu_position' => 20,
49 'hierarchical' => true,
52 'delete_with_user' => true,
53 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
56 register_post_type( 'attachment', array(
58 'name' => _x('Media', 'post type general name'),
59 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
60 'add_new' => _x( 'Add New', 'add new media' ),
61 'edit_item' => __( 'Edit Media' ),
62 'view_item' => __( 'View Attachment Page' ),
66 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
67 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
68 'capability_type' => 'post',
69 'capabilities' => array(
70 'create_posts' => 'upload_files',
72 'map_meta_cap' => true,
73 'hierarchical' => false,
76 'show_in_nav_menus' => false,
77 'delete_with_user' => true,
78 'supports' => array( 'title', 'author', 'comments' ),
80 add_post_type_support( 'attachment:audio', 'thumbnail' );
81 add_post_type_support( 'attachment:video', 'thumbnail' );
83 register_post_type( 'revision', array(
85 'name' => __( 'Revisions' ),
86 'singular_name' => __( 'Revision' ),
89 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
90 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
91 'capability_type' => 'post',
92 'map_meta_cap' => true,
93 'hierarchical' => false,
96 'can_export' => false,
97 'delete_with_user' => true,
98 'supports' => array( 'author' ),
101 register_post_type( 'nav_menu_item', array(
103 'name' => __( 'Navigation Menu Items' ),
104 'singular_name' => __( 'Navigation Menu Item' ),
107 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
108 'hierarchical' => false,
110 'delete_with_user' => false,
111 'query_var' => false,
114 register_post_status( 'publish', array(
115 'label' => _x( 'Published', 'post status' ),
117 '_builtin' => true, /* internal use only. */
118 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
121 register_post_status( 'future', array(
122 'label' => _x( 'Scheduled', 'post status' ),
124 '_builtin' => true, /* internal use only. */
125 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
128 register_post_status( 'draft', array(
129 'label' => _x( 'Draft', 'post status' ),
131 '_builtin' => true, /* internal use only. */
132 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
135 register_post_status( 'pending', array(
136 'label' => _x( 'Pending', 'post status' ),
138 '_builtin' => true, /* internal use only. */
139 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
142 register_post_status( 'private', array(
143 'label' => _x( 'Private', 'post status' ),
145 '_builtin' => true, /* internal use only. */
146 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
149 register_post_status( 'trash', array(
150 'label' => _x( 'Trash', 'post status' ),
152 '_builtin' => true, /* internal use only. */
153 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
154 'show_in_admin_status_list' => true,
157 register_post_status( 'auto-draft', array(
158 'label' => 'auto-draft',
160 '_builtin' => true, /* internal use only. */
163 register_post_status( 'inherit', array(
164 'label' => 'inherit',
166 '_builtin' => true, /* internal use only. */
167 'exclude_from_search' => false,
172 * Retrieve attached file path based on attachment ID.
174 * By default the path will go through the 'get_attached_file' filter, but
175 * passing a true to the $unfiltered argument of get_attached_file() will
176 * return the file path unfiltered.
178 * The function works by getting the single post meta name, named
179 * '_wp_attached_file' and returning it. This is a convenience function to
180 * prevent looking up the meta name and provide a mechanism for sending the
181 * attached filename through a filter.
185 * @param int $attachment_id Attachment ID.
186 * @param bool $unfiltered Optional. Whether to apply filters. Default false.
187 * @return string|false The file path to where the attached file should be, false otherwise.
189 function get_attached_file( $attachment_id, $unfiltered = false ) {
190 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
192 // If the file is relative, prepend upload dir.
193 if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) && ( ( $uploads = wp_get_upload_dir() ) && false === $uploads['error'] ) ) {
194 $file = $uploads['basedir'] . "/$file";
202 * Filters the attached file based on the given ID.
206 * @param string $file Path to attached file.
207 * @param int $attachment_id Attachment ID.
209 return apply_filters( 'get_attached_file', $file, $attachment_id );
213 * Update attachment file path based on attachment ID.
215 * Used to update the file path of the attachment, which uses post meta name
216 * '_wp_attached_file' to store the path of the attachment.
220 * @param int $attachment_id Attachment ID.
221 * @param string $file File path for the attachment.
222 * @return bool True on success, false on failure.
224 function update_attached_file( $attachment_id, $file ) {
225 if ( !get_post( $attachment_id ) )
229 * Filters the path to the attached file to update.
233 * @param string $file Path to the attached file to update.
234 * @param int $attachment_id Attachment ID.
236 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
238 if ( $file = _wp_relative_upload_path( $file ) )
239 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
241 return delete_post_meta( $attachment_id, '_wp_attached_file' );
245 * Return relative path to an uploaded file.
247 * The path is relative to the current upload dir.
251 * @param string $path Full path to the file.
252 * @return string Relative path on success, unchanged path on failure.
254 function _wp_relative_upload_path( $path ) {
257 $uploads = wp_get_upload_dir();
258 if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
259 $new_path = str_replace( $uploads['basedir'], '', $new_path );
260 $new_path = ltrim( $new_path, '/' );
264 * Filters the relative path to an uploaded file.
268 * @param string $new_path Relative path to the file.
269 * @param string $path Full path to the file.
271 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
275 * Retrieve all children of the post parent ID.
277 * Normally, without any enhancements, the children would apply to pages. In the
278 * context of the inner workings of WordPress, pages, posts, and attachments
279 * share the same table, so therefore the functionality could apply to any one
280 * of them. It is then noted that while this function does not work on posts, it
281 * does not mean that it won't work on posts. It is recommended that you know
282 * what context you wish to retrieve the children of.
284 * Attachments may also be made the child of a post, so if that is an accurate
285 * statement (which needs to be verified), it would then be possible to get
286 * all of the attachments for a post. Attachments have since changed since
287 * version 2.5, so this is most likely inaccurate, but serves generally as an
288 * example of what is possible.
290 * The arguments listed as defaults are for this function and also of the
291 * get_posts() function. The arguments are combined with the get_children defaults
292 * and are then passed to the get_posts() function, which accepts additional arguments.
293 * You can replace the defaults in this function, listed below and the additional
294 * arguments listed in the get_posts() function.
296 * The 'post_parent' is the most important argument and important attention
297 * needs to be paid to the $args parameter. If you pass either an object or an
298 * integer (number), then just the 'post_parent' is grabbed and everything else
299 * is lost. If you don't specify any arguments, then it is assumed that you are
300 * in The Loop and the post parent will be grabbed for from the current post.
302 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
303 * is the amount of posts to retrieve that has a default of '-1', which is
304 * used to get all of the posts. Giving a number higher than 0 will only
305 * retrieve that amount of posts.
307 * The 'post_type' and 'post_status' arguments can be used to choose what
308 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
309 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
310 * argument will accept any post status within the write administration panels.
315 * @todo Check validity of description.
317 * @global WP_Post $post
319 * @param mixed $args Optional. User defined arguments for replacing the defaults. Default empty.
320 * @param string $output Optional. Constant for return type. Accepts OBJECT, ARRAY_A, ARRAY_N.
322 * @return array Array of children, where the type of each element is determined by $output parameter.
323 * Empty array on failure.
325 function get_children( $args = '', $output = OBJECT ) {
327 if ( empty( $args ) ) {
328 if ( isset( $GLOBALS['post'] ) ) {
329 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
333 } elseif ( is_object( $args ) ) {
334 $args = array('post_parent' => (int) $args->post_parent );
335 } elseif ( is_numeric( $args ) ) {
336 $args = array('post_parent' => (int) $args);
340 'numberposts' => -1, 'post_type' => 'any',
341 'post_status' => 'any', 'post_parent' => 0,
344 $r = wp_parse_args( $args, $defaults );
346 $children = get_posts( $r );
351 if ( ! empty( $r['fields'] ) )
354 update_post_cache($children);
356 foreach ( $children as $key => $child )
357 $kids[$child->ID] = $children[$key];
359 if ( $output == OBJECT ) {
361 } elseif ( $output == ARRAY_A ) {
363 foreach ( (array) $kids as $kid ) {
364 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
367 } elseif ( $output == ARRAY_N ) {
369 foreach ( (array) $kids as $kid ) {
370 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
379 * Get extended entry info (<!--more-->).
381 * There should not be any space after the second dash and before the word
382 * 'more'. There can be text or space(s) after the word 'more', but won't be
385 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
386 * the `<!--more-->`. The 'extended' key has the content after the
387 * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
391 * @param string $post Post content.
392 * @return array Post before ('main'), after ('extended'), and custom read more ('more_text').
394 function get_extended( $post ) {
395 //Match the new style more links.
396 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
397 list($main, $extended) = explode($matches[0], $post, 2);
398 $more_text = $matches[1];
405 // leading and trailing whitespace.
406 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
407 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
408 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
410 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
414 * Retrieves post data given a post ID or post object.
416 * See sanitize_post() for optional $filter values. Also, the parameter
417 * `$post`, must be given as a variable, since it is passed by reference.
421 * @global WP_Post $post
423 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
424 * @param string $output Optional, default is Object. Accepts OBJECT, ARRAY_A, or ARRAY_N.
426 * @param string $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
427 * or 'display'. Default 'raw'.
428 * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
429 * When $output is OBJECT, a `WP_Post` instance is returned.
431 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
432 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
433 $post = $GLOBALS['post'];
435 if ( $post instanceof WP_Post ) {
437 } elseif ( is_object( $post ) ) {
438 if ( empty( $post->filter ) ) {
439 $_post = sanitize_post( $post, 'raw' );
440 $_post = new WP_Post( $_post );
441 } elseif ( 'raw' == $post->filter ) {
442 $_post = new WP_Post( $post );
444 $_post = WP_Post::get_instance( $post->ID );
447 $_post = WP_Post::get_instance( $post );
453 $_post = $_post->filter( $filter );
455 if ( $output == ARRAY_A )
456 return $_post->to_array();
457 elseif ( $output == ARRAY_N )
458 return array_values( $_post->to_array() );
464 * Retrieve ancestors of a post.
468 * @param int|WP_Post $post Post ID or post object.
469 * @return array Ancestor IDs or empty array if none are found.
471 function get_post_ancestors( $post ) {
472 $post = get_post( $post );
474 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
477 $ancestors = array();
479 $id = $ancestors[] = $post->post_parent;
481 while ( $ancestor = get_post( $id ) ) {
482 // Loop detection: If the ancestor has been seen before, break.
483 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
486 $id = $ancestors[] = $ancestor->post_parent;
493 * Retrieve data from a post field based on Post ID.
495 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
496 * etc and based off of the post object property or key names.
498 * The context values are based off of the taxonomy filter functions and
499 * supported values are found within those functions.
502 * @since 4.5.0 The `$post` parameter was made optional.
504 * @see sanitize_post_field()
506 * @param string $field Post field name.
507 * @param int|WP_Post $post Optional. Post ID or post object. Defaults to current post.
508 * @param string $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
509 * or 'display'. Default 'display'.
510 * @return string The value of the post field on success, empty string on failure.
512 function get_post_field( $field, $post = null, $context = 'display' ) {
513 $post = get_post( $post );
518 if ( !isset($post->$field) )
521 return sanitize_post_field($field, $post->$field, $post->ID, $context);
525 * Retrieve the mime type of an attachment based on the ID.
527 * This function can be used with any post type, but it makes more sense with
532 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
533 * @return string|false The mime type on success, false on failure.
535 function get_post_mime_type( $ID = '' ) {
536 $post = get_post($ID);
538 if ( is_object($post) )
539 return $post->post_mime_type;
545 * Retrieve the post status based on the Post ID.
547 * If the post ID is of an attachment, then the parent post status will be given
552 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
553 * @return string|false Post status on success, false on failure.
555 function get_post_status( $ID = '' ) {
556 $post = get_post($ID);
558 if ( !is_object($post) )
561 if ( 'attachment' == $post->post_type ) {
562 if ( 'private' == $post->post_status )
565 // Unattached attachments are assumed to be published.
566 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
569 // Inherit status from the parent.
570 if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) {
571 $parent_post_status = get_post_status( $post->post_parent );
572 if ( 'trash' == $parent_post_status ) {
573 return get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
575 return $parent_post_status;
582 * Filters the post status.
586 * @param string $post_status The post status.
587 * @param WP_Post $post The post object.
589 return apply_filters( 'get_post_status', $post->post_status, $post );
593 * Retrieve all of the WordPress supported post statuses.
595 * Posts have a limited set of valid status values, this provides the
596 * post_status values and descriptions.
600 * @return array List of post statuses.
602 function get_post_statuses() {
604 'draft' => __( 'Draft' ),
605 'pending' => __( 'Pending Review' ),
606 'private' => __( 'Private' ),
607 'publish' => __( 'Published' )
614 * Retrieve all of the WordPress support page statuses.
616 * Pages have a limited set of valid status values, this provides the
617 * post_status values and descriptions.
621 * @return array List of page statuses.
623 function get_page_statuses() {
625 'draft' => __( 'Draft' ),
626 'private' => __( 'Private' ),
627 'publish' => __( 'Published' )
634 * Register a post status. Do not use before init.
636 * A simple function for creating or modifying a post status based on the
637 * parameters given. The function will accept an array (second optional
638 * parameter), along with a string for the post status name.
640 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
643 * @global array $wp_post_statuses Inserts new post status object into the list
645 * @param string $post_status Name of the post status.
646 * @param array|string $args {
647 * Optional. Array or string of post status arguments.
649 * @type bool|string $label A descriptive name for the post status marked
650 * for translation. Defaults to value of $post_status.
651 * @type bool|array $label_count Descriptive text to use for nooped plurals.
652 * Default array of $label, twice
653 * @type bool $exclude_from_search Whether to exclude posts with this post status
654 * from search results. Default is value of $internal.
655 * @type bool $_builtin Whether the status is built-in. Core-use only.
657 * @type bool $public Whether posts of this status should be shown
658 * in the front end of the site. Default false.
659 * @type bool $internal Whether the status is for internal use only.
661 * @type bool $protected Whether posts with this status should be protected.
663 * @type bool $private Whether posts with this status should be private.
665 * @type bool $publicly_queryable Whether posts with this status should be publicly-
666 * queryable. Default is value of $public.
667 * @type bool $show_in_admin_all_list Whether to include posts in the edit listing for
668 * their post type. Default is value of $internal.
669 * @type bool $show_in_admin_status_list Show in the list of statuses with post counts at
670 * the top of the edit listings,
671 * e.g. All (12) | Published (9) | My Custom Status (2)
672 * Default is value of $internal.
676 function register_post_status( $post_status, $args = array() ) {
677 global $wp_post_statuses;
679 if (!is_array($wp_post_statuses))
680 $wp_post_statuses = array();
682 // Args prefixed with an underscore are reserved for internal use.
685 'label_count' => false,
686 'exclude_from_search' => null,
692 'publicly_queryable' => null,
693 'show_in_admin_status_list' => null,
694 'show_in_admin_all_list' => null,
696 $args = wp_parse_args($args, $defaults);
697 $args = (object) $args;
699 $post_status = sanitize_key($post_status);
700 $args->name = $post_status;
702 // Set various defaults.
703 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
704 $args->internal = true;
706 if ( null === $args->public )
707 $args->public = false;
709 if ( null === $args->private )
710 $args->private = false;
712 if ( null === $args->protected )
713 $args->protected = false;
715 if ( null === $args->internal )
716 $args->internal = false;
718 if ( null === $args->publicly_queryable )
719 $args->publicly_queryable = $args->public;
721 if ( null === $args->exclude_from_search )
722 $args->exclude_from_search = $args->internal;
724 if ( null === $args->show_in_admin_all_list )
725 $args->show_in_admin_all_list = !$args->internal;
727 if ( null === $args->show_in_admin_status_list )
728 $args->show_in_admin_status_list = !$args->internal;
730 if ( false === $args->label )
731 $args->label = $post_status;
733 if ( false === $args->label_count )
734 $args->label_count = array( $args->label, $args->label );
736 $wp_post_statuses[$post_status] = $args;
742 * Retrieve a post status object by name.
746 * @global array $wp_post_statuses List of post statuses.
748 * @see register_post_status()
750 * @param string $post_status The name of a registered post status.
751 * @return object|null A post status object.
753 function get_post_status_object( $post_status ) {
754 global $wp_post_statuses;
756 if ( empty($wp_post_statuses[$post_status]) )
759 return $wp_post_statuses[$post_status];
763 * Get a list of post statuses.
767 * @global array $wp_post_statuses List of post statuses.
769 * @see register_post_status()
771 * @param array|string $args Optional. Array or string of post status arguments to compare against
772 * properties of the global `$wp_post_statuses objects`. Default empty array.
773 * @param string $output Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
774 * @param string $operator Optional. The logical operation to perform. 'or' means only one element
775 * from the array needs to match; 'and' means all elements must match.
777 * @return array A list of post status names or objects.
779 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
780 global $wp_post_statuses;
782 $field = ('names' == $output) ? 'name' : false;
784 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
788 * Whether the post type is hierarchical.
790 * A false return value might also mean that the post type does not exist.
794 * @see get_post_type_object()
796 * @param string $post_type Post type name
797 * @return bool Whether post type is hierarchical.
799 function is_post_type_hierarchical( $post_type ) {
800 if ( ! post_type_exists( $post_type ) )
803 $post_type = get_post_type_object( $post_type );
804 return $post_type->hierarchical;
808 * Check if a post type is registered.
812 * @see get_post_type_object()
814 * @param string $post_type Post type name.
815 * @return bool Whether post type is registered.
817 function post_type_exists( $post_type ) {
818 return (bool) get_post_type_object( $post_type );
822 * Retrieves the post type of the current post or of a given post.
826 * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
827 * @return string|false Post type on success, false on failure.
829 function get_post_type( $post = null ) {
830 if ( $post = get_post( $post ) )
831 return $post->post_type;
837 * Retrieves a post type object by name.
840 * @since 4.6.0 Object returned is now an instance of WP_Post_Type.
842 * @global array $wp_post_types List of post types.
844 * @see register_post_type()
846 * @param string $post_type The name of a registered post type.
847 * @return WP_Post_Type|null WP_Post_Type object if it exists, null otherwise.
849 function get_post_type_object( $post_type ) {
850 global $wp_post_types;
852 if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
856 return $wp_post_types[ $post_type ];
860 * Get a list of all registered post type objects.
864 * @global array $wp_post_types List of post types.
866 * @see register_post_type() for accepted arguments.
868 * @param array|string $args Optional. An array of key => value arguments to match against
869 * the post type objects. Default empty array.
870 * @param string $output Optional. The type of output to return. Accepts post type 'names'
871 * or 'objects'. Default 'names'.
872 * @param string $operator Optional. The logical operation to perform. 'or' means only one
873 * element from the array needs to match; 'and' means all elements
874 * must match; 'not' means no elements may match. Default 'and'.
875 * @return array A list of post type names or objects.
877 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
878 global $wp_post_types;
880 $field = ('names' == $output) ? 'name' : false;
882 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
886 * Registers a post type.
888 * Note: Post type registrations should not be hooked before the
889 * {@see 'init'} action. Also, any taxonomy connections should be
890 * registered via the `$taxonomies` argument to ensure consistency
891 * when hooks such as {@see 'parse_query'} or {@see 'pre_get_posts'}
894 * Post types can support any number of built-in core features such
895 * as meta boxes, custom fields, post thumbnails, post statuses,
896 * comments, and more. See the `$supports` argument for a complete
897 * list of supported features.
900 * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
901 * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing
902 * screen and post editing screen.
903 * @since 4.6.0 Post type object returned is now an instance of WP_Post_Type.
905 * @global array $wp_post_types List of post types.
907 * @param string $post_type Post type key. Must not exceed 20 characters and may
908 * only contain lowercase alphanumeric characters, dashes,
909 * and underscores. See sanitize_key().
910 * @param array|string $args {
911 * Array or string of arguments for registering a post type.
913 * @type string $label Name of the post type shown in the menu. Usually plural.
914 * Default is value of $labels['name'].
915 * @type array $labels An array of labels for this post type. If not set, post
916 * labels are inherited for non-hierarchical types and page
917 * labels for hierarchical ones. See get_post_type_labels() for a full
918 * list of supported labels.
919 * @type string $description A short descriptive summary of what the post type is.
921 * @type bool $public Whether a post type is intended for use publicly either via
922 * the admin interface or by front-end users. While the default
923 * settings of $exclude_from_search, $publicly_queryable, $show_ui,
924 * and $show_in_nav_menus are inherited from public, each does not
925 * rely on this relationship and controls a very specific intention.
927 * @type bool $hierarchical Whether the post type is hierarchical (e.g. page). Default false.
928 * @type bool $exclude_from_search Whether to exclude posts with this post type from front end search
929 * results. Default is the opposite value of $public.
930 * @type bool $publicly_queryable Whether queries can be performed on the front end for the post type
931 * as part of parse_request(). Endpoints would include:
932 * * ?post_type={post_type_key}
933 * * ?{post_type_key}={single_post_slug}
934 * * ?{post_type_query_var}={single_post_slug}
935 * If not set, the default is inherited from $public.
936 * @type bool $show_ui Whether to generate and allow a UI for managing this post type in the
937 * admin. Default is value of $public.
938 * @type bool $show_in_menu Where to show the post type in the admin menu. To work, $show_ui
939 * must be true. If true, the post type is shown in its own top level
940 * menu. If false, no menu is shown. If a string of an existing top
941 * level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
942 * type will be placed as a sub-menu of that.
943 * Default is value of $show_ui.
944 * @type bool $show_in_nav_menus Makes this post type available for selection in navigation menus.
945 * Default is value $public.
946 * @type bool $show_in_admin_bar Makes this post type available via the admin bar. Default is value
948 * @type int $menu_position The position in the menu order the post type should appear. To work,
949 * $show_in_menu must be true. Default null (at the bottom).
950 * @type string $menu_icon The url to the icon to be used for this menu. Pass a base64-encoded
951 * SVG using a data URI, which will be colored to match the color scheme
952 * -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
953 * of a Dashicons helper class to use a font icon, e.g.
954 * 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
955 * so an icon can be added via CSS. Defaults to use the posts icon.
956 * @type string $capability_type The string to use to build the read, edit, and delete capabilities.
957 * May be passed as an array to allow for alternative plurals when using
958 * this argument as a base to construct the capabilities, e.g.
959 * array('story', 'stories'). Default 'post'.
960 * @type array $capabilities Array of capabilities for this post type. $capability_type is used
961 * as a base to construct capabilities by default.
962 * See get_post_type_capabilities().
963 * @type bool $map_meta_cap Whether to use the internal default meta capability handling.
965 * @type array $supports Core feature(s) the post type supports. Serves as an alias for calling
966 * add_post_type_support() directly. Core features include 'title',
967 * 'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt',
968 * 'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'.
969 * Additionally, the 'revisions' feature dictates whether the post type
970 * will store revisions, and the 'comments' feature dictates whether the
971 * comments count will show on the edit screen. Defaults is an array
972 * containing 'title' and 'editor'.
973 * @type callable $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
974 * edit form. Do remove_meta_box() and add_meta_box() calls in the
975 * callback. Default null.
976 * @type array $taxonomies An array of taxonomy identifiers that will be registered for the
977 * post type. Taxonomies can be registered later with register_taxonomy()
978 * or register_taxonomy_for_object_type().
979 * Default empty array.
980 * @type bool|string $has_archive Whether there should be post type archives, or if a string, the
981 * archive slug to use. Will generate the proper rewrite rules if
982 * $rewrite is enabled. Default false.
983 * @type bool|array $rewrite {
984 * Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
985 * Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
986 * passed with any of these keys:
988 * @type string $slug Customize the permastruct slug. Defaults to $post_type key.
989 * @type bool $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
991 * @type bool $feeds Whether the feed permastruct should be built for this post type.
992 * Default is value of $has_archive.
993 * @type bool $pages Whether the permastruct should provide for pagination. Default true.
994 * @type const $ep_mask Endpoint mask to assign. If not specified and permalink_epmask is set,
995 * inherits from $permalink_epmask. If not specified and permalink_epmask
996 * is not set, defaults to EP_PERMALINK.
998 * @type string|bool $query_var Sets the query_var key for this post type. Defaults to $post_type
999 * key. If false, a post type cannot be loaded at
1000 * ?{query_var}={post_slug}. If specified as a string, the query
1001 * ?{query_var_string}={post_slug} will be valid.
1002 * @type bool $can_export Whether to allow this post type to be exported. Default true.
1003 * @type bool $delete_with_user Whether to delete posts of this type when deleting a user. If true,
1004 * posts of this type belonging to the user will be moved to trash
1005 * when then user is deleted. If false, posts of this type belonging
1006 * to the user will *not* be trashed or deleted. If not set (the default),
1007 * posts are trashed if post_type_supports('author'). Otherwise posts
1008 * are not trashed or deleted. Default null.
1009 * @type bool $_builtin FOR INTERNAL USE ONLY! True if this post type is a native or
1010 * "built-in" post_type. Default false.
1011 * @type string $_edit_link FOR INTERNAL USE ONLY! URL segment to use for edit link of
1012 * this post type. Default 'post.php?post=%d'.
1014 * @return WP_Post_Type|WP_Error The registered post type object, or an error object.
1016 function register_post_type( $post_type, $args = array() ) {
1017 global $wp_post_types;
1019 if ( ! is_array( $wp_post_types ) ) {
1020 $wp_post_types = array();
1023 // Sanitize post type name
1024 $post_type = sanitize_key( $post_type );
1026 if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1027 _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2.0' );
1028 return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1031 $post_type_object = new WP_Post_Type( $post_type, $args );
1032 $post_type_object->add_supports();
1033 $post_type_object->add_rewrite_rules();
1034 $post_type_object->register_meta_boxes();
1036 $wp_post_types[ $post_type ] = $post_type_object;
1038 $post_type_object->add_hooks();
1039 $post_type_object->register_taxonomies();
1042 * Fires after a post type is registered.
1045 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1047 * @param string $post_type Post type.
1048 * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1050 do_action( 'registered_post_type', $post_type, $post_type_object );
1052 return $post_type_object;
1056 * Unregisters a post type.
1058 * Can not be used to unregister built-in post types.
1062 * @global array $wp_post_types List of post types.
1064 * @param string $post_type Post type to unregister.
1065 * @return bool|WP_Error True on success, WP_Error on failure or if the post type doesn't exist.
1067 function unregister_post_type( $post_type ) {
1068 global $wp_post_types;
1070 if ( ! post_type_exists( $post_type ) ) {
1071 return new WP_Error( 'invalid_post_type', __( 'Invalid post type.' ) );
1074 $post_type_object = get_post_type_object( $post_type );
1076 // Do not allow unregistering internal post types.
1077 if ( $post_type_object->_builtin ) {
1078 return new WP_Error( 'invalid_post_type', __( 'Unregistering a built-in post type is not allowed' ) );
1081 $post_type_object->remove_supports();
1082 $post_type_object->remove_rewrite_rules();
1083 $post_type_object->unregister_meta_boxes();
1084 $post_type_object->remove_hooks();
1085 $post_type_object->unregister_taxonomies();
1087 unset( $wp_post_types[ $post_type ] );
1090 * Fires after a post type was unregistered.
1094 * @param string $post_type Post type key.
1096 do_action( 'unregistered_post_type', $post_type );
1102 * Build an object with all post type capabilities out of a post type object
1104 * Post type capabilities use the 'capability_type' argument as a base, if the
1105 * capability is not set in the 'capabilities' argument array or if the
1106 * 'capabilities' argument is not supplied.
1108 * The capability_type argument can optionally be registered as an array, with
1109 * the first value being singular and the second plural, e.g. array('story, 'stories')
1110 * Otherwise, an 's' will be added to the value for the plural form. After
1111 * registration, capability_type will always be a string of the singular value.
1113 * By default, seven keys are accepted as part of the capabilities array:
1115 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1116 * generally mapped to corresponding primitive capabilities depending on the
1117 * context, which would be the post being edited/read/deleted and the user or
1118 * role being checked. Thus these capabilities would generally not be granted
1119 * directly to users or roles.
1121 * - edit_posts - Controls whether objects of this post type can be edited.
1122 * - edit_others_posts - Controls whether objects of this type owned by other users
1123 * can be edited. If the post type does not support an author, then this will
1124 * behave like edit_posts.
1125 * - publish_posts - Controls publishing objects of this post type.
1126 * - read_private_posts - Controls whether private objects can be read.
1128 * These four primitive capabilities are checked in core in various locations.
1129 * There are also seven other primitive capabilities which are not referenced
1130 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1131 * meta capabilities and translates them into one or more primitive capabilities
1132 * that must then be checked against the user or role, depending on the context.
1134 * - read - Controls whether objects of this post type can be read.
1135 * - delete_posts - Controls whether objects of this post type can be deleted.
1136 * - delete_private_posts - Controls whether private objects can be deleted.
1137 * - delete_published_posts - Controls whether published objects can be deleted.
1138 * - delete_others_posts - Controls whether objects owned by other users can be
1139 * can be deleted. If the post type does not support an author, then this will
1140 * behave like delete_posts.
1141 * - edit_private_posts - Controls whether private objects can be edited.
1142 * - edit_published_posts - Controls whether published objects can be edited.
1144 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1145 * only assigned by default if the post type is registered with the 'map_meta_cap'
1146 * argument set to true (default is false).
1150 * @see register_post_type()
1151 * @see map_meta_cap()
1153 * @param object $args Post type registration arguments.
1154 * @return object object with all the capabilities as member variables.
1156 function get_post_type_capabilities( $args ) {
1157 if ( ! is_array( $args->capability_type ) )
1158 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1160 // Singular base for meta capabilities, plural base for primitive capabilities.
1161 list( $singular_base, $plural_base ) = $args->capability_type;
1163 $default_capabilities = array(
1164 // Meta capabilities
1165 'edit_post' => 'edit_' . $singular_base,
1166 'read_post' => 'read_' . $singular_base,
1167 'delete_post' => 'delete_' . $singular_base,
1168 // Primitive capabilities used outside of map_meta_cap():
1169 'edit_posts' => 'edit_' . $plural_base,
1170 'edit_others_posts' => 'edit_others_' . $plural_base,
1171 'publish_posts' => 'publish_' . $plural_base,
1172 'read_private_posts' => 'read_private_' . $plural_base,
1175 // Primitive capabilities used within map_meta_cap():
1176 if ( $args->map_meta_cap ) {
1177 $default_capabilities_for_mapping = array(
1179 'delete_posts' => 'delete_' . $plural_base,
1180 'delete_private_posts' => 'delete_private_' . $plural_base,
1181 'delete_published_posts' => 'delete_published_' . $plural_base,
1182 'delete_others_posts' => 'delete_others_' . $plural_base,
1183 'edit_private_posts' => 'edit_private_' . $plural_base,
1184 'edit_published_posts' => 'edit_published_' . $plural_base,
1186 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1189 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1191 // Post creation capability simply maps to edit_posts by default:
1192 if ( ! isset( $capabilities['create_posts'] ) )
1193 $capabilities['create_posts'] = $capabilities['edit_posts'];
1195 // Remember meta capabilities for future reference.
1196 if ( $args->map_meta_cap )
1197 _post_type_meta_capabilities( $capabilities );
1199 return (object) $capabilities;
1203 * Store or return a list of post type meta caps for map_meta_cap().
1208 * @global array $post_type_meta_caps Used to store meta capabilities.
1210 * @param array $capabilities Post type meta capabilities.
1212 function _post_type_meta_capabilities( $capabilities = null ) {
1213 global $post_type_meta_caps;
1215 foreach ( $capabilities as $core => $custom ) {
1216 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) ) {
1217 $post_type_meta_caps[ $custom ] = $core;
1223 * Builds an object with all post type labels out of a post type object.
1225 * Accepted keys of the label array in the post type object:
1227 * - `name` - General name for the post type, usually plural. The same and overridden
1228 * by `$post_type_object->label`. Default is 'Posts' / 'Pages'.
1229 * - `singular_name` - Name for one object of this post type. Default is 'Post' / 'Page'.
1230 * - `add_new` - Default is 'Add New' for both hierarchical and non-hierarchical types.
1231 * When internationalizing this string, please use a {@link https://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context}
1232 * matching your post type. Example: `_x( 'Add New', 'product', 'textdomain' );`.
1233 * - `add_new_item` - Label for adding a new singular item. Default is 'Add New Post' / 'Add New Page'.
1234 * - `edit_item` - Label for editing a singular item. Default is 'Edit Post' / 'Edit Page'.
1235 * - `new_item` - Label for the new item page title. Default is 'New Post' / 'New Page'.
1236 * - `view_item` - Label for viewing a singular item. Default is 'View Post' / 'View Page'.
1237 * - `search_items` - Label for searching plural items. Default is 'Search Posts' / 'Search Pages'.
1238 * - `not_found` - Label used when no items are found. Default is 'No posts found' / 'No pages found'.
1239 * - `not_found_in_trash` - Label used when no items are in the trash. Default is 'No posts found in Trash' /
1240 * 'No pages found in Trash'.
1241 * - `parent_item_colon` - Label used to prefix parents of hierarchical items. Not used on non-hierarchical
1242 * post types. Default is 'Parent Page:'.
1243 * - `all_items` - Label to signify all items in a submenu link. Default is 'All Posts' / 'All Pages'.
1244 * - `archives` - Label for archives in nav menus. Default is 'Post Archives' / 'Page Archives'.
1245 * - `insert_into_item` - Label for the media frame button. Default is 'Insert into post' / 'Insert into page'.
1246 * - `uploaded_to_this_item` - Label for the media frame filter. Default is 'Uploaded to this post' /
1247 * 'Uploaded to this page'.
1248 * - `featured_image` - Label for the Featured Image meta box title. Default is 'Featured Image'.
1249 * - `set_featured_image` - Label for setting the featured image. Default is 'Set featured image'.
1250 * - `remove_featured_image` - Label for removing the featured image. Default is 'Remove featured image'.
1251 * - `use_featured_image` - Label in the media frame for using a featured image. Default is 'Use as featured image'.
1252 * - `menu_name` - Label for the menu name. Default is the same as `name`.
1253 * - `filter_items_list` - Label for the table views hidden heading. Default is 'Filter posts list' /
1254 * 'Filter pages list'.
1255 * - `items_list_navigation` - Label for the table pagination hidden heading. Default is 'Posts list navigation' /
1256 * 'Pages list navigation'.
1257 * - `items_list` - Label for the table hidden heading. Default is 'Posts list' / 'Pages list'.
1259 * Above, the first default value is for non-hierarchical post types (like posts)
1260 * and the second one is for hierarchical post types (like pages).
1262 * Note: To set labels used in post type admin notices, see the {@see 'post_updated_messages'} filter.
1265 * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
1266 * and `use_featured_image` labels.
1267 * @since 4.4.0 Added the `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
1268 * `items_list_navigation`, and `items_list` labels.
1269 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1273 * @param object|WP_Post_Type $post_type_object Post type object.
1274 * @return object Object with all the labels as member variables.
1276 function get_post_type_labels( $post_type_object ) {
1277 $nohier_vs_hier_defaults = array(
1278 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1279 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1280 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1281 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1282 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1283 'new_item' => array( __('New Post'), __('New Page') ),
1284 'view_item' => array( __('View Post'), __('View Page') ),
1285 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1286 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1287 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1288 'parent_item_colon' => array( null, __('Parent Page:') ),
1289 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ),
1290 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ),
1291 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ),
1292 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ),
1293 'featured_image' => array( __( 'Featured Image' ), __( 'Featured Image' ) ),
1294 'set_featured_image' => array( __( 'Set featured image' ), __( 'Set featured image' ) ),
1295 'remove_featured_image' => array( __( 'Remove featured image' ), __( 'Remove featured image' ) ),
1296 'use_featured_image' => array( __( 'Use as featured image' ), __( 'Use as featured image' ) ),
1297 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ),
1298 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ),
1299 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ),
1301 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1303 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1305 $post_type = $post_type_object->name;
1307 $default_labels = clone $labels;
1310 * Filters the labels of a specific post type.
1312 * The dynamic portion of the hook name, `$post_type`, refers to
1313 * the post type slug.
1317 * @see get_post_type_labels() for the full list of labels.
1319 * @param object $labels Object with labels for the post type as member variables.
1321 $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
1323 // Ensure that the filtered labels contain all required default values.
1324 $labels = (object) array_merge( (array) $default_labels, (array) $labels );
1330 * Build an object with custom-something object (post type, taxonomy) labels
1331 * out of a custom-something object
1336 * @param object $object A custom-something object.
1337 * @param array $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
1338 * @return object Object containing labels for the given custom-something object.
1340 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1341 $object->labels = (array) $object->labels;
1343 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1344 $object->labels['name'] = $object->label;
1346 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1347 $object->labels['singular_name'] = $object->labels['name'];
1349 if ( ! isset( $object->labels['name_admin_bar'] ) )
1350 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1352 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1353 $object->labels['menu_name'] = $object->labels['name'];
1355 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1356 $object->labels['all_items'] = $object->labels['menu_name'];
1358 if ( !isset( $object->labels['archives'] ) && isset( $object->labels['all_items'] ) ) {
1359 $object->labels['archives'] = $object->labels['all_items'];
1362 $defaults = array();
1363 foreach ( $nohier_vs_hier_defaults as $key => $value ) {
1364 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1366 $labels = array_merge( $defaults, $object->labels );
1367 $object->labels = (object) $object->labels;
1369 return (object) $labels;
1373 * Add submenus for post types.
1378 function _add_post_type_submenus() {
1379 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1380 $ptype_obj = get_post_type_object( $ptype );
1382 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1384 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" );
1389 * Register support of certain features for a post type.
1391 * All core features are directly associated with a functional area of the edit
1392 * screen, such as the editor or a meta box. Features include: 'title', 'editor',
1393 * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
1394 * 'thumbnail', 'custom-fields', and 'post-formats'.
1396 * Additionally, the 'revisions' feature dictates whether the post type will
1397 * store revisions, and the 'comments' feature dictates whether the comments
1398 * count will show on the edit screen.
1402 * @global array $_wp_post_type_features
1404 * @param string $post_type The post type for which to add the feature.
1405 * @param string|array $feature The feature being added, accepts an array of
1406 * feature strings or a single string.
1408 function add_post_type_support( $post_type, $feature ) {
1409 global $_wp_post_type_features;
1411 $features = (array) $feature;
1412 foreach ($features as $feature) {
1413 if ( func_num_args() == 2 )
1414 $_wp_post_type_features[$post_type][$feature] = true;
1416 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1421 * Remove support for a feature from a post type.
1425 * @global array $_wp_post_type_features
1427 * @param string $post_type The post type for which to remove the feature.
1428 * @param string $feature The feature being removed.
1430 function remove_post_type_support( $post_type, $feature ) {
1431 global $_wp_post_type_features;
1433 unset( $_wp_post_type_features[ $post_type ][ $feature ] );
1437 * Get all the post type features
1441 * @global array $_wp_post_type_features
1443 * @param string $post_type The post type.
1444 * @return array Post type supports list.
1446 function get_all_post_type_supports( $post_type ) {
1447 global $_wp_post_type_features;
1449 if ( isset( $_wp_post_type_features[$post_type] ) )
1450 return $_wp_post_type_features[$post_type];
1456 * Check a post type's support for a given feature.
1460 * @global array $_wp_post_type_features
1462 * @param string $post_type The post type being checked.
1463 * @param string $feature The feature being checked.
1464 * @return bool Whether the post type supports the given feature.
1466 function post_type_supports( $post_type, $feature ) {
1467 global $_wp_post_type_features;
1469 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1473 * Retrieves a list of post type names that support a specific feature.
1477 * @global array $_wp_post_type_features Post type features
1479 * @param array|string $feature Single feature or an array of features the post types should support.
1480 * @param string $operator Optional. The logical operation to perform. 'or' means
1481 * only one element from the array needs to match; 'and'
1482 * means all elements must match; 'not' means no elements may
1483 * match. Default 'and'.
1484 * @return array A list of post type names.
1486 function get_post_types_by_support( $feature, $operator = 'and' ) {
1487 global $_wp_post_type_features;
1489 $features = array_fill_keys( (array) $feature, true );
1491 return array_keys( wp_filter_object_list( $_wp_post_type_features, $features, $operator ) );
1495 * Update the post type for the post ID.
1497 * The page or post cache will be cleaned for the post ID.
1501 * @global wpdb $wpdb WordPress database abstraction object.
1503 * @param int $post_id Optional. Post ID to change post type. Default 0.
1504 * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
1505 * name a few. Default 'post'.
1506 * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
1508 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1511 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1512 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1514 clean_post_cache( $post_id );
1520 * Determines whether a post type is considered "viewable".
1522 * For built-in post types such as posts and pages, the 'public' value will be evaluated.
1523 * For all others, the 'publicly_queryable' value will be used.
1526 * @since 4.5.0 Added the ability to pass a post type name in addition to object.
1527 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1529 * @param string|WP_Post_Type $post_type Post type name or object.
1530 * @return bool Whether the post type should be considered viewable.
1532 function is_post_type_viewable( $post_type ) {
1533 if ( is_scalar( $post_type ) ) {
1534 $post_type = get_post_type_object( $post_type );
1535 if ( ! $post_type ) {
1540 return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
1544 * Retrieve list of latest posts or posts matching criteria.
1546 * The defaults are as follows:
1550 * @see WP_Query::parse_query()
1552 * @param array $args {
1553 * Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all
1554 * available arguments.
1556 * @type int $numberposts Total number of posts to retrieve. Is an alias of $posts_per_page
1557 * in WP_Query. Accepts -1 for all. Default 5.
1558 * @type int|string $category Category ID or comma-separated list of IDs (this or any children).
1559 * Is an alias of $cat in WP_Query. Default 0.
1560 * @type array $include An array of post IDs to retrieve, sticky posts will be included.
1561 * Is an alias of $post__in in WP_Query. Default empty array.
1562 * @type array $exclude An array of post IDs not to retrieve. Default empty array.
1563 * @type bool $suppress_filters Whether to suppress filters. Default true.
1565 * @return array List of posts.
1567 function get_posts( $args = null ) {
1570 'category' => 0, 'orderby' => 'date',
1571 'order' => 'DESC', 'include' => array(),
1572 'exclude' => array(), 'meta_key' => '',
1573 'meta_value' =>'', 'post_type' => 'post',
1574 'suppress_filters' => true
1577 $r = wp_parse_args( $args, $defaults );
1578 if ( empty( $r['post_status'] ) )
1579 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1580 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1581 $r['posts_per_page'] = $r['numberposts'];
1582 if ( ! empty($r['category']) )
1583 $r['cat'] = $r['category'];
1584 if ( ! empty($r['include']) ) {
1585 $incposts = wp_parse_id_list( $r['include'] );
1586 $r['posts_per_page'] = count($incposts); // only the number of posts included
1587 $r['post__in'] = $incposts;
1588 } elseif ( ! empty($r['exclude']) )
1589 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1591 $r['ignore_sticky_posts'] = true;
1592 $r['no_found_rows'] = true;
1594 $get_posts = new WP_Query;
1595 return $get_posts->query($r);
1600 // Post meta functions
1604 * Add meta data field to a post.
1606 * Post meta data is called "Custom Fields" on the Administration Screen.
1610 * @param int $post_id Post ID.
1611 * @param string $meta_key Metadata name.
1612 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1613 * @param bool $unique Optional. Whether the same key should not be added.
1615 * @return int|false Meta ID on success, false on failure.
1617 function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
1618 // Make sure meta is added to the post, not a revision.
1619 if ( $the_post = wp_is_post_revision($post_id) )
1620 $post_id = $the_post;
1622 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1626 * Remove metadata matching criteria from a post.
1628 * You can match based on the key, or key and value. Removing based on key and
1629 * value, will keep from removing duplicate metadata with the same key. It also
1630 * allows removing all metadata matching key, if needed.
1634 * @param int $post_id Post ID.
1635 * @param string $meta_key Metadata name.
1636 * @param mixed $meta_value Optional. Metadata value. Must be serializable if
1637 * non-scalar. Default empty.
1638 * @return bool True on success, false on failure.
1640 function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
1641 // Make sure meta is added to the post, not a revision.
1642 if ( $the_post = wp_is_post_revision($post_id) )
1643 $post_id = $the_post;
1645 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1649 * Retrieve post meta field for a post.
1653 * @param int $post_id Post ID.
1654 * @param string $key Optional. The meta key to retrieve. By default, returns
1655 * data for all keys. Default empty.
1656 * @param bool $single Optional. Whether to return a single value. Default false.
1657 * @return mixed Will be an array if $single is false. Will be value of meta data
1658 * field if $single is true.
1660 function get_post_meta( $post_id, $key = '', $single = false ) {
1661 return get_metadata('post', $post_id, $key, $single);
1665 * Update post meta field based on post ID.
1667 * Use the $prev_value parameter to differentiate between meta fields with the
1668 * same key and post ID.
1670 * If the meta field for the post does not exist, it will be added.
1674 * @param int $post_id Post ID.
1675 * @param string $meta_key Metadata key.
1676 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1677 * @param mixed $prev_value Optional. Previous value to check before removing.
1679 * @return int|bool Meta ID if the key didn't exist, true on successful update,
1682 function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
1683 // Make sure meta is added to the post, not a revision.
1684 if ( $the_post = wp_is_post_revision($post_id) )
1685 $post_id = $the_post;
1687 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1691 * Delete everything from post meta matching meta key.
1695 * @param string $post_meta_key Key to search for when deleting.
1696 * @return bool Whether the post meta key was deleted from the database.
1698 function delete_post_meta_by_key( $post_meta_key ) {
1699 return delete_metadata( 'post', null, $post_meta_key, '', true );
1703 * Retrieve post meta fields, based on post ID.
1705 * The post meta fields are retrieved from the cache where possible,
1706 * so the function is optimized to be called more than once.
1710 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1711 * @return array Post meta for the given post.
1713 function get_post_custom( $post_id = 0 ) {
1714 $post_id = absint( $post_id );
1716 $post_id = get_the_ID();
1718 return get_post_meta( $post_id );
1722 * Retrieve meta field names for a post.
1724 * If there are no meta fields, then nothing (null) will be returned.
1728 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1729 * @return array|void Array of the keys, if retrieved.
1731 function get_post_custom_keys( $post_id = 0 ) {
1732 $custom = get_post_custom( $post_id );
1734 if ( !is_array($custom) )
1737 if ( $keys = array_keys($custom) )
1742 * Retrieve values for a custom post field.
1744 * The parameters must not be considered optional. All of the post meta fields
1745 * will be retrieved and only the meta field key values returned.
1749 * @param string $key Optional. Meta field key. Default empty.
1750 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1751 * @return array|null Meta field values.
1753 function get_post_custom_values( $key = '', $post_id = 0 ) {
1757 $custom = get_post_custom($post_id);
1759 return isset($custom[$key]) ? $custom[$key] : null;
1763 * Check if post is sticky.
1765 * Sticky posts should remain at the top of The Loop. If the post ID is not
1766 * given, then The Loop ID for the current post will be used.
1770 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1771 * @return bool Whether post is sticky.
1773 function is_sticky( $post_id = 0 ) {
1774 $post_id = absint( $post_id );
1777 $post_id = get_the_ID();
1779 $stickies = get_option( 'sticky_posts' );
1781 if ( ! is_array( $stickies ) )
1784 if ( in_array( $post_id, $stickies ) )
1791 * Sanitize every post field.
1793 * If the context is 'raw', then the post object or array will get minimal
1794 * sanitization of the integer fields.
1798 * @see sanitize_post_field()
1800 * @param object|WP_Post|array $post The Post Object or Array
1801 * @param string $context Optional. How to sanitize post fields.
1802 * Accepts 'raw', 'edit', 'db', or 'display'.
1803 * Default 'display'.
1804 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the
1805 * same type as $post).
1807 function sanitize_post( $post, $context = 'display' ) {
1808 if ( is_object($post) ) {
1809 // Check if post already filtered for this context.
1810 if ( isset($post->filter) && $context == $post->filter )
1812 if ( !isset($post->ID) )
1814 foreach ( array_keys(get_object_vars($post)) as $field )
1815 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1816 $post->filter = $context;
1817 } elseif ( is_array( $post ) ) {
1818 // Check if post already filtered for this context.
1819 if ( isset($post['filter']) && $context == $post['filter'] )
1821 if ( !isset($post['ID']) )
1823 foreach ( array_keys($post) as $field )
1824 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1825 $post['filter'] = $context;
1831 * Sanitize post field based on context.
1833 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and
1834 * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
1835 * are treated like 'display' when calling filters.
1838 * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
1840 * @param string $field The Post Object field name.
1841 * @param mixed $value The Post Object value.
1842 * @param int $post_id Post ID.
1843 * @param string $context Optional. How to sanitize post fields. Looks for 'raw', 'edit',
1844 * 'db', 'display', 'attribute' and 'js'. Default 'display'.
1845 * @return mixed Sanitized value.
1847 function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
1848 $int_fields = array('ID', 'post_parent', 'menu_order');
1849 if ( in_array($field, $int_fields) )
1850 $value = (int) $value;
1852 // Fields which contain arrays of integers.
1853 $array_int_fields = array( 'ancestors' );
1854 if ( in_array($field, $array_int_fields) ) {
1855 $value = array_map( 'absint', $value);
1859 if ( 'raw' == $context )
1863 if ( false !== strpos($field, 'post_') ) {
1865 $field_no_prefix = str_replace('post_', '', $field);
1868 if ( 'edit' == $context ) {
1869 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1874 * Filters the value of a specific post field to edit.
1876 * The dynamic portion of the hook name, `$field`, refers to the post
1881 * @param mixed $value Value of the post field.
1882 * @param int $post_id Post ID.
1884 $value = apply_filters( "edit_{$field}", $value, $post_id );
1887 * Filters the value of a specific post field to edit.
1889 * The dynamic portion of the hook name, `$field_no_prefix`, refers to
1890 * the post field name.
1894 * @param mixed $value Value of the post field.
1895 * @param int $post_id Post ID.
1897 $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
1899 $value = apply_filters( "edit_post_{$field}", $value, $post_id );
1902 if ( in_array($field, $format_to_edit) ) {
1903 if ( 'post_content' == $field )
1904 $value = format_to_edit($value, user_can_richedit());
1906 $value = format_to_edit($value);
1908 $value = esc_attr($value);
1910 } elseif ( 'db' == $context ) {
1914 * Filters the value of a specific post field before saving.
1916 * The dynamic portion of the hook name, `$field`, refers to the post
1921 * @param mixed $value Value of the post field.
1923 $value = apply_filters( "pre_{$field}", $value );
1926 * Filters the value of a specific field before saving.
1928 * The dynamic portion of the hook name, `$field_no_prefix`, refers
1929 * to the post field name.
1933 * @param mixed $value Value of the post field.
1935 $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
1937 $value = apply_filters( "pre_post_{$field}", $value );
1940 * Filters the value of a specific post field before saving.
1942 * The dynamic portion of the hook name, `$field`, refers to the post
1947 * @param mixed $value Value of the post field.
1949 $value = apply_filters( "{$field}_pre", $value );
1953 // Use display filters by default.
1957 * Filters the value of a specific post field for display.
1959 * The dynamic portion of the hook name, `$field`, refers to the post
1964 * @param mixed $value Value of the prefixed post field.
1965 * @param int $post_id Post ID.
1966 * @param string $context Context for how to sanitize the field. Possible
1967 * values include 'raw', 'edit', 'db', 'display',
1968 * 'attribute' and 'js'.
1970 $value = apply_filters( $field, $value, $post_id, $context );
1972 $value = apply_filters( "post_{$field}", $value, $post_id, $context );
1975 if ( 'attribute' == $context ) {
1976 $value = esc_attr( $value );
1977 } elseif ( 'js' == $context ) {
1978 $value = esc_js( $value );
1986 * Make a post sticky.
1988 * Sticky posts should be displayed at the top of the front page.
1992 * @param int $post_id Post ID.
1994 function stick_post( $post_id ) {
1995 $stickies = get_option('sticky_posts');
1997 if ( !is_array($stickies) )
1998 $stickies = array($post_id);
2000 if ( ! in_array($post_id, $stickies) )
2001 $stickies[] = $post_id;
2003 $updated = update_option( 'sticky_posts', $stickies );
2007 * Fires once a post has been added to the sticky list.
2011 * @param int $post_id ID of the post that was stuck.
2013 do_action( 'post_stuck', $post_id );
2020 * Sticky posts should be displayed at the top of the front page.
2024 * @param int $post_id Post ID.
2026 function unstick_post( $post_id ) {
2027 $stickies = get_option('sticky_posts');
2029 if ( !is_array($stickies) )
2032 if ( ! in_array($post_id, $stickies) )
2035 $offset = array_search($post_id, $stickies);
2036 if ( false === $offset )
2039 array_splice($stickies, $offset, 1);
2041 $updated = update_option( 'sticky_posts', $stickies );
2045 * Fires once a post has been removed from the sticky list.
2049 * @param int $post_id ID of the post that was unstuck.
2051 do_action( 'post_unstuck', $post_id );
2056 * Return the cache key for wp_count_posts() based on the passed arguments.
2060 * @param string $type Optional. Post type to retrieve count Default 'post'.
2061 * @param string $perm Optional. 'readable' or empty. Default empty.
2062 * @return string The cache key.
2064 function _count_posts_cache_key( $type = 'post', $perm = '' ) {
2065 $cache_key = 'posts-' . $type;
2066 if ( 'readable' == $perm && is_user_logged_in() ) {
2067 $post_type_object = get_post_type_object( $type );
2068 if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2069 $cache_key .= '_' . $perm . '_' . get_current_user_id();
2076 * Count number of posts of a post type and if user has permissions to view.
2078 * This function provides an efficient method of finding the amount of post's
2079 * type a blog has. Another method is to count the amount of items in
2080 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2081 * when developing for 2.5+, use this function instead.
2083 * The $perm parameter checks for 'readable' value and if the user can read
2084 * private posts, it will display that for the user that is signed in.
2088 * @global wpdb $wpdb WordPress database abstraction object.
2090 * @param string $type Optional. Post type to retrieve count. Default 'post'.
2091 * @param string $perm Optional. 'readable' or empty. Default empty.
2092 * @return object Number of posts for each status.
2094 function wp_count_posts( $type = 'post', $perm = '' ) {
2097 if ( ! post_type_exists( $type ) )
2098 return new stdClass;
2100 $cache_key = _count_posts_cache_key( $type, $perm );
2102 $counts = wp_cache_get( $cache_key, 'counts' );
2103 if ( false !== $counts ) {
2104 /** This filter is documented in wp-includes/post.php */
2105 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2108 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2109 if ( 'readable' == $perm && is_user_logged_in() ) {
2110 $post_type_object = get_post_type_object($type);
2111 if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2112 $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
2113 get_current_user_id()
2117 $query .= ' GROUP BY post_status';
2119 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2120 $counts = array_fill_keys( get_post_stati(), 0 );
2122 foreach ( $results as $row ) {
2123 $counts[ $row['post_status'] ] = $row['num_posts'];
2126 $counts = (object) $counts;
2127 wp_cache_set( $cache_key, $counts, 'counts' );
2130 * Modify returned post counts by status for the current post type.
2134 * @param object $counts An object containing the current post_type's post
2136 * @param string $type Post type.
2137 * @param string $perm The permission to determine if the posts are 'readable'
2138 * by the current user.
2140 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2144 * Count number of attachments for the mime type(s).
2146 * If you set the optional mime_type parameter, then an array will still be
2147 * returned, but will only have the item you are looking for. It does not give
2148 * you the number of attachments that are children of a post. You can get that
2149 * by counting the number of children that post has.
2153 * @global wpdb $wpdb WordPress database abstraction object.
2155 * @param string|array $mime_type Optional. Array or comma-separated list of
2156 * MIME patterns. Default empty.
2157 * @return object An object containing the attachment counts by mime type.
2159 function wp_count_attachments( $mime_type = '' ) {
2162 $and = wp_post_mime_type_where( $mime_type );
2163 $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 );
2166 foreach ( (array) $count as $row ) {
2167 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2169 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2172 * Modify returned attachment counts by mime type.
2176 * @param object $counts An object containing the attachment counts by
2178 * @param string $mime_type The mime type pattern used to filter the attachments
2181 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2185 * Get default post mime types.
2189 * @return array List of post mime types.
2191 function get_post_mime_types() {
2192 $post_mime_types = array( // array( adj, noun )
2193 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2194 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2195 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2199 * Filters the default list of post mime types.
2203 * @param array $post_mime_types Default list of post mime types.
2205 return apply_filters( 'post_mime_types', $post_mime_types );
2209 * Check a MIME-Type against a list.
2211 * If the wildcard_mime_types parameter is a string, it must be comma separated
2212 * list. If the real_mime_types is a string, it is also comma separated to
2217 * @param string|array $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
2218 * or flash (same as *flash*).
2219 * @param string|array $real_mime_types Real post mime type values.
2220 * @return array array(wildcard=>array(real types)).
2222 function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
2224 if ( is_string( $wildcard_mime_types ) ) {
2225 $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
2227 if ( is_string( $real_mime_types ) ) {
2228 $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
2231 $patternses = array();
2232 $wild = '[-._a-z0-9]*';
2234 foreach ( (array) $wildcard_mime_types as $type ) {
2235 $mimes = array_map( 'trim', explode( ',', $type ) );
2236 foreach ( $mimes as $mime ) {
2237 $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
2238 $patternses[][$type] = "^$regex$";
2239 if ( false === strpos( $mime, '/' ) ) {
2240 $patternses[][$type] = "^$regex/";
2241 $patternses[][$type] = $regex;
2245 asort( $patternses );
2247 foreach ( $patternses as $patterns ) {
2248 foreach ( $patterns as $type => $pattern ) {
2249 foreach ( (array) $real_mime_types as $real ) {
2250 if ( preg_match( "#$pattern#", $real ) && ( empty( $matches[$type] ) || false === array_search( $real, $matches[$type] ) ) ) {
2251 $matches[$type][] = $real;
2260 * Convert MIME types into SQL.
2264 * @param string|array $post_mime_types List of mime types or comma separated string
2266 * @param string $table_alias Optional. Specify a table alias, if needed.
2268 * @return string The SQL AND clause for mime searching.
2270 function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
2272 $wildcards = array('', '%', '%/%');
2273 if ( is_string($post_mime_types) )
2274 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2278 foreach ( (array) $post_mime_types as $mime_type ) {
2279 $mime_type = preg_replace('/\s/', '', $mime_type);
2280 $slashpos = strpos($mime_type, '/');
2281 if ( false !== $slashpos ) {
2282 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2283 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2284 if ( empty($mime_subgroup) )
2285 $mime_subgroup = '*';
2287 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2288 $mime_pattern = "$mime_group/$mime_subgroup";
2290 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2291 if ( false === strpos($mime_pattern, '*') )
2292 $mime_pattern .= '/*';
2295 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2297 if ( in_array( $mime_type, $wildcards ) )
2300 if ( false !== strpos($mime_pattern, '%') )
2301 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2303 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2305 if ( !empty($wheres) )
2306 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2311 * Trash or delete a post or page.
2313 * When the post and page is permanently deleted, everything that is tied to
2314 * it is deleted also. This includes comments, post meta fields, and terms
2315 * associated with the post.
2317 * The post or page is moved to trash instead of permanently deleted unless
2318 * trash is disabled, item is already in the trash, or $force_delete is true.
2322 * @global wpdb $wpdb WordPress database abstraction object.
2323 * @see wp_delete_attachment()
2324 * @see wp_trash_post()
2326 * @param int $postid Optional. Post ID. Default 0.
2327 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
2329 * @return array|false|WP_Post False on failure.
2331 function wp_delete_post( $postid = 0, $force_delete = false ) {
2334 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2337 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2338 return wp_trash_post( $postid );
2340 if ( $post->post_type == 'attachment' )
2341 return wp_delete_attachment( $postid, $force_delete );
2344 * Filters whether a post deletion should take place.
2348 * @param bool $delete Whether to go forward with deletion.
2349 * @param WP_Post $post Post object.
2350 * @param bool $force_delete Whether to bypass the trash.
2352 $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
2353 if ( null !== $check ) {
2358 * Fires before a post is deleted, at the start of wp_delete_post().
2362 * @see wp_delete_post()
2364 * @param int $postid Post ID.
2366 do_action( 'before_delete_post', $postid );
2368 delete_post_meta($postid,'_wp_trash_meta_status');
2369 delete_post_meta($postid,'_wp_trash_meta_time');
2371 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2373 $parent_data = array( 'post_parent' => $post->post_parent );
2374 $parent_where = array( 'post_parent' => $postid );
2376 if ( is_post_type_hierarchical( $post->post_type ) ) {
2377 // Point children of this page to its parent, also clean the cache of affected children.
2378 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2379 $children = $wpdb->get_results( $children_query );
2381 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2385 // Do raw query. wp_get_post_revisions() is filtered.
2386 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2387 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2388 foreach ( $revision_ids as $revision_id )
2389 wp_delete_post_revision( $revision_id );
2391 // Point all attachments to this post up one level.
2392 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2394 wp_defer_comment_counting( true );
2396 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2397 foreach ( $comment_ids as $comment_id ) {
2398 wp_delete_comment( $comment_id, true );
2401 wp_defer_comment_counting( false );
2403 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2404 foreach ( $post_meta_ids as $mid )
2405 delete_metadata_by_mid( 'post', $mid );
2408 * Fires immediately before a post is deleted from the database.
2412 * @param int $postid Post ID.
2414 do_action( 'delete_post', $postid );
2415 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2421 * Fires immediately after a post is deleted from the database.
2425 * @param int $postid Post ID.
2427 do_action( 'deleted_post', $postid );
2429 clean_post_cache( $post );
2431 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2432 foreach ( $children as $child )
2433 clean_post_cache( $child );
2436 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2439 * Fires after a post is deleted, at the conclusion of wp_delete_post().
2443 * @see wp_delete_post()
2445 * @param int $postid Post ID.
2447 do_action( 'after_delete_post', $postid );
2453 * Reset the page_on_front, show_on_front, and page_for_post settings when
2454 * a linked page is deleted or trashed.
2456 * Also ensures the post is no longer sticky.
2461 * @param int $post_id Post ID.
2463 function _reset_front_page_settings_for_post( $post_id ) {
2464 $post = get_post( $post_id );
2465 if ( 'page' == $post->post_type ) {
2467 * If the page is defined in option page_on_front or post_for_posts,
2468 * adjust the corresponding options.
2470 if ( get_option( 'page_on_front' ) == $post->ID ) {
2471 update_option( 'show_on_front', 'posts' );
2472 update_option( 'page_on_front', 0 );
2474 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2475 delete_option( 'page_for_posts', 0 );
2478 unstick_post( $post->ID );
2482 * Move a post or page to the Trash
2484 * If trash is disabled, the post or page is permanently deleted.
2488 * @see wp_delete_post()
2490 * @param int $post_id Optional. Post ID. Default is ID of the global $post
2491 * if EMPTY_TRASH_DAYS equals true.
2492 * @return false|array|WP_Post|null Post data array, otherwise false.
2494 function wp_trash_post( $post_id = 0 ) {
2495 if ( !EMPTY_TRASH_DAYS )
2496 return wp_delete_post($post_id, true);
2498 if ( !$post = get_post($post_id, ARRAY_A) )
2501 if ( $post['post_status'] == 'trash' )
2505 * Fires before a post is sent to the trash.
2509 * @param int $post_id Post ID.
2511 do_action( 'wp_trash_post', $post_id );
2513 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2514 add_post_meta($post_id,'_wp_trash_meta_time', time());
2516 $post['post_status'] = 'trash';
2517 wp_insert_post( wp_slash( $post ) );
2519 wp_trash_post_comments($post_id);
2522 * Fires after a post is sent to the trash.
2526 * @param int $post_id Post ID.
2528 do_action( 'trashed_post', $post_id );
2534 * Restore a post or page from the Trash.
2538 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2539 * @return WP_Post|false WP_Post object. False on failure.
2541 function wp_untrash_post( $post_id = 0 ) {
2542 if ( !$post = get_post($post_id, ARRAY_A) )
2545 if ( $post['post_status'] != 'trash' )
2549 * Fires before a post is restored from the trash.
2553 * @param int $post_id Post ID.
2555 do_action( 'untrash_post', $post_id );
2557 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2559 $post['post_status'] = $post_status;
2561 delete_post_meta($post_id, '_wp_trash_meta_status');
2562 delete_post_meta($post_id, '_wp_trash_meta_time');
2564 wp_insert_post( wp_slash( $post ) );
2566 wp_untrash_post_comments($post_id);
2569 * Fires after a post is restored from the trash.
2573 * @param int $post_id Post ID.
2575 do_action( 'untrashed_post', $post_id );
2581 * Moves comments for a post to the trash.
2585 * @global wpdb $wpdb WordPress database abstraction object.
2587 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2588 * @return mixed|void False on failure.
2590 function wp_trash_post_comments( $post = null ) {
2593 $post = get_post($post);
2597 $post_id = $post->ID;
2600 * Fires before comments are sent to the trash.
2604 * @param int $post_id Post ID.
2606 do_action( 'trash_post_comments', $post_id );
2608 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2609 if ( empty($comments) )
2612 // Cache current status for each comment.
2613 $statuses = array();
2614 foreach ( $comments as $comment )
2615 $statuses[$comment->comment_ID] = $comment->comment_approved;
2616 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2618 // Set status for all comments to post-trashed.
2619 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2621 clean_comment_cache( array_keys($statuses) );
2624 * Fires after comments are sent to the trash.
2628 * @param int $post_id Post ID.
2629 * @param array $statuses Array of comment statuses.
2631 do_action( 'trashed_post_comments', $post_id, $statuses );
2637 * Restore comments for a post from the trash.
2641 * @global wpdb $wpdb WordPress database abstraction object.
2643 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2646 function wp_untrash_post_comments( $post = null ) {
2649 $post = get_post($post);
2653 $post_id = $post->ID;
2655 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2657 if ( empty($statuses) )
2661 * Fires before comments are restored for a post from the trash.
2665 * @param int $post_id Post ID.
2667 do_action( 'untrash_post_comments', $post_id );
2669 // Restore each comment to its original status.
2670 $group_by_status = array();
2671 foreach ( $statuses as $comment_id => $comment_status )
2672 $group_by_status[$comment_status][] = $comment_id;
2674 foreach ( $group_by_status as $status => $comments ) {
2675 // Sanity check. This shouldn't happen.
2676 if ( 'post-trashed' == $status ) {
2679 $comments_in = implode( ', ', array_map( 'intval', $comments ) );
2680 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
2683 clean_comment_cache( array_keys($statuses) );
2685 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2688 * Fires after comments are restored for a post from the trash.
2692 * @param int $post_id Post ID.
2694 do_action( 'untrashed_post_comments', $post_id );
2698 * Retrieve the list of categories for a post.
2700 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2701 * away from the complexity of the taxonomy layer.
2705 * @see wp_get_object_terms()
2707 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2708 * global $post. Default 0.
2709 * @param array $args Optional. Category arguments. See wp_get_object_terms(). Default empty.
2710 * @return array List of categories. If the `$fields` argument passed via `$args` is 'all' or
2711 * 'all_with_object_id', an array of WP_Term objects will be returned. If `$fields`
2712 * is 'ids', an array of category ids. If `$fields` is 'names', an array of category names.
2714 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2715 $post_id = (int) $post_id;
2717 $defaults = array('fields' => 'ids');
2718 $args = wp_parse_args( $args, $defaults );
2720 $cats = wp_get_object_terms($post_id, 'category', $args);
2725 * Retrieve the tags for a post.
2727 * There is only one default for this function, called 'fields' and by default
2728 * is set to 'all'. There are other defaults that can be overridden in
2729 * wp_get_object_terms().
2733 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2734 * global $post. Default 0.
2735 * @param array $args Optional. Overwrite the defaults
2736 * @return array List of post tags.
2738 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2739 return wp_get_post_terms( $post_id, 'post_tag', $args);
2743 * Retrieve the terms for a post.
2745 * There is only one default for this function, called 'fields' and by default
2746 * is set to 'all'. There are other defaults that can be overridden in
2747 * wp_get_object_terms().
2751 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2752 * global $post. Default 0.
2753 * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
2754 * @param array $args Optional. wp_get_object_terms() arguments. Default empty array.
2755 * @return array|WP_Error List of post terms or empty array if no terms were found. WP_Error object
2756 * if `$taxonomy` doesn't exist.
2758 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2759 $post_id = (int) $post_id;
2761 $defaults = array('fields' => 'all');
2762 $args = wp_parse_args( $args, $defaults );
2764 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2770 * Retrieve a number of recent posts.
2776 * @param array $args Optional. Arguments to retrieve posts. Default empty array.
2777 * @param string $output Optional. Type of output. Accepts ARRAY_A or ''. Default ARRAY_A.
2778 * @return array|false Associative array if $output equals ARRAY_A, array or false if no results.
2780 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2782 if ( is_numeric( $args ) ) {
2783 _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2784 $args = array( 'numberposts' => absint( $args ) );
2787 // Set default arguments.
2789 'numberposts' => 10, 'offset' => 0,
2790 'category' => 0, 'orderby' => 'post_date',
2791 'order' => 'DESC', 'include' => '',
2792 'exclude' => '', 'meta_key' => '',
2793 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2794 'suppress_filters' => true
2797 $r = wp_parse_args( $args, $defaults );
2799 $results = get_posts( $r );
2801 // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
2802 if ( ARRAY_A == $output ){
2803 foreach ( $results as $key => $result ) {
2804 $results[$key] = get_object_vars( $result );
2806 return $results ? $results : array();
2809 return $results ? $results : false;
2814 * Insert or update a post.
2816 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2818 * You can set the post date manually, by setting the values for 'post_date'
2819 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2820 * setting the value for 'comment_status' key.
2823 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
2824 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
2826 * @see sanitize_post()
2827 * @global wpdb $wpdb WordPress database abstraction object.
2829 * @param array $postarr {
2830 * An array of elements that make up a post to update or insert.
2832 * @type int $ID The post ID. If equal to something other than 0,
2833 * the post with that ID will be updated. Default 0.
2834 * @type int $post_author The ID of the user who added the post. Default is
2835 * the current user ID.
2836 * @type string $post_date The date of the post. Default is the current time.
2837 * @type string $post_date_gmt The date of the post in the GMT timezone. Default is
2838 * the value of `$post_date`.
2839 * @type mixed $post_content The post content. Default empty.
2840 * @type string $post_content_filtered The filtered post content. Default empty.
2841 * @type string $post_title The post title. Default empty.
2842 * @type string $post_excerpt The post excerpt. Default empty.
2843 * @type string $post_status The post status. Default 'draft'.
2844 * @type string $post_type The post type. Default 'post'.
2845 * @type string $comment_status Whether the post can accept comments. Accepts 'open' or 'closed'.
2846 * Default is the value of 'default_comment_status' option.
2847 * @type string $ping_status Whether the post can accept pings. Accepts 'open' or 'closed'.
2848 * Default is the value of 'default_ping_status' option.
2849 * @type string $post_password The password to access the post. Default empty.
2850 * @type string $post_name The post name. Default is the sanitized post title
2851 * when creating a new post.
2852 * @type string $to_ping Space or carriage return-separated list of URLs to ping.
2854 * @type string $pinged Space or carriage return-separated list of URLs that have
2855 * been pinged. Default empty.
2856 * @type string $post_modified The date when the post was last modified. Default is
2858 * @type string $post_modified_gmt The date when the post was last modified in the GMT
2859 * timezone. Default is the current time.
2860 * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
2861 * @type int $menu_order The order the post should be displayed in. Default 0.
2862 * @type string $post_mime_type The mime type of the post. Default empty.
2863 * @type string $guid Global Unique ID for referencing the post. Default empty.
2864 * @type array $post_category Array of category names, slugs, or IDs.
2865 * Defaults to value of the 'default_category' option.
2866 * @type array $tax_input Array of taxonomy terms keyed by their taxonomy name. Default empty.
2867 * @type array $meta_input Array of post meta values keyed by their post meta key. Default empty.
2869 * @param bool $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
2870 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2872 function wp_insert_post( $postarr, $wp_error = false ) {
2875 $user_id = get_current_user_id();
2878 'post_author' => $user_id,
2879 'post_content' => '',
2880 'post_content_filtered' => '',
2882 'post_excerpt' => '',
2883 'post_status' => 'draft',
2884 'post_type' => 'post',
2885 'comment_status' => '',
2886 'ping_status' => '',
2887 'post_password' => '',
2897 $postarr = wp_parse_args($postarr, $defaults);
2899 unset( $postarr[ 'filter' ] );
2901 $postarr = sanitize_post($postarr, 'db');
2903 // Are we updating or creating?
2906 $guid = $postarr['guid'];
2908 if ( ! empty( $postarr['ID'] ) ) {
2911 // Get the post ID and GUID.
2912 $post_ID = $postarr['ID'];
2913 $post_before = get_post( $post_ID );
2914 if ( is_null( $post_before ) ) {
2916 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2921 $guid = get_post_field( 'guid', $post_ID );
2922 $previous_status = get_post_field('post_status', $post_ID );
2924 $previous_status = 'new';
2927 $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
2929 $post_title = $postarr['post_title'];
2930 $post_content = $postarr['post_content'];
2931 $post_excerpt = $postarr['post_excerpt'];
2932 if ( isset( $postarr['post_name'] ) ) {
2933 $post_name = $postarr['post_name'];
2934 } elseif ( $update ) {
2935 // For an update, don't modify the post_name if it wasn't supplied as an argument.
2936 $post_name = $post_before->post_name;
2939 $maybe_empty = 'attachment' !== $post_type
2940 && ! $post_content && ! $post_title && ! $post_excerpt
2941 && post_type_supports( $post_type, 'editor' )
2942 && post_type_supports( $post_type, 'title' )
2943 && post_type_supports( $post_type, 'excerpt' );
2946 * Filters whether the post should be considered "empty".
2948 * The post is considered "empty" if both:
2949 * 1. The post type supports the title, editor, and excerpt fields
2950 * 2. The title, editor, and excerpt fields are all empty
2952 * Returning a truthy value to the filter will effectively short-circuit
2953 * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
2954 * will be returned instead.
2958 * @param bool $maybe_empty Whether the post should be considered "empty".
2959 * @param array $postarr Array of post data.
2961 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2963 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2969 $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
2970 if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash' ) ) ) {
2971 $post_status = 'inherit';
2974 if ( ! empty( $postarr['post_category'] ) ) {
2975 // Filter out empty terms.
2976 $post_category = array_filter( $postarr['post_category'] );
2979 // Make sure we set a valid category.
2980 if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
2981 // 'post' requires at least one category.
2982 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
2983 $post_category = array( get_option('default_category') );
2985 $post_category = array();
2989 // Don't allow contributors to set the post slug for pending review posts.
2990 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
2995 * Create a valid post name. Drafts and pending posts are allowed to have
2996 * an empty post name.
2998 if ( empty($post_name) ) {
2999 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3000 $post_name = sanitize_title($post_title);
3005 // On updates, we need to check to see if it's using the old, fixed sanitization context.
3006 $check_name = sanitize_title( $post_name, '', 'old-save' );
3007 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
3008 $post_name = $check_name;
3009 } else { // new post, or slug has changed.
3010 $post_name = sanitize_title($post_name);
3015 * If the post date is empty (due to having been new or a draft) and status
3016 * is not 'draft' or 'pending', set date to now.
3018 if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
3019 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3020 $post_date = current_time( 'mysql' );
3022 $post_date = get_date_from_gmt( $postarr['post_date_gmt'] );
3025 $post_date = $postarr['post_date'];
3028 // Validate the date.
3029 $mm = substr( $post_date, 5, 2 );
3030 $jj = substr( $post_date, 8, 2 );
3031 $aa = substr( $post_date, 0, 4 );
3032 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
3033 if ( ! $valid_date ) {
3035 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
3041 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3042 if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3043 $post_date_gmt = get_gmt_from_date( $post_date );
3045 $post_date_gmt = '0000-00-00 00:00:00';
3048 $post_date_gmt = $postarr['post_date_gmt'];
3051 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
3052 $post_modified = current_time( 'mysql' );
3053 $post_modified_gmt = current_time( 'mysql', 1 );
3055 $post_modified = $post_date;
3056 $post_modified_gmt = $post_date_gmt;
3059 if ( 'attachment' !== $post_type ) {
3060 if ( 'publish' == $post_status ) {
3061 $now = gmdate('Y-m-d H:i:59');
3062 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
3063 $post_status = 'future';
3065 } elseif ( 'future' == $post_status ) {
3066 $now = gmdate('Y-m-d H:i:59');
3067 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) {
3068 $post_status = 'publish';
3074 if ( empty( $postarr['comment_status'] ) ) {
3076 $comment_status = 'closed';
3078 $comment_status = get_default_comment_status( $post_type );
3081 $comment_status = $postarr['comment_status'];
3084 // These variables are needed by compact() later.
3085 $post_content_filtered = $postarr['post_content_filtered'];
3086 $post_author = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
3087 $ping_status = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
3088 $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
3089 $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
3090 $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
3093 * The 'wp_insert_post_parent' filter expects all variables to be present.
3094 * Previously, these variables would have already been extracted
3096 if ( isset( $postarr['menu_order'] ) ) {
3097 $menu_order = (int) $postarr['menu_order'];
3102 $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
3103 if ( 'private' == $post_status ) {
3104 $post_password = '';
3107 if ( isset( $postarr['post_parent'] ) ) {
3108 $post_parent = (int) $postarr['post_parent'];
3114 * Filters the post parent -- used to check for and prevent hierarchy loops.
3118 * @param int $post_parent Post parent ID.
3119 * @param int $post_ID Post ID.
3120 * @param array $new_postarr Array of parsed post data.
3121 * @param array $postarr Array of sanitized, but otherwise unmodified post data.
3123 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
3126 * If the post is being untrashed and it has a desired slug stored in post meta,
3129 if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
3130 $desired_post_slug = get_post_meta( $post_ID, '_wp_desired_post_slug', true );
3131 if ( $desired_post_slug ) {
3132 delete_post_meta( $post_ID, '_wp_desired_post_slug' );
3133 $post_name = $desired_post_slug;
3137 // If a trashed post has the desired slug, change it and let this post have it.
3138 if ( 'trash' !== $post_status && $post_name ) {
3139 wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID );
3142 // When trashing an existing post, change its slug to allow non-trashed posts to use it.
3143 if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
3144 $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_ID );
3147 $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
3150 $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
3152 // Expected_slashed (everything!).
3153 $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' );
3155 $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
3157 foreach ( $emoji_fields as $emoji_field ) {
3158 if ( isset( $data[ $emoji_field ] ) ) {
3159 $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
3160 if ( 'utf8' === $charset ) {
3161 $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
3166 if ( 'attachment' === $post_type ) {
3168 * Filters attachment post data before it is updated in or added to the database.
3172 * @param array $data An array of sanitized attachment post data.
3173 * @param array $postarr An array of unsanitized attachment post data.
3175 $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
3178 * Filters slashed post data just before it is inserted into the database.
3182 * @param array $data An array of slashed post data.
3183 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3185 $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
3187 $data = wp_unslash( $data );
3188 $where = array( 'ID' => $post_ID );
3192 * Fires immediately before an existing post is updated in the database.
3196 * @param int $post_ID Post ID.
3197 * @param array $data Array of unslashed post data.
3199 do_action( 'pre_post_update', $post_ID, $data );
3200 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
3202 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
3208 // If there is a suggested ID, use it if not already present.
3209 if ( ! empty( $import_id ) ) {
3210 $import_id = (int) $import_id;
3211 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3212 $data['ID'] = $import_id;
3215 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
3217 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
3222 $post_ID = (int) $wpdb->insert_id;
3224 // Use the newly generated $post_ID.
3225 $where = array( 'ID' => $post_ID );
3228 if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
3229 $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_ID ), $post_ID, $data['post_status'], $post_type, $post_parent );
3230 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
3231 clean_post_cache( $post_ID );
3234 if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
3235 wp_set_post_categories( $post_ID, $post_category );
3238 if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
3239 wp_set_post_tags( $post_ID, $postarr['tags_input'] );
3242 // New-style support for all custom taxonomies.
3243 if ( ! empty( $postarr['tax_input'] ) ) {
3244 foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
3245 $taxonomy_obj = get_taxonomy($taxonomy);
3246 if ( ! $taxonomy_obj ) {
3247 /* translators: %s: taxonomy name */
3248 _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
3252 // array = hierarchical, string = non-hierarchical.
3253 if ( is_array( $tags ) ) {
3254 $tags = array_filter($tags);
3256 if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
3257 wp_set_post_terms( $post_ID, $tags, $taxonomy );
3262 if ( ! empty( $postarr['meta_input'] ) ) {
3263 foreach ( $postarr['meta_input'] as $field => $value ) {
3264 update_post_meta( $post_ID, $field, $value );
3268 $current_guid = get_post_field( 'guid', $post_ID );
3271 if ( ! $update && '' == $current_guid ) {
3272 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
3275 if ( 'attachment' === $postarr['post_type'] ) {
3276 if ( ! empty( $postarr['file'] ) ) {
3277 update_attached_file( $post_ID, $postarr['file'] );
3280 if ( ! empty( $postarr['context'] ) ) {
3281 add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
3285 // Set or remove featured image.
3286 if ( isset( $postarr['_thumbnail_id'] ) ) {
3287 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
3288 if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
3289 if ( wp_attachment_is( 'audio', $post_ID ) ) {
3290 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3291 } elseif ( wp_attachment_is( 'video', $post_ID ) ) {
3292 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3296 if ( $thumbnail_support ) {
3297 $thumbnail_id = intval( $postarr['_thumbnail_id'] );
3298 if ( -1 === $thumbnail_id ) {
3299 delete_post_thumbnail( $post_ID );
3301 set_post_thumbnail( $post_ID, $thumbnail_id );
3306 clean_post_cache( $post_ID );
3308 $post = get_post( $post_ID );
3310 if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
3311 $post->page_template = $postarr['page_template'];
3312 $page_templates = wp_get_theme()->get_page_templates( $post );
3313 if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
3315 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
3317 update_post_meta( $post_ID, '_wp_page_template', 'default' );
3319 update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
3323 if ( 'attachment' !== $postarr['post_type'] ) {
3324 wp_transition_post_status( $data['post_status'], $previous_status, $post );
3328 * Fires once an existing attachment has been updated.
3332 * @param int $post_ID Attachment ID.
3334 do_action( 'edit_attachment', $post_ID );
3335 $post_after = get_post( $post_ID );
3338 * Fires once an existing attachment has been updated.
3342 * @param int $post_ID Post ID.
3343 * @param WP_Post $post_after Post object following the update.
3344 * @param WP_Post $post_before Post object before the update.
3346 do_action( 'attachment_updated', $post_ID, $post_after, $post_before );
3350 * Fires once an attachment has been added.
3354 * @param int $post_ID Attachment ID.
3356 do_action( 'add_attachment', $post_ID );
3364 * Fires once an existing post has been updated.
3368 * @param int $post_ID Post ID.
3369 * @param WP_Post $post Post object.
3371 do_action( 'edit_post', $post_ID, $post );
3372 $post_after = get_post($post_ID);
3375 * Fires once an existing post has been updated.
3379 * @param int $post_ID Post ID.
3380 * @param WP_Post $post_after Post object following the update.
3381 * @param WP_Post $post_before Post object before the update.
3383 do_action( 'post_updated', $post_ID, $post_after, $post_before);
3387 * Fires once a post has been saved.
3389 * The dynamic portion of the hook name, `$post->post_type`, refers to
3390 * the post type slug.
3394 * @param int $post_ID Post ID.
3395 * @param WP_Post $post Post object.
3396 * @param bool $update Whether this is an existing post being updated or not.
3398 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
3401 * Fires once a post has been saved.
3405 * @param int $post_ID Post ID.
3406 * @param WP_Post $post Post object.
3407 * @param bool $update Whether this is an existing post being updated or not.
3409 do_action( 'save_post', $post_ID, $post, $update );
3412 * Fires once a post has been saved.
3416 * @param int $post_ID Post ID.
3417 * @param WP_Post $post Post object.
3418 * @param bool $update Whether this is an existing post being updated or not.
3420 do_action( 'wp_insert_post', $post_ID, $post, $update );
3426 * Update a post with new post data.
3428 * The date does not have to be set for drafts. You can set the date and it will
3429 * not be overridden.
3433 * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
3434 * objects are not. Default array.
3435 * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
3436 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
3438 function wp_update_post( $postarr = array(), $wp_error = false ) {
3439 if ( is_object($postarr) ) {
3440 // Non-escaped post was passed.
3441 $postarr = get_object_vars($postarr);
3442 $postarr = wp_slash($postarr);
3445 // First, get all of the original fields.
3446 $post = get_post($postarr['ID'], ARRAY_A);
3448 if ( is_null( $post ) ) {
3450 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3454 // Escape data pulled from DB.
3455 $post = wp_slash($post);
3457 // Passed post category list overwrites existing category list if not empty.
3458 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3459 && 0 != count($postarr['post_category']) )
3460 $post_cats = $postarr['post_category'];
3462 $post_cats = $post['post_category'];
3464 // Drafts shouldn't be assigned a date unless explicitly done so by the user.
3465 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3466 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3469 $clear_date = false;
3471 // Merge old and new fields with new fields overwriting old ones.
3472 $postarr = array_merge($post, $postarr);
3473 $postarr['post_category'] = $post_cats;
3474 if ( $clear_date ) {
3475 $postarr['post_date'] = current_time('mysql');
3476 $postarr['post_date_gmt'] = '';
3479 if ($postarr['post_type'] == 'attachment')
3480 return wp_insert_attachment($postarr);
3482 return wp_insert_post( $postarr, $wp_error );
3486 * Publish a post by transitioning the post status.
3490 * @global wpdb $wpdb WordPress database abstraction object.
3492 * @param int|WP_Post $post Post ID or post object.
3494 function wp_publish_post( $post ) {
3497 if ( ! $post = get_post( $post ) )
3500 if ( 'publish' == $post->post_status )
3503 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3505 clean_post_cache( $post->ID );
3507 $old_status = $post->post_status;
3508 $post->post_status = 'publish';
3509 wp_transition_post_status( 'publish', $old_status, $post );
3511 /** This action is documented in wp-includes/post.php */
3512 do_action( 'edit_post', $post->ID, $post );
3514 /** This action is documented in wp-includes/post.php */
3515 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3517 /** This action is documented in wp-includes/post.php */
3518 do_action( 'save_post', $post->ID, $post, true );
3520 /** This action is documented in wp-includes/post.php */
3521 do_action( 'wp_insert_post', $post->ID, $post, true );
3525 * Publish future post and make sure post ID has future post status.
3527 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3528 * from publishing drafts, etc.
3532 * @param int|WP_Post $post_id Post ID or post object.
3534 function check_and_publish_future_post( $post_id ) {
3535 $post = get_post($post_id);
3540 if ( 'future' != $post->post_status )
3543 $time = strtotime( $post->post_date_gmt . ' GMT' );
3545 // Uh oh, someone jumped the gun!
3546 if ( $time > time() ) {
3547 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3548 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3552 // wp_publish_post() returns no meaningful value.
3553 wp_publish_post( $post_id );
3557 * Computes a unique slug for the post, when given the desired slug and some post details.
3561 * @global wpdb $wpdb WordPress database abstraction object.
3562 * @global WP_Rewrite $wp_rewrite
3564 * @param string $slug The desired slug (post_name).
3565 * @param int $post_ID Post ID.
3566 * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
3567 * @param string $post_type Post type.
3568 * @param int $post_parent Post parent ID.
3569 * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3571 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3572 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3575 global $wpdb, $wp_rewrite;
3577 $original_slug = $slug;
3579 $feeds = $wp_rewrite->feeds;
3580 if ( ! is_array( $feeds ) )
3583 if ( 'attachment' == $post_type ) {
3584 // Attachment slugs must be unique across all types.
3585 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3586 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3589 * Filters whether the post slug would make a bad attachment slug.
3593 * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
3594 * @param string $slug The post slug.
3596 if ( $post_name_check || in_array( $slug, $feeds ) || 'embed' === $slug || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3599 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3600 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3602 } while ( $post_name_check );
3603 $slug = $alt_post_name;
3605 } elseif ( is_post_type_hierarchical( $post_type ) ) {
3606 if ( 'nav_menu_item' == $post_type )
3610 * Page slugs must be unique within their own trees. Pages are in a separate
3611 * namespace than posts so page slugs are allowed to overlap post slugs.
3613 $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";
3614 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
3617 * Filters whether the post slug would make a bad hierarchical post slug.
3621 * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
3622 * @param string $slug The post slug.
3623 * @param string $post_type Post type.
3624 * @param int $post_parent Post parent ID.
3626 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 ) ) {
3629 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3630 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
3632 } while ( $post_name_check );
3633 $slug = $alt_post_name;
3636 // Post slugs must be unique across all posts.
3637 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3638 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3640 // Prevent new post slugs that could result in URLs that conflict with date archives.
3641 $post = get_post( $post_ID );
3642 $conflicts_with_date_archive = false;
3643 if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) && $slug_num = intval( $slug ) ) {
3644 $permastructs = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
3645 $postname_index = array_search( '%postname%', $permastructs );
3648 * Potential date clashes are as follows:
3650 * - Any integer in the first permastruct position could be a year.
3651 * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
3652 * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
3654 if ( 0 === $postname_index ||
3655 ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
3656 ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
3658 $conflicts_with_date_archive = true;
3663 * Filters whether the post slug would be bad as a flat slug.
3667 * @param bool $bad_slug Whether the post slug would be bad as a flat slug.
3668 * @param string $slug The post slug.
3669 * @param string $post_type Post type.
3671 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 ) ) {
3674 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3675 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3677 } while ( $post_name_check );
3678 $slug = $alt_post_name;
3683 * Filters the unique post slug.
3687 * @param string $slug The post slug.
3688 * @param int $post_ID Post ID.
3689 * @param string $post_status The post status.
3690 * @param string $post_type Post type.
3691 * @param int $post_parent Post parent ID
3692 * @param string $original_slug The original post slug.
3694 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3698 * Truncate a post slug.
3703 * @see utf8_uri_encode()
3705 * @param string $slug The slug to truncate.
3706 * @param int $length Optional. Max length of the slug. Default 200 (characters).
3707 * @return string The truncated slug.
3709 function _truncate_post_slug( $slug, $length = 200 ) {
3710 if ( strlen( $slug ) > $length ) {
3711 $decoded_slug = urldecode( $slug );
3712 if ( $decoded_slug === $slug )
3713 $slug = substr( $slug, 0, $length );
3715 $slug = utf8_uri_encode( $decoded_slug, $length );
3718 return rtrim( $slug, '-' );
3722 * Add tags to a post.
3724 * @see wp_set_post_tags()
3728 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3729 * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
3730 * separated by commas. Default empty.
3731 * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3733 function wp_add_post_tags( $post_id = 0, $tags = '' ) {
3734 return wp_set_post_tags($post_id, $tags, true);
3738 * Set the tags for a post.
3742 * @see wp_set_object_terms()
3744 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3745 * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
3746 * separated by commas. Default empty.
3747 * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
3748 * replace the tags with the new tags. Default false.
3749 * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
3751 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3752 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3756 * Set the terms for a post.
3760 * @see wp_set_object_terms()
3762 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3763 * @param string|array $tags Optional. An array of terms to set for the post, or a string of terms
3764 * separated by commas. Default empty.
3765 * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
3766 * @param bool $append Optional. If true, don't delete existing terms, just add on. If false,
3767 * replace the terms with the new terms. Default false.
3768 * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
3770 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3771 $post_id = (int) $post_id;
3779 if ( ! is_array( $tags ) ) {
3780 $comma = _x( ',', 'tag delimiter' );
3781 if ( ',' !== $comma )
3782 $tags = str_replace( $comma, ',', $tags );
3783 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3787 * Hierarchical taxonomies must always pass IDs rather than names so that
3788 * children with the same names but different parents aren't confused.
3790 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3791 $tags = array_unique( array_map( 'intval', $tags ) );
3794 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3798 * Set categories for a post.
3800 * If the post categories parameter is not set, then the default category is
3805 * @param int $post_ID Optional. The Post ID. Does not default to the ID
3806 * of the global $post. Default 0.
3807 * @param array|int $post_categories Optional. List of categories or ID of category.
3808 * Default empty array.
3809 * @param bool $append If true, don't delete existing categories, just add on.
3810 * If false, replace the categories with the new categories.
3811 * @return array|false|WP_Error Array of term taxonomy IDs of affected categories. WP_Error or false on failure.
3813 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3814 $post_ID = (int) $post_ID;
3815 $post_type = get_post_type( $post_ID );
3816 $post_status = get_post_status( $post_ID );
3817 // If $post_categories isn't already an array, make it one:
3818 $post_categories = (array) $post_categories;
3819 if ( empty( $post_categories ) ) {
3820 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3821 $post_categories = array( get_option('default_category') );
3824 $post_categories = array();
3826 } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) {
3830 return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3834 * Fires actions related to the transitioning of a post's status.
3836 * When a post is saved, the post status is "transitioned" from one status to another,
3837 * though this does not always mean the status has actually changed before and after
3838 * the save. This function fires a number of action hooks related to that transition:
3839 * the generic {@see 'transition_post_status'} action, as well as the dynamic hooks
3840 * {@see '$old_status_to_$new_status'} and {@see '$new_status_$post->post_type'}. Note
3841 * that the function does not transition the post object in the database.
3843 * For instance: When publishing a post for the first time, the post status may transition
3844 * from 'draft' – or some other status – to 'publish'. However, if a post is already
3845 * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
3846 * before and after the transition.
3850 * @param string $new_status Transition to this post status.
3851 * @param string $old_status Previous post status.
3852 * @param WP_Post $post Post data.
3854 function wp_transition_post_status( $new_status, $old_status, $post ) {
3856 * Fires when a post is transitioned from one status to another.
3860 * @param string $new_status New post status.
3861 * @param string $old_status Old post status.
3862 * @param WP_Post $post Post object.
3864 do_action( 'transition_post_status', $new_status, $old_status, $post );
3867 * Fires when a post is transitioned from one status to another.
3869 * The dynamic portions of the hook name, `$new_status` and `$old status`,
3870 * refer to the old and new post statuses, respectively.
3874 * @param WP_Post $post Post object.
3876 do_action( "{$old_status}_to_{$new_status}", $post );
3879 * Fires when a post is transitioned from one status to another.
3881 * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
3882 * refer to the new post status and post type, respectively.
3884 * Please note: When this action is hooked using a particular post status (like
3885 * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
3886 * first transitioned to that status from something else, as well as upon
3887 * subsequent post updates (old and new status are both the same).
3889 * Therefore, if you are looking to only fire a callback when a post is first
3890 * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
3894 * @param int $post_id Post ID.
3895 * @param WP_Post $post Post object.
3897 do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
3901 // Comment, trackback, and pingback functions.
3905 * Add a URL to those already pinged.
3909 * @global wpdb $wpdb WordPress database abstraction object.
3911 * @param int $post_id Post ID.
3912 * @param string $uri Ping URI.
3913 * @return int|false How many rows were updated.
3915 function add_ping( $post_id, $uri ) {
3917 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3918 $pung = trim($pung);
3919 $pung = preg_split('/\s/', $pung);
3921 $new = implode("\n", $pung);
3924 * Filters the new ping URL to add for the given post.
3928 * @param string $new New ping URL to add.
3930 $new = apply_filters( 'add_ping', $new );
3932 // expected_slashed ($new).
3933 $new = wp_unslash($new);
3934 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3938 * Retrieve enclosures already enclosed for a post.
3942 * @param int $post_id Post ID.
3943 * @return array List of enclosures.
3945 function get_enclosed( $post_id ) {
3946 $custom_fields = get_post_custom( $post_id );
3948 if ( !is_array( $custom_fields ) )
3951 foreach ( $custom_fields as $key => $val ) {
3952 if ( 'enclosure' != $key || !is_array( $val ) )
3954 foreach ( $val as $enc ) {
3955 $enclosure = explode( "\n", $enc );
3956 $pung[] = trim( $enclosure[ 0 ] );
3961 * Filters the list of enclosures already enclosed for the given post.
3965 * @param array $pung Array of enclosures for the given post.
3966 * @param int $post_id Post ID.
3968 return apply_filters( 'get_enclosed', $pung, $post_id );
3972 * Retrieve URLs already pinged for a post.
3976 * @global wpdb $wpdb WordPress database abstraction object.
3978 * @param int $post_id Post ID.
3981 function get_pung( $post_id ) {
3983 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3984 $pung = trim($pung);
3985 $pung = preg_split('/\s/', $pung);
3988 * Filters the list of already-pinged URLs for the given post.
3992 * @param array $pung Array of URLs already pinged for the given post.
3994 return apply_filters( 'get_pung', $pung );
3998 * Retrieve URLs that need to be pinged.
4002 * @global wpdb $wpdb WordPress database abstraction object.
4004 * @param int $post_id Post ID
4007 function get_to_ping( $post_id ) {
4009 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
4010 $to_ping = sanitize_trackback_urls( $to_ping );
4011 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
4014 * Filters the list of URLs yet to ping for the given post.
4018 * @param array $to_ping List of URLs yet to ping.
4020 return apply_filters( 'get_to_ping', $to_ping );
4024 * Do trackbacks for a list of URLs.
4028 * @param string $tb_list Comma separated list of URLs.
4029 * @param int $post_id Post ID.
4031 function trackback_url_list( $tb_list, $post_id ) {
4032 if ( ! empty( $tb_list ) ) {
4034 $postdata = get_post( $post_id, ARRAY_A );
4037 $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
4039 if ( strlen( $excerpt ) > 255 ) {
4040 $excerpt = substr( $excerpt, 0, 252 ) . '…';
4043 $trackback_urls = explode( ',', $tb_list );
4044 foreach ( (array) $trackback_urls as $tb_url ) {
4045 $tb_url = trim( $tb_url );
4046 trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
4056 * Get a list of page IDs.
4060 * @global wpdb $wpdb WordPress database abstraction object.
4062 * @return array List of page IDs.
4064 function get_all_page_ids() {
4067 $page_ids = wp_cache_get('all_page_ids', 'posts');
4068 if ( ! is_array( $page_ids ) ) {
4069 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
4070 wp_cache_add('all_page_ids', $page_ids, 'posts');
4077 * Retrieves page data given a page ID or page object.
4079 * Use get_post() instead of get_page().
4082 * @deprecated 3.5.0 Use get_post()
4084 * @param mixed $page Page object or page ID. Passed by reference.
4085 * @param string $output Optional. What to output. Accepts OBJECT, ARRAY_A, or ARRAY_N.
4087 * @param string $filter Optional. How the return value should be filtered. Accepts 'raw',
4088 * 'edit', 'db', 'display'. Default 'raw'.
4089 * @return WP_Post|array|null WP_Post on success or null on failure.
4091 function get_page( $page, $output = OBJECT, $filter = 'raw') {
4092 return get_post( $page, $output, $filter );
4096 * Retrieves a page given its path.
4100 * @global wpdb $wpdb WordPress database abstraction object.
4102 * @param string $page_path Page path.
4103 * @param string $output Optional. Output type. Accepts OBJECT, ARRAY_N, or ARRAY_A.
4105 * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4106 * @return WP_Post|array|void WP_Post on success.
4108 function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
4111 $last_changed = wp_cache_get( 'last_changed', 'posts' );
4112 if ( false === $last_changed ) {
4113 $last_changed = microtime();
4114 wp_cache_set( 'last_changed', $last_changed, 'posts' );
4117 $hash = md5( $page_path . serialize( $post_type ) );
4118 $cache_key = "get_page_by_path:$hash:$last_changed";
4119 $cached = wp_cache_get( $cache_key, 'posts' );
4120 if ( false !== $cached ) {
4121 // Special case: '0' is a bad `$page_path`.
4122 if ( '0' === $cached || 0 === $cached ) {
4125 return get_post( $cached, $output );
4129 $page_path = rawurlencode(urldecode($page_path));
4130 $page_path = str_replace('%2F', '/', $page_path);
4131 $page_path = str_replace('%20', ' ', $page_path);
4132 $parts = explode( '/', trim( $page_path, '/' ) );
4133 $parts = esc_sql( $parts );
4134 $parts = array_map( 'sanitize_title_for_query', $parts );
4136 $in_string = "'" . implode( "','", $parts ) . "'";
4138 if ( is_array( $post_type ) ) {
4139 $post_types = $post_type;
4141 $post_types = array( $post_type, 'attachment' );
4144 $post_types = esc_sql( $post_types );
4145 $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
4147 SELECT ID, post_name, post_parent, post_type
4149 WHERE post_name IN ($in_string)
4150 AND post_type IN ($post_type_in_string)
4153 $pages = $wpdb->get_results( $sql, OBJECT_K );
4155 $revparts = array_reverse( $parts );
4158 foreach ( (array) $pages as $page ) {
4159 if ( $page->post_name == $revparts[0] ) {
4164 * Loop through the given path parts from right to left,
4165 * ensuring each matches the post ancestry.
4167 while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
4169 $parent = $pages[ $p->post_parent ];
4170 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
4175 if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
4176 $foundid = $page->ID;
4177 if ( $page->post_type == $post_type )
4183 // We cache misses as well as hits.
4184 wp_cache_set( $cache_key, $foundid, 'posts' );
4187 return get_post( $foundid, $output );
4192 * Retrieve a page given its title.
4196 * @global wpdb $wpdb WordPress database abstraction object.
4198 * @param string $page_title Page title
4199 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
4201 * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4202 * @return WP_Post|array|void WP_Post on success or null on failure
4204 function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
4207 if ( is_array( $post_type ) ) {
4208 $post_type = esc_sql( $post_type );
4209 $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
4210 $sql = $wpdb->prepare( "
4213 WHERE post_title = %s
4214 AND post_type IN ($post_type_in_string)
4217 $sql = $wpdb->prepare( "
4220 WHERE post_title = %s
4222 ", $page_title, $post_type );
4225 $page = $wpdb->get_var( $sql );
4228 return get_post( $page, $output );
4233 * Identify descendants of a given page ID in a list of page objects.
4235 * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
4239 * @param int $page_id Page ID.
4240 * @param array $pages List of page objects from which descendants should be identified.
4241 * @return array List of page children.
4243 function get_page_children( $page_id, $pages ) {
4244 // Build a hash of ID -> children.
4245 $children = array();
4246 foreach ( (array) $pages as $page ) {
4247 $children[ intval( $page->post_parent ) ][] = $page;
4250 $page_list = array();
4252 // Start the search by looking at immediate children.
4253 if ( isset( $children[ $page_id ] ) ) {
4254 // Always start at the end of the stack in order to preserve original `$pages` order.
4255 $to_look = array_reverse( $children[ $page_id ] );
4257 while ( $to_look ) {
4258 $p = array_pop( $to_look );
4260 if ( isset( $children[ $p->ID ] ) ) {
4261 foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
4262 // Append to the `$to_look` stack to descend the tree.
4263 $to_look[] = $child;
4273 * Order the pages with children under parents in a flat list.
4275 * It uses auxiliary structure to hold parent-children relationships and
4276 * runs in O(N) complexity
4280 * @param array $pages Posts array, passed by reference.
4281 * @param int $page_id Optional. Parent page ID. Default 0.
4282 * @return array A list arranged by hierarchy. Children immediately follow their parents.
4284 function get_page_hierarchy( &$pages, $page_id = 0 ) {
4285 if ( empty( $pages ) ) {
4289 $children = array();
4290 foreach ( (array) $pages as $p ) {
4291 $parent_id = intval( $p->post_parent );
4292 $children[ $parent_id ][] = $p;
4296 _page_traverse_name( $page_id, $children, $result );
4302 * Traverse and return all the nested children post names of a root page.
4304 * $children contains parent-children relations
4308 * @see _page_traverse_name()
4310 * @param int $page_id Page ID.
4311 * @param array $children Parent-children relations, passed by reference.
4312 * @param array $result Result, passed by reference.
4314 function _page_traverse_name( $page_id, &$children, &$result ){
4315 if ( isset( $children[ $page_id ] ) ){
4316 foreach ( (array)$children[ $page_id ] as $child ) {
4317 $result[ $child->ID ] = $child->post_name;
4318 _page_traverse_name( $child->ID, $children, $result );
4324 * Build the URI path for a page.
4326 * Sub pages will be in the "directory" under the parent page post name.
4329 * @since 4.6.0 Converted the `$page` parameter to optional.
4331 * @param WP_Post|object|int $page Optional. Page ID or WP_Post object. Default is global $post.
4332 * @return string|false Page URI, false on error.
4334 function get_page_uri( $page = 0 ) {
4335 if ( ! $page instanceof WP_Post ) {
4336 $page = get_post( $page );
4342 $uri = $page->post_name;
4344 foreach ( $page->ancestors as $parent ) {
4345 $parent = get_post( $parent );
4346 if ( $parent && $parent->post_name ) {
4347 $uri = $parent->post_name . '/' . $uri;
4352 * Filters the URI for a page.
4356 * @param string $uri Page URI.
4357 * @param WP_Post $page Page object.
4359 return apply_filters( 'get_page_uri', $uri, $page );
4363 * Retrieve a list of pages.
4365 * @global wpdb $wpdb WordPress database abstraction object.
4369 * @param array|string $args {
4370 * Optional. Array or string of arguments to retrieve pages.
4372 * @type int $child_of Page ID to return child and grandchild pages of. Note: The value
4373 * of `$hierarchical` has no bearing on whether `$child_of` returns
4374 * hierarchical results. Default 0, or no restriction.
4375 * @type string $sort_order How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
4376 * @type string $sort_column What columns to sort pages by, comma-separated. Accepts 'post_author',
4377 * 'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
4378 * 'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
4379 * 'post_' can be omitted for any values that start with it.
4380 * Default 'post_title'.
4381 * @type bool $hierarchical Whether to return pages hierarchically. If false in conjunction with
4382 * `$child_of` also being false, both arguments will be disregarded.
4384 * @type array $exclude Array of page IDs to exclude. Default empty array.
4385 * @type array $include Array of page IDs to include. Cannot be used with `$child_of`,
4386 * `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
4387 * Default empty array.
4388 * @type string $meta_key Only include pages with this meta key. Default empty.
4389 * @type string $meta_value Only include pages with this meta value. Requires `$meta_key`.
4391 * @type string $authors A comma-separated list of author IDs. Default empty.
4392 * @type int $parent Page ID to return direct children of. Default -1, or no restriction.
4393 * @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude.
4394 * Default empty array.
4395 * @type int $number The number of pages to return. Default 0, or all pages.
4396 * @type int $offset The number of pages to skip before returning. Requires `$number`.
4398 * @type string $post_type The post type to query. Default 'page'.
4399 * @type string $post_status A comma-separated list of post status types to include.
4400 * Default 'publish'.
4402 * @return array|false List of pages matching defaults or `$args`.
4404 function get_pages( $args = array() ) {
4408 'child_of' => 0, 'sort_order' => 'ASC',
4409 'sort_column' => 'post_title', 'hierarchical' => 1,
4410 'exclude' => array(), 'include' => array(),
4411 'meta_key' => '', 'meta_value' => '',
4412 'authors' => '', 'parent' => -1, 'exclude_tree' => array(),
4413 'number' => '', 'offset' => 0,
4414 'post_type' => 'page', 'post_status' => 'publish',
4417 $r = wp_parse_args( $args, $defaults );
4419 $number = (int) $r['number'];
4420 $offset = (int) $r['offset'];
4421 $child_of = (int) $r['child_of'];
4422 $hierarchical = $r['hierarchical'];
4423 $exclude = $r['exclude'];
4424 $meta_key = $r['meta_key'];
4425 $meta_value = $r['meta_value'];
4426 $parent = $r['parent'];
4427 $post_status = $r['post_status'];
4429 // Make sure the post type is hierarchical.
4430 $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
4431 if ( ! in_array( $r['post_type'], $hierarchical_post_types ) ) {
4435 if ( $parent > 0 && ! $child_of ) {
4436 $hierarchical = false;
4439 // Make sure we have a valid post status.
4440 if ( ! is_array( $post_status ) ) {
4441 $post_status = explode( ',', $post_status );
4443 if ( array_diff( $post_status, get_post_stati() ) ) {
4447 // $args can be whatever, only use the args defined in defaults to compute the key.
4448 $key = md5( serialize( wp_array_slice_assoc( $r, array_keys( $defaults ) ) ) );
4449 $last_changed = wp_cache_get( 'last_changed', 'posts' );
4450 if ( ! $last_changed ) {
4451 $last_changed = microtime();
4452 wp_cache_set( 'last_changed', $last_changed, 'posts' );
4455 $cache_key = "get_pages:$key:$last_changed";
4456 if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
4457 // Convert to WP_Post instances.
4458 $pages = array_map( 'get_post', $cache );
4459 /** This filter is documented in wp-includes/post.php */
4460 $pages = apply_filters( 'get_pages', $pages, $r );
4465 if ( ! empty( $r['include'] ) ) {
4466 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
4471 $hierarchical = false;
4472 $incpages = wp_parse_id_list( $r['include'] );
4473 if ( ! empty( $incpages ) ) {
4474 $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
4479 if ( ! empty( $exclude ) ) {
4480 $expages = wp_parse_id_list( $exclude );
4481 if ( ! empty( $expages ) ) {
4482 $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
4487 if ( ! empty( $r['authors'] ) ) {
4488 $post_authors = preg_split( '/[\s,]+/', $r['authors'] );
4490 if ( ! empty( $post_authors ) ) {
4491 foreach ( $post_authors as $post_author ) {
4492 //Do we have an author id or an author login?
4493 if ( 0 == intval($post_author) ) {
4494 $post_author = get_user_by('login', $post_author);
4495 if ( empty( $post_author ) ) {
4498 if ( empty( $post_author->ID ) ) {
4501 $post_author = $post_author->ID;
4504 if ( '' == $author_query ) {
4505 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
4507 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
4510 if ( '' != $author_query ) {
4511 $author_query = " AND ($author_query)";
4517 $where = "$exclusions $inclusions ";
4518 if ( '' !== $meta_key || '' !== $meta_value ) {
4519 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
4521 // meta_key and meta_value might be slashed
4522 $meta_key = wp_unslash($meta_key);
4523 $meta_value = wp_unslash($meta_value);
4524 if ( '' !== $meta_key ) {
4525 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
4527 if ( '' !== $meta_value ) {
4528 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
4533 if ( is_array( $parent ) ) {
4534 $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
4535 if ( ! empty( $post_parent__in ) ) {
4536 $where .= " AND post_parent IN ($post_parent__in)";
4538 } elseif ( $parent >= 0 ) {
4539 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
4542 if ( 1 == count( $post_status ) ) {
4543 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $r['post_type'], reset( $post_status ) );
4545 $post_status = implode( "', '", $post_status );
4546 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $r['post_type'] );
4549 $orderby_array = array();
4550 $allowed_keys = array( 'author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
4551 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
4552 'ID', 'rand', 'comment_count' );
4554 foreach ( explode( ',', $r['sort_column'] ) as $orderby ) {
4555 $orderby = trim( $orderby );
4556 if ( ! in_array( $orderby, $allowed_keys ) ) {
4560 switch ( $orderby ) {
4564 $orderby = "$wpdb->posts.ID";
4567 $orderby = 'RAND()';
4569 case 'comment_count':
4570 $orderby = "$wpdb->posts.comment_count";
4573 if ( 0 === strpos( $orderby, 'post_' ) ) {
4574 $orderby = "$wpdb->posts." . $orderby;
4576 $orderby = "$wpdb->posts.post_" . $orderby;
4580 $orderby_array[] = $orderby;
4583 $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
4585 $sort_order = strtoupper( $r['sort_order'] );
4586 if ( '' !== $sort_order && ! in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) {
4587 $sort_order = 'ASC';
4590 $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
4591 $query .= $author_query;
4592 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
4594 if ( ! empty( $number ) ) {
4595 $query .= ' LIMIT ' . $offset . ',' . $number;
4598 $pages = $wpdb->get_results($query);
4600 if ( empty($pages) ) {
4601 /** This filter is documented in wp-includes/post.php */
4602 $pages = apply_filters( 'get_pages', array(), $r );
4606 // Sanitize before caching so it'll only get done once.
4607 $num_pages = count($pages);
4608 for ($i = 0; $i < $num_pages; $i++) {
4609 $pages[$i] = sanitize_post($pages[$i], 'raw');
4613 update_post_cache( $pages );
4615 if ( $child_of || $hierarchical ) {
4616 $pages = get_page_children($child_of, $pages);
4619 if ( ! empty( $r['exclude_tree'] ) ) {
4620 $exclude = wp_parse_id_list( $r['exclude_tree'] );
4621 foreach ( $exclude as $id ) {
4622 $children = get_page_children( $id, $pages );
4623 foreach ( $children as $child ) {
4624 $exclude[] = $child->ID;
4628 $num_pages = count( $pages );
4629 for ( $i = 0; $i < $num_pages; $i++ ) {
4630 if ( in_array( $pages[$i]->ID, $exclude ) ) {
4631 unset( $pages[$i] );
4636 $page_structure = array();
4637 foreach ( $pages as $page ) {
4638 $page_structure[] = $page->ID;
4641 wp_cache_set( $cache_key, $page_structure, 'posts' );
4643 // Convert to WP_Post instances
4644 $pages = array_map( 'get_post', $pages );
4647 * Filters the retrieved list of pages.
4651 * @param array $pages List of pages to retrieve.
4652 * @param array $r Array of get_pages() arguments.
4654 return apply_filters( 'get_pages', $pages, $r );
4658 // Attachment functions
4662 * Check if the attachment URI is local one and is really an attachment.
4666 * @param string $url URL to check
4667 * @return bool True on success, false on failure.
4669 function is_local_attachment($url) {
4670 if (strpos($url, home_url()) === false)
4672 if (strpos($url, home_url('/?attachment_id=')) !== false)
4674 if ( $id = url_to_postid($url) ) {
4675 $post = get_post($id);
4676 if ( 'attachment' == $post->post_type )
4683 * Insert an attachment.
4685 * If you set the 'ID' in the $args parameter, it will mean that you are
4686 * updating and attempt to update the attachment. You can also set the
4687 * attachment name or title by setting the key 'post_name' or 'post_title'.
4689 * You can set the dates for the attachment manually by setting the 'post_date'
4690 * and 'post_date_gmt' keys' values.
4692 * By default, the comments will use the default settings for whether the
4693 * comments are allowed. You can close them manually or keep them open by
4694 * setting the value for the 'comment_status' key.
4698 * @see wp_insert_post()
4700 * @param string|array $args Arguments for inserting an attachment.
4701 * @param string $file Optional. Filename.
4702 * @param int $parent Optional. Parent post ID.
4703 * @return int Attachment ID.
4705 function wp_insert_attachment( $args, $file = false, $parent = 0 ) {
4711 $data = wp_parse_args( $args, $defaults );
4713 if ( ! empty( $parent ) ) {
4714 $data['post_parent'] = $parent;
4717 $data['post_type'] = 'attachment';
4719 return wp_insert_post( $data );
4723 * Trash or delete an attachment.
4725 * When an attachment is permanently deleted, the file will also be removed.
4726 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4727 * with the attachment (except the main post).
4729 * The attachment is moved to the trash instead of permanently deleted unless trash
4730 * for media is disabled, item is already in the trash, or $force_delete is true.
4734 * @global wpdb $wpdb WordPress database abstraction object.
4736 * @param int $post_id Attachment ID.
4737 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
4739 * @return mixed False on failure. Post data on success.
4741 function wp_delete_attachment( $post_id, $force_delete = false ) {
4744 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4747 if ( 'attachment' != $post->post_type )
4750 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4751 return wp_trash_post( $post_id );
4753 delete_post_meta($post_id, '_wp_trash_meta_status');
4754 delete_post_meta($post_id, '_wp_trash_meta_time');
4756 $meta = wp_get_attachment_metadata( $post_id );
4757 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4758 $file = get_attached_file( $post_id );
4760 if ( is_multisite() )
4761 delete_transient( 'dirsize_cache' );
4764 * Fires before an attachment is deleted, at the start of wp_delete_attachment().
4768 * @param int $post_id Attachment ID.
4770 do_action( 'delete_attachment', $post_id );
4772 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4773 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4775 // Delete all for any posts.
4776 delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
4778 wp_defer_comment_counting( true );
4780 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4781 foreach ( $comment_ids as $comment_id ) {
4782 wp_delete_comment( $comment_id, true );
4785 wp_defer_comment_counting( false );
4787 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4788 foreach ( $post_meta_ids as $mid )
4789 delete_metadata_by_mid( 'post', $mid );
4791 /** This action is documented in wp-includes/post.php */
4792 do_action( 'delete_post', $post_id );
4793 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4797 /** This action is documented in wp-includes/post.php */
4798 do_action( 'deleted_post', $post_id );
4800 $uploadpath = wp_get_upload_dir();
4802 if ( ! empty($meta['thumb']) ) {
4803 // Don't delete the thumb if another attachment uses it.
4804 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)) ) {
4805 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4806 /** This filter is documented in wp-includes/functions.php */
4807 $thumbfile = apply_filters( 'wp_delete_file', $thumbfile );
4808 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4812 // Remove intermediate and backup images if there are any.
4813 if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
4814 foreach ( $meta['sizes'] as $size => $sizeinfo ) {
4815 $intermediate_file = str_replace( basename( $file ), $sizeinfo['file'], $file );
4816 /** This filter is documented in wp-includes/functions.php */
4817 $intermediate_file = apply_filters( 'wp_delete_file', $intermediate_file );
4818 @ unlink( path_join( $uploadpath['basedir'], $intermediate_file ) );
4822 if ( is_array($backup_sizes) ) {
4823 foreach ( $backup_sizes as $size ) {
4824 $del_file = path_join( dirname($meta['file']), $size['file'] );
4825 /** This filter is documented in wp-includes/functions.php */
4826 $del_file = apply_filters( 'wp_delete_file', $del_file );
4827 @ unlink( path_join($uploadpath['basedir'], $del_file) );
4831 wp_delete_file( $file );
4833 clean_post_cache( $post );
4839 * Retrieve attachment meta field for attachment ID.
4843 * @param int $post_id Attachment ID. Default 0.
4844 * @param bool $unfiltered Optional. If true, filters are not run. Default false.
4845 * @return mixed Attachment meta field. False on failure.
4847 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4848 $post_id = (int) $post_id;
4849 if ( !$post = get_post( $post_id ) )
4852 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4858 * Filters the attachment meta data.
4862 * @param array|bool $data Array of meta data for the given attachment, or false
4863 * if the object does not exist.
4864 * @param int $post_id Attachment ID.
4866 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4870 * Update metadata for an attachment.
4874 * @param int $post_id Attachment ID.
4875 * @param array $data Attachment data.
4876 * @return int|bool False if $post is invalid.
4878 function wp_update_attachment_metadata( $post_id, $data ) {
4879 $post_id = (int) $post_id;
4880 if ( !$post = get_post( $post_id ) )
4884 * Filters the updated attachment meta data.
4888 * @param array $data Array of updated attachment meta data.
4889 * @param int $post_id Attachment ID.
4891 if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4892 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4894 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4898 * Retrieve the URL for an attachment.
4902 * @global string $pagenow
4904 * @param int $post_id Optional. Attachment ID. Default 0.
4905 * @return string|false Attachment URL, otherwise false.
4907 function wp_get_attachment_url( $post_id = 0 ) {
4908 $post_id = (int) $post_id;
4909 if ( !$post = get_post( $post_id ) )
4912 if ( 'attachment' != $post->post_type )
4916 // Get attached file.
4917 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true ) ) {
4918 // Get upload directory.
4919 if ( ( $uploads = wp_get_upload_dir() ) && false === $uploads['error'] ) {
4920 // Check that the upload base exists in the file location.
4921 if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
4922 // Replace file location with url location.
4923 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
4924 } elseif ( false !== strpos($file, 'wp-content/uploads') ) {
4925 // Get the directory name relative to the basedir (back compat for pre-2.7 uploads)
4926 $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . basename( $file );
4928 // It's a newly-uploaded file, therefore $file is relative to the basedir.
4929 $url = $uploads['baseurl'] . "/$file";
4935 * If any of the above options failed, Fallback on the GUID as used pre-2.7,
4936 * not recommended to rely upon this.
4938 if ( empty($url) ) {
4939 $url = get_the_guid( $post->ID );
4942 // On SSL front end, URLs should be HTTPS.
4943 if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) {
4944 $url = set_url_scheme( $url );
4948 * Filters the attachment URL.
4952 * @param string $url URL for the given attachment.
4953 * @param int $post_id Attachment ID.
4955 $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4957 if ( empty( $url ) )
4964 * Retrieves the caption for an attachment.
4968 * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
4969 * @return string|false False on failure. Attachment caption on success.
4971 function wp_get_attachment_caption( $post_id = 0 ) {
4972 $post_id = (int) $post_id;
4973 if ( ! $post = get_post( $post_id ) ) {
4977 if ( 'attachment' !== $post->post_type ) {
4981 $caption = $post->post_excerpt;
4984 * Filters the attachment caption.
4988 * @param string $caption Caption for the given attachment.
4989 * @param int $post_id Attachment ID.
4991 return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
4995 * Retrieve thumbnail for an attachment.
4999 * @param int $post_id Optional. Attachment ID. Default 0.
5000 * @return string|false False on failure. Thumbnail file path on success.
5002 function wp_get_attachment_thumb_file( $post_id = 0 ) {
5003 $post_id = (int) $post_id;
5004 if ( !$post = get_post( $post_id ) )
5006 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
5009 $file = get_attached_file( $post->ID );
5011 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) {
5013 * Filters the attachment thumbnail file path.
5017 * @param string $thumbfile File path to the attachment thumbnail.
5018 * @param int $post_id Attachment ID.
5020 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
5026 * Retrieve URL for an attachment thumbnail.
5030 * @param int $post_id Optional. Attachment ID. Default 0.
5031 * @return string|false False on failure. Thumbnail URL on success.
5033 function wp_get_attachment_thumb_url( $post_id = 0 ) {
5034 $post_id = (int) $post_id;
5035 if ( !$post = get_post( $post_id ) )
5037 if ( !$url = wp_get_attachment_url( $post->ID ) )
5040 $sized = image_downsize( $post_id, 'thumbnail' );
5044 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
5047 $url = str_replace(basename($url), basename($thumb), $url);
5050 * Filters the attachment thumbnail URL.
5054 * @param string $url URL for the attachment thumbnail.
5055 * @param int $post_id Attachment ID.
5057 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
5061 * Verifies an attachment is of a given type.
5065 * @param string $type Attachment type. Accepts 'image', 'audio', or 'video'.
5066 * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
5067 * @return bool True if one of the accepted types, false otherwise.
5069 function wp_attachment_is( $type, $post = null ) {
5070 if ( ! $post = get_post( $post ) ) {
5074 if ( ! $file = get_attached_file( $post->ID ) ) {
5078 if ( 0 === strpos( $post->post_mime_type, $type . '/' ) ) {
5082 $check = wp_check_filetype( $file );
5083 if ( empty( $check['ext'] ) ) {
5087 $ext = $check['ext'];
5089 if ( 'import' !== $post->post_mime_type ) {
5090 return $type === $ext;
5095 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
5096 return in_array( $ext, $image_exts );
5099 return in_array( $ext, wp_get_audio_extensions() );
5102 return in_array( $ext, wp_get_video_extensions() );
5105 return $type === $ext;
5110 * Checks if the attachment is an image.
5113 * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
5114 * allowed WP_Post object to be passed.
5116 * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
5117 * @return bool Whether the attachment is an image.
5119 function wp_attachment_is_image( $post = null ) {
5120 return wp_attachment_is( 'image', $post );
5124 * Retrieve the icon for a MIME type.
5128 * @param string|int $mime MIME type or attachment ID.
5129 * @return string|false Icon, false otherwise.
5131 function wp_mime_type_icon( $mime = 0 ) {
5132 if ( !is_numeric($mime) )
5133 $icon = wp_cache_get("mime_type_icon_$mime");
5136 if ( empty($icon) ) {
5137 $post_mimes = array();
5138 if ( is_numeric($mime) ) {
5139 $mime = (int) $mime;
5140 if ( $post = get_post( $mime ) ) {
5141 $post_id = (int) $post->ID;
5142 $file = get_attached_file( $post_id );
5143 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $file);
5144 if ( !empty($ext) ) {
5145 $post_mimes[] = $ext;
5146 if ( $ext_type = wp_ext2type( $ext ) )
5147 $post_mimes[] = $ext_type;
5149 $mime = $post->post_mime_type;
5154 $post_mimes[] = $mime;
5157 $icon_files = wp_cache_get('icon_files');
5159 if ( !is_array($icon_files) ) {
5161 * Filters the icon directory path.
5165 * @param string $path Icon directory absolute path.
5167 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
5170 * Filters the icon directory URI.
5174 * @param string $uri Icon directory URI.
5176 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
5179 * Filters the list of icon directory URIs.
5183 * @param array $uris List of icon directory URIs.
5185 $dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
5186 $icon_files = array();
5188 $keys = array_keys( $dirs );
5189 $dir = array_shift( $keys );
5190 $uri = array_shift($dirs);
5191 if ( $dh = opendir($dir) ) {
5192 while ( false !== $file = readdir($dh) ) {
5193 $file = basename($file);
5194 if ( substr($file, 0, 1) == '.' )
5196 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
5197 if ( is_dir("$dir/$file") )
5198 $dirs["$dir/$file"] = "$uri/$file";
5201 $icon_files["$dir/$file"] = "$uri/$file";
5206 wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
5210 // Icon basename - extension = MIME wildcard.
5211 foreach ( $icon_files as $file => $uri )
5212 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
5214 if ( ! empty($mime) ) {
5215 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
5216 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
5217 $post_mimes[] = str_replace('/', '_', $mime);
5220 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
5221 $matches['default'] = array('default');
5223 foreach ( $matches as $match => $wilds ) {
5224 foreach ( $wilds as $wild ) {
5225 if ( ! isset( $types[ $wild ] ) ) {
5229 $icon = $types[ $wild ];
5230 if ( ! is_numeric( $mime ) ) {
5231 wp_cache_add( "mime_type_icon_$mime", $icon );
5239 * Filters the mime type icon.
5243 * @param string $icon Path to the mime type icon.
5244 * @param string $mime Mime type.
5245 * @param int $post_id Attachment ID. Will equal 0 if the function passed
5248 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
5252 * Check for changed slugs for published post objects and save the old slug.
5254 * The function is used when a post object of any type is updated,
5255 * by comparing the current and previous post objects.
5257 * If the slug was changed and not already part of the old slugs then it will be
5258 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
5261 * The most logically usage of this function is redirecting changed post objects, so
5262 * that those that linked to an changed post will be redirected to the new post.
5266 * @param int $post_id Post ID.
5267 * @param WP_Post $post The Post Object
5268 * @param WP_Post $post_before The Previous Post Object
5270 function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
5271 // Don't bother if it hasn't changed.
5272 if ( $post->post_name == $post_before->post_name ) {
5276 // We're only concerned with published, non-hierarchical objects.
5277 if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
5281 $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
5283 // If we haven't added this old slug before, add it now.
5284 if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs ) ) {
5285 add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
5288 // If the new slug was used previously, delete it from the list.
5289 if ( in_array( $post->post_name, $old_slugs ) ) {
5290 delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
5295 * Retrieve the private post SQL based on capability.
5297 * This function provides a standardized way to appropriately select on the
5298 * post_status of a post type. The function will return a piece of SQL code
5299 * that can be added to a WHERE clause; this SQL is constructed to allow all
5300 * published posts, and all private posts to which the user has access.
5303 * @since 4.3.0 Added the ability to pass an array to `$post_type`.
5305 * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
5306 * @return string SQL code that can be added to a where clause.
5308 function get_private_posts_cap_sql( $post_type ) {
5309 return get_posts_by_author_sql( $post_type, false );
5313 * Retrieve the post SQL based on capability, author, and type.
5316 * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
5318 * @see get_private_posts_cap_sql()
5319 * @global wpdb $wpdb WordPress database abstraction object.
5321 * @param array|string $post_type Single post type or an array of post types.
5322 * @param bool $full Optional. Returns a full WHERE statement instead of just
5323 * an 'andalso' term. Default true.
5324 * @param int $post_author Optional. Query posts having a single author ID. Default null.
5325 * @param bool $public_only Optional. Only return public posts. Skips cap checks for
5326 * $current_user. Default false.
5327 * @return string SQL WHERE code that can be added to a query.
5329 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
5332 if ( is_array( $post_type ) ) {
5333 $post_types = $post_type;
5335 $post_types = array( $post_type );
5338 $post_type_clauses = array();
5339 foreach ( $post_types as $post_type ) {
5340 $post_type_obj = get_post_type_object( $post_type );
5341 if ( ! $post_type_obj ) {
5346 * Filters the capability to read private posts for a custom post type
5347 * when generating SQL for getting posts by author.
5350 * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
5352 * @param string $cap Capability.
5354 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
5355 $cap = current_user_can( $post_type_obj->cap->read_private_posts );
5358 // Only need to check the cap if $public_only is false.
5359 $post_status_sql = "post_status = 'publish'";
5360 if ( false === $public_only ) {
5362 // Does the user have the capability to view private posts? Guess so.
5363 $post_status_sql .= " OR post_status = 'private'";
5364 } elseif ( is_user_logged_in() ) {
5365 // Users can view their own private posts.
5366 $id = get_current_user_id();
5367 if ( null === $post_author || ! $full ) {
5368 $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
5369 } elseif ( $id == (int) $post_author ) {
5370 $post_status_sql .= " OR post_status = 'private'";
5375 $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
5378 if ( empty( $post_type_clauses ) ) {
5379 return $full ? 'WHERE 1 = 0' : '1 = 0';
5382 $sql = '( '. implode( ' OR ', $post_type_clauses ) . ' )';
5384 if ( null !== $post_author ) {
5385 $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
5389 $sql = 'WHERE ' . $sql;
5396 * Retrieve the date that the last post was published.
5398 * The server timezone is the default and is the difference between GMT and
5399 * server time. The 'blog' value is the date when the last post was posted. The
5400 * 'gmt' is when the last post was posted in GMT formatted date.
5403 * @since 4.4.0 The `$post_type` argument was added.
5405 * @param string $timezone Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
5406 * 'server' uses the server's internal timezone.
5407 * 'blog' uses the `post_modified` field, which proxies to the timezone set for the site.
5408 * 'gmt' uses the `post_modified_gmt` field.
5410 * @param string $post_type Optional. The post type to check. Default 'any'.
5411 * @return string The date of the last post.
5413 function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
5415 * Filters the date the last post was published.
5419 * @param string $date Date the last post was published.
5420 * @param string $timezone Location to use for getting the post published date.
5421 * See get_lastpostdate() for accepted `$timezone` values.
5423 return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date', $post_type ), $timezone );
5427 * Get the timestamp of the last time any post was modified.
5429 * The server timezone is the default and is the difference between GMT and
5430 * server time. The 'blog' value is just when the last post was modified. The
5431 * 'gmt' is when the last post was modified in GMT time.
5434 * @since 4.4.0 The `$post_type` argument was added.
5436 * @param string $timezone Optional. The timezone for the timestamp. See get_lastpostdate()
5437 * for information on accepted values.
5439 * @param string $post_type Optional. The post type to check. Default 'any'.
5440 * @return string The timestamp.
5442 function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
5444 * Pre-filter the return value of get_lastpostmodified() before the query is run.
5448 * @param string $lastpostmodified Date the last post was modified.
5449 * Returning anything other than false will short-circuit the function.
5450 * @param string $timezone Location to use for getting the post modified date.
5451 * See get_lastpostdate() for accepted `$timezone` values.
5452 * @param string $post_type The post type to check.
5454 $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
5455 if ( false !== $lastpostmodified ) {
5456 return $lastpostmodified;
5459 $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
5461 $lastpostdate = get_lastpostdate($timezone);
5462 if ( $lastpostdate > $lastpostmodified ) {
5463 $lastpostmodified = $lastpostdate;
5467 * Filters the date the last post was modified.
5471 * @param string $lastpostmodified Date the last post was modified.
5472 * @param string $timezone Location to use for getting the post modified date.
5473 * See get_lastpostdate() for accepted `$timezone` values.
5475 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
5479 * Get the timestamp of the last time any post was modified or published.
5482 * @since 4.4.0 The `$post_type` argument was added.
5485 * @global wpdb $wpdb WordPress database abstraction object.
5487 * @param string $timezone The timezone for the timestamp. See get_lastpostdate().
5488 * for information on accepted values.
5489 * @param string $field Post field to check. Accepts 'date' or 'modified'.
5490 * @param string $post_type Optional. The post type to check. Default 'any'.
5491 * @return string|false The timestamp.
5493 function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
5496 if ( ! in_array( $field, array( 'date', 'modified' ) ) ) {
5500 $timezone = strtolower( $timezone );
5502 $key = "lastpost{$field}:$timezone";
5503 if ( 'any' !== $post_type ) {
5504 $key .= ':' . sanitize_key( $post_type );
5507 $date = wp_cache_get( $key, 'timeinfo' );
5510 if ( 'any' === $post_type ) {
5511 $post_types = get_post_types( array( 'public' => true ) );
5512 array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
5513 $post_types = "'" . implode( "', '", $post_types ) . "'";
5515 $post_types = "'" . sanitize_key( $post_type ) . "'";
5518 switch ( $timezone ) {
5520 $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");
5523 $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");
5526 $add_seconds_server = date( 'Z' );
5527 $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");
5532 wp_cache_set( $key, $date, 'timeinfo' );
5540 * Updates posts in cache.
5544 * @param array $posts Array of post objects, passed by reference.
5546 function update_post_cache( &$posts ) {
5550 foreach ( $posts as $post )
5551 wp_cache_add( $post->ID, $post, 'posts' );
5555 * Will clean the post in the cache.
5557 * Cleaning means delete from the cache of the post. Will call to clean the term
5558 * object cache associated with the post ID.
5560 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
5561 * wp_suspend_cache_invalidation().
5565 * @global bool $_wp_suspend_cache_invalidation
5567 * @param int|WP_Post $post Post ID or post object to remove from the cache.
5569 function clean_post_cache( $post ) {
5570 global $_wp_suspend_cache_invalidation;
5572 if ( ! empty( $_wp_suspend_cache_invalidation ) )
5575 $post = get_post( $post );
5576 if ( empty( $post ) )
5579 wp_cache_delete( $post->ID, 'posts' );
5580 wp_cache_delete( $post->ID, 'post_meta' );
5582 clean_object_term_cache( $post->ID, $post->post_type );
5584 wp_cache_delete( 'wp_get_archives', 'general' );
5587 * Fires immediately after the given post's cache is cleaned.
5591 * @param int $post_id Post ID.
5592 * @param WP_Post $post Post object.
5594 do_action( 'clean_post_cache', $post->ID, $post );
5596 if ( 'page' == $post->post_type ) {
5597 wp_cache_delete( 'all_page_ids', 'posts' );
5600 * Fires immediately after the given page's cache is cleaned.
5604 * @param int $post_id Post ID.
5606 do_action( 'clean_page_cache', $post->ID );
5609 wp_cache_set( 'last_changed', microtime(), 'posts' );
5613 * Call major cache updating functions for list of Post objects.
5617 * @param array $posts Array of Post objects
5618 * @param string $post_type Optional. Post type. Default 'post'.
5619 * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
5620 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
5622 function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
5623 // No point in doing all this work if we didn't match any posts.
5627 update_post_cache($posts);
5629 $post_ids = array();
5630 foreach ( $posts as $post )
5631 $post_ids[] = $post->ID;
5636 if ( $update_term_cache ) {
5637 if ( is_array($post_type) ) {
5638 $ptypes = $post_type;
5639 } elseif ( 'any' == $post_type ) {
5641 // Just use the post_types in the supplied posts.
5642 foreach ( $posts as $post ) {
5643 $ptypes[] = $post->post_type;
5645 $ptypes = array_unique($ptypes);
5647 $ptypes = array($post_type);
5650 if ( ! empty($ptypes) )
5651 update_object_term_cache($post_ids, $ptypes);
5654 if ( $update_meta_cache )
5655 update_postmeta_cache($post_ids);
5659 * Updates metadata cache for list of post IDs.
5661 * Performs SQL query to retrieve the metadata for the post IDs and updates the
5662 * metadata cache for the posts. Therefore, the functions, which call this
5663 * function, do not need to perform SQL queries on their own.
5667 * @param array $post_ids List of post IDs.
5668 * @return array|false Returns false if there is nothing to update or an array
5671 function update_postmeta_cache( $post_ids ) {
5672 return update_meta_cache('post', $post_ids);
5676 * Will clean the attachment in the cache.
5678 * Cleaning means delete from the cache. Optionally will clean the term
5679 * object cache associated with the attachment ID.
5681 * This function will not run if $_wp_suspend_cache_invalidation is not empty.
5685 * @global bool $_wp_suspend_cache_invalidation
5687 * @param int $id The attachment ID in the cache to clean.
5688 * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
5690 function clean_attachment_cache( $id, $clean_terms = false ) {
5691 global $_wp_suspend_cache_invalidation;
5693 if ( !empty($_wp_suspend_cache_invalidation) )
5698 wp_cache_delete($id, 'posts');
5699 wp_cache_delete($id, 'post_meta');
5702 clean_object_term_cache($id, 'attachment');
5705 * Fires after the given attachment's cache is cleaned.
5709 * @param int $id Attachment ID.
5711 do_action( 'clean_attachment_cache', $id );
5719 * Hook for managing future post transitions to published.
5724 * @see wp_clear_scheduled_hook()
5725 * @global wpdb $wpdb WordPress database abstraction object.
5727 * @param string $new_status New post status.
5728 * @param string $old_status Previous post status.
5729 * @param WP_Post $post Post object.
5731 function _transition_post_status( $new_status, $old_status, $post ) {
5734 if ( $old_status != 'publish' && $new_status == 'publish' ) {
5735 // Reset GUID if transitioning to publish and it is empty.
5736 if ( '' == get_the_guid($post->ID) )
5737 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
5740 * Fires when a post's status is transitioned from private to published.
5743 * @deprecated 2.3.0 Use 'private_to_publish' instead.
5745 * @param int $post_id Post ID.
5747 do_action('private_to_published', $post->ID);
5750 // If published posts changed clear the lastpostmodified cache.
5751 if ( 'publish' == $new_status || 'publish' == $old_status) {
5752 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
5753 wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
5754 wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
5755 wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
5759 if ( $new_status !== $old_status ) {
5760 wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
5761 wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
5764 // Always clears the hook in case the post status bounced from future to draft.
5765 wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
5769 * Hook used to schedule publication for a post marked for the future.
5771 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
5776 * @param int $deprecated Not used. Can be set to null. Never implemented. Not marked
5777 * as deprecated with _deprecated_argument() as it conflicts with
5778 * wp_transition_post_status() and the default filter for _future_post_hook().
5779 * @param WP_Post $post Post object.
5781 function _future_post_hook( $deprecated, $post ) {
5782 wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
5783 wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
5787 * Hook to schedule pings and enclosures when a post is published.
5789 * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
5794 * @param int $post_id The ID in the database table of the post being published.
5796 function _publish_post_hook( $post_id ) {
5797 if ( defined( 'XMLRPC_REQUEST' ) ) {
5799 * Fires when _publish_post_hook() is called during an XML-RPC request.
5803 * @param int $post_id Post ID.
5805 do_action( 'xmlrpc_publish_post', $post_id );
5808 if ( defined('WP_IMPORTING') )
5811 if ( get_option('default_pingback_flag') )
5812 add_post_meta( $post_id, '_pingme', '1' );
5813 add_post_meta( $post_id, '_encloseme', '1' );
5815 wp_schedule_single_event(time(), 'do_pings');
5819 * Return the post's parent's post_ID
5823 * @param int $post_ID
5825 * @return int|false Post parent ID, otherwise false.
5827 function wp_get_post_parent_id( $post_ID ) {
5828 $post = get_post( $post_ID );
5829 if ( !$post || is_wp_error( $post ) )
5831 return (int) $post->post_parent;
5835 * Check the given subset of the post hierarchy for hierarchy loops.
5837 * Prevents loops from forming and breaks those that it finds. Attached
5838 * to the {@see 'wp_insert_post_parent'} filter.
5842 * @see wp_find_hierarchy_loop()
5844 * @param int $post_parent ID of the parent for the post we're checking.
5845 * @param int $post_ID ID of the post we're checking.
5846 * @return int The new post_parent for the post, 0 otherwise.
5848 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
5849 // Nothing fancy here - bail.
5850 if ( !$post_parent )
5853 // New post can't cause a loop.
5854 if ( empty( $post_ID ) )
5855 return $post_parent;
5857 // Can't be its own parent.
5858 if ( $post_parent == $post_ID )
5861 // Now look for larger loops.
5862 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
5863 return $post_parent; // No loop
5865 // Setting $post_parent to the given value causes a loop.
5866 if ( isset( $loop[$post_ID] ) )
5869 // There's a loop, but it doesn't contain $post_ID. Break the loop.
5870 foreach ( array_keys( $loop ) as $loop_member )
5871 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
5873 return $post_parent;
5877 * Set a post thumbnail.
5881 * @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
5882 * @param int $thumbnail_id Thumbnail to attach.
5883 * @return int|bool True on success, false on failure.
5885 function set_post_thumbnail( $post, $thumbnail_id ) {
5886 $post = get_post( $post );
5887 $thumbnail_id = absint( $thumbnail_id );
5888 if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
5889 if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
5890 return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
5892 return delete_post_meta( $post->ID, '_thumbnail_id' );
5898 * Remove a post thumbnail.
5902 * @param int|WP_Post $post Post ID or post object where thumbnail should be removed from.
5903 * @return bool True on success, false on failure.
5905 function delete_post_thumbnail( $post ) {
5906 $post = get_post( $post );
5908 return delete_post_meta( $post->ID, '_thumbnail_id' );
5913 * Delete auto-drafts for new posts that are > 7 days old.
5917 * @global wpdb $wpdb WordPress database abstraction object.
5919 function wp_delete_auto_drafts() {
5922 // Cleanup old auto-drafts more than 7 days old.
5923 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
5924 foreach ( (array) $old_posts as $delete ) {
5926 wp_delete_post( $delete, true );
5931 * Queues posts for lazy-loading of term meta.
5935 * @param array $posts Array of WP_Post objects.
5937 function wp_queue_posts_for_term_meta_lazyload( $posts ) {
5938 $post_type_taxonomies = $term_ids = array();
5939 foreach ( $posts as $post ) {
5940 if ( ! ( $post instanceof WP_Post ) ) {
5944 if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
5945 $post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
5948 foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
5949 // Term cache should already be primed by `update_post_term_cache()`.
5950 $terms = get_object_term_cache( $post->ID, $taxonomy );
5951 if ( false !== $terms ) {
5952 foreach ( $terms as $term ) {
5953 if ( ! isset( $term_ids[ $term->term_id ] ) ) {
5954 $term_ids[] = $term->term_id;
5962 $lazyloader = wp_metadata_lazyloader();
5963 $lazyloader->queue_objects( 'term', $term_ids );
5968 * Update the custom taxonomies' term counts when a post's status is changed.
5970 * For example, default posts term counts (for custom taxonomies) don't include
5971 * private / draft posts.
5976 * @param string $new_status New post status.
5977 * @param string $old_status Old post status.
5978 * @param WP_Post $post Post object.
5980 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
5981 // Update counts for the post's terms.
5982 foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
5983 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
5984 wp_update_term_count( $tt_ids, $taxonomy );
5989 * Adds any posts from the given ids to the cache that do not already exist in cache
5994 * @see update_post_caches()
5996 * @global wpdb $wpdb WordPress database abstraction object.
5998 * @param array $ids ID list.
5999 * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
6000 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
6002 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
6005 $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
6006 if ( !empty( $non_cached_ids ) ) {
6007 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
6009 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
6014 * Adds a suffix if any trashed posts have a given slug.
6016 * Store its desired (i.e. current) slug so it can try to reclaim it
6017 * if the post is untrashed.
6024 * @param string $post_name Slug.
6025 * @param string $post_ID Optional. Post ID that should be ignored. Default 0.
6027 function wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID = 0 ) {
6028 $trashed_posts_with_desired_slug = get_posts( array(
6029 'name' => $post_name,
6030 'post_status' => 'trash',
6031 'post_type' => 'any',
6033 'post__not_in' => array( $post_ID )
6036 if ( ! empty( $trashed_posts_with_desired_slug ) ) {
6037 foreach ( $trashed_posts_with_desired_slug as $_post ) {
6038 wp_add_trashed_suffix_to_post_name_for_post( $_post );
6044 * Adds a trashed suffix for a given post.
6046 * Store its desired (i.e. current) slug so it can try to reclaim it
6047 * if the post is untrashed.
6054 * @param WP_Post $post The post.
6055 * @return string New slug for the post.
6057 function wp_add_trashed_suffix_to_post_name_for_post( $post ) {
6060 $post = get_post( $post );
6062 if ( '__trashed' === substr( $post->post_name, -9 ) ) {
6063 return $post->post_name;
6065 add_post_meta( $post->ID, '_wp_desired_post_slug', $post->post_name );
6066 $post_name = _truncate_post_slug( $post->post_name, 191 ) . '__trashed';
6067 $wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), array( 'ID' => $post->ID ) );
6068 clean_post_cache( $post->ID );