10 // Post Type Registration
14 * Creates the initial post types when 'init' action is fired.
18 function create_initial_post_types() {
19 register_post_type( 'post', array(
21 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
24 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
25 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
26 'capability_type' => 'post',
27 'map_meta_cap' => true,
29 'hierarchical' => false,
32 'delete_with_user' => true,
33 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
36 register_post_type( 'page', array(
38 'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
41 'publicly_queryable' => false,
42 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
43 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
44 'capability_type' => 'page',
45 'map_meta_cap' => true,
46 'menu_position' => 20,
47 'hierarchical' => true,
50 'delete_with_user' => true,
51 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
54 register_post_type( 'attachment', array(
56 'name' => _x('Media', 'post type general name'),
57 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
58 'add_new' => _x( 'Add New', 'add new media' ),
59 'edit_item' => __( 'Edit Media' ),
60 'view_item' => __( 'View Attachment Page' ),
64 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
65 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
66 'capability_type' => 'post',
67 'capabilities' => array(
68 'create_posts' => 'upload_files',
70 'map_meta_cap' => true,
71 'hierarchical' => false,
74 'show_in_nav_menus' => false,
75 'delete_with_user' => true,
76 'supports' => array( 'title', 'author', 'comments' ),
78 add_post_type_support( 'attachment:audio', 'thumbnail' );
79 add_post_type_support( 'attachment:video', 'thumbnail' );
81 register_post_type( 'revision', array(
83 'name' => __( 'Revisions' ),
84 'singular_name' => __( 'Revision' ),
87 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
88 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
89 'capability_type' => 'post',
90 'map_meta_cap' => true,
91 'hierarchical' => false,
94 'can_export' => false,
95 'delete_with_user' => true,
96 'supports' => array( 'author' ),
99 register_post_type( 'nav_menu_item', array(
101 'name' => __( 'Navigation Menu Items' ),
102 'singular_name' => __( 'Navigation Menu Item' ),
105 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
106 'hierarchical' => false,
108 'delete_with_user' => false,
109 'query_var' => false,
112 register_post_status( 'publish', array(
113 'label' => _x( 'Published', 'post' ),
115 '_builtin' => true, /* internal use only. */
116 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
119 register_post_status( 'future', array(
120 'label' => _x( 'Scheduled', 'post' ),
122 '_builtin' => true, /* internal use only. */
123 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
126 register_post_status( 'draft', array(
127 'label' => _x( 'Draft', 'post' ),
129 '_builtin' => true, /* internal use only. */
130 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
133 register_post_status( 'pending', array(
134 'label' => _x( 'Pending', 'post' ),
136 '_builtin' => true, /* internal use only. */
137 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
140 register_post_status( 'private', array(
141 'label' => _x( 'Private', 'post' ),
143 '_builtin' => true, /* internal use only. */
144 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
147 register_post_status( 'trash', array(
148 'label' => _x( 'Trash', 'post' ),
150 '_builtin' => true, /* internal use only. */
151 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
152 'show_in_admin_status_list' => true,
155 register_post_status( 'auto-draft', array(
156 'label' => 'auto-draft',
158 '_builtin' => true, /* internal use only. */
161 register_post_status( 'inherit', array(
162 'label' => 'inherit',
164 '_builtin' => true, /* internal use only. */
165 'exclude_from_search' => false,
170 * Retrieve attached file path based on attachment ID.
172 * By default the path will go through the 'get_attached_file' filter, but
173 * passing a true to the $unfiltered argument of get_attached_file() will
174 * return the file path unfiltered.
176 * The function works by getting the single post meta name, named
177 * '_wp_attached_file' and returning it. This is a convenience function to
178 * prevent looking up the meta name and provide a mechanism for sending the
179 * attached filename through a filter.
183 * @param int $attachment_id Attachment ID.
184 * @param bool $unfiltered Optional. Whether to apply filters. Default false.
185 * @return string|false The file path to where the attached file should be, false otherwise.
187 function get_attached_file( $attachment_id, $unfiltered = false ) {
188 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
189 // If the file is relative, prepend upload dir.
190 if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
191 $file = $uploads['basedir'] . "/$file";
196 * Filter the attached file based on the given ID.
200 * @param string $file Path to attached file.
201 * @param int $attachment_id Attachment ID.
203 return apply_filters( 'get_attached_file', $file, $attachment_id );
207 * Update attachment file path based on attachment ID.
209 * Used to update the file path of the attachment, which uses post meta name
210 * '_wp_attached_file' to store the path of the attachment.
214 * @param int $attachment_id Attachment ID.
215 * @param string $file File path for the attachment.
216 * @return bool True on success, false on failure.
218 function update_attached_file( $attachment_id, $file ) {
219 if ( !get_post( $attachment_id ) )
223 * Filter the path to the attached file to update.
227 * @param string $file Path to the attached file to update.
228 * @param int $attachment_id Attachment ID.
230 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
232 if ( $file = _wp_relative_upload_path( $file ) )
233 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
235 return delete_post_meta( $attachment_id, '_wp_attached_file' );
239 * Return relative path to an uploaded file.
241 * The path is relative to the current upload dir.
245 * @param string $path Full path to the file.
246 * @return string Relative path on success, unchanged path on failure.
248 function _wp_relative_upload_path( $path ) {
251 $uploads = wp_upload_dir();
252 if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
253 $new_path = str_replace( $uploads['basedir'], '', $new_path );
254 $new_path = ltrim( $new_path, '/' );
258 * Filter the relative path to an uploaded file.
262 * @param string $new_path Relative path to the file.
263 * @param string $path Full path to the file.
265 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
269 * Retrieve all children of the post parent ID.
271 * Normally, without any enhancements, the children would apply to pages. In the
272 * context of the inner workings of WordPress, pages, posts, and attachments
273 * share the same table, so therefore the functionality could apply to any one
274 * of them. It is then noted that while this function does not work on posts, it
275 * does not mean that it won't work on posts. It is recommended that you know
276 * what context you wish to retrieve the children of.
278 * Attachments may also be made the child of a post, so if that is an accurate
279 * statement (which needs to be verified), it would then be possible to get
280 * all of the attachments for a post. Attachments have since changed since
281 * version 2.5, so this is most likely inaccurate, but serves generally as an
282 * example of what is possible.
284 * The arguments listed as defaults are for this function and also of the
285 * {@link get_posts()} function. The arguments are combined with the
286 * get_children defaults and are then passed to the {@link get_posts()}
287 * function, which accepts additional arguments. You can replace the defaults in
288 * this function, listed below and the additional arguments listed in the
289 * {@link get_posts()} function.
291 * The 'post_parent' is the most important argument and important attention
292 * needs to be paid to the $args parameter. If you pass either an object or an
293 * integer (number), then just the 'post_parent' is grabbed and everything else
294 * is lost. If you don't specify any arguments, then it is assumed that you are
295 * in The Loop and the post parent will be grabbed for from the current post.
297 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
298 * is the amount of posts to retrieve that has a default of '-1', which is
299 * used to get all of the posts. Giving a number higher than 0 will only
300 * retrieve that amount of posts.
302 * The 'post_type' and 'post_status' arguments can be used to choose what
303 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
304 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
305 * argument will accept any post status within the write administration panels.
310 * @todo Check validity of description.
312 * @global WP_Post $post
314 * @param mixed $args Optional. User defined arguments for replacing the defaults. Default empty.
315 * @param string $output Optional. Constant for return type. Accepts OBJECT, ARRAY_A, ARRAY_N.
317 * @return array Array of children, where the type of each element is determined by $output parameter.
318 * Empty array on failure.
320 function get_children( $args = '', $output = OBJECT ) {
322 if ( empty( $args ) ) {
323 if ( isset( $GLOBALS['post'] ) ) {
324 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
328 } elseif ( is_object( $args ) ) {
329 $args = array('post_parent' => (int) $args->post_parent );
330 } elseif ( is_numeric( $args ) ) {
331 $args = array('post_parent' => (int) $args);
335 'numberposts' => -1, 'post_type' => 'any',
336 'post_status' => 'any', 'post_parent' => 0,
339 $r = wp_parse_args( $args, $defaults );
341 $children = get_posts( $r );
346 if ( ! empty( $r['fields'] ) )
349 update_post_cache($children);
351 foreach ( $children as $key => $child )
352 $kids[$child->ID] = $children[$key];
354 if ( $output == OBJECT ) {
356 } elseif ( $output == ARRAY_A ) {
358 foreach ( (array) $kids as $kid ) {
359 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
362 } elseif ( $output == ARRAY_N ) {
364 foreach ( (array) $kids as $kid ) {
365 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
374 * Get extended entry info (<!--more-->).
376 * There should not be any space after the second dash and before the word
377 * 'more'. There can be text or space(s) after the word 'more', but won't be
380 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
381 * the `<!--more-->`. The 'extended' key has the content after the
382 * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
386 * @param string $post Post content.
387 * @return array Post before ('main'), after ('extended'), and custom read more ('more_text').
389 function get_extended( $post ) {
390 //Match the new style more links.
391 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
392 list($main, $extended) = explode($matches[0], $post, 2);
393 $more_text = $matches[1];
400 // leading and trailing whitespace.
401 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
402 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
403 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
405 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
409 * Retrieves post data given a post ID or post object.
411 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
412 * $post, must be given as a variable, since it is passed by reference.
416 * @global WP_Post $post
418 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
419 * @param string $output Optional, default is Object. Accepts OBJECT, ARRAY_A, or ARRAY_N.
421 * @param string $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
422 * or 'display'. Default 'raw'.
423 * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
424 * When $output is OBJECT, a `WP_Post` instance is returned.
426 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
427 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
428 $post = $GLOBALS['post'];
430 if ( $post instanceof WP_Post ) {
432 } elseif ( is_object( $post ) ) {
433 if ( empty( $post->filter ) ) {
434 $_post = sanitize_post( $post, 'raw' );
435 $_post = new WP_Post( $_post );
436 } elseif ( 'raw' == $post->filter ) {
437 $_post = new WP_Post( $post );
439 $_post = WP_Post::get_instance( $post->ID );
442 $_post = WP_Post::get_instance( $post );
448 $_post = $_post->filter( $filter );
450 if ( $output == ARRAY_A )
451 return $_post->to_array();
452 elseif ( $output == ARRAY_N )
453 return array_values( $_post->to_array() );
459 * Retrieve ancestors of a post.
463 * @param int|WP_Post $post Post ID or post object.
464 * @return array Ancestor IDs or empty array if none are found.
466 function get_post_ancestors( $post ) {
467 $post = get_post( $post );
469 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
472 $ancestors = array();
474 $id = $ancestors[] = $post->post_parent;
476 while ( $ancestor = get_post( $id ) ) {
477 // Loop detection: If the ancestor has been seen before, break.
478 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
481 $id = $ancestors[] = $ancestor->post_parent;
488 * Retrieve data from a post field based on Post ID.
490 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
491 * etc and based off of the post object property or key names.
493 * The context values are based off of the taxonomy filter functions and
494 * supported values are found within those functions.
498 * @see sanitize_post_field()
500 * @param string $field Post field name.
501 * @param int|WP_Post $post Post ID or post object.
502 * @param string $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
503 * or 'display'. Default 'display'.
504 * @return string The value of the post field on success, empty string on failure.
506 function get_post_field( $field, $post, $context = 'display' ) {
507 $post = get_post( $post );
512 if ( !isset($post->$field) )
515 return sanitize_post_field($field, $post->$field, $post->ID, $context);
519 * Retrieve the mime type of an attachment based on the ID.
521 * This function can be used with any post type, but it makes more sense with
526 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
527 * @return string|false The mime type on success, false on failure.
529 function get_post_mime_type( $ID = '' ) {
530 $post = get_post($ID);
532 if ( is_object($post) )
533 return $post->post_mime_type;
539 * Retrieve the post status based on the Post ID.
541 * If the post ID is of an attachment, then the parent post status will be given
546 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
547 * @return string|false Post status on success, false on failure.
549 function get_post_status( $ID = '' ) {
550 $post = get_post($ID);
552 if ( !is_object($post) )
555 if ( 'attachment' == $post->post_type ) {
556 if ( 'private' == $post->post_status )
559 // Unattached attachments are assumed to be published.
560 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
563 // Inherit status from the parent.
564 if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) {
565 $parent_post_status = get_post_status( $post->post_parent );
566 if ( 'trash' == $parent_post_status ) {
567 return get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
569 return $parent_post_status;
576 * Filter the post status.
580 * @param string $post_status The post status.
581 * @param WP_Post $post The post object.
583 return apply_filters( 'get_post_status', $post->post_status, $post );
587 * Retrieve all of the WordPress supported post statuses.
589 * Posts have a limited set of valid status values, this provides the
590 * post_status values and descriptions.
594 * @return array List of post statuses.
596 function get_post_statuses() {
598 'draft' => __( 'Draft' ),
599 'pending' => __( 'Pending Review' ),
600 'private' => __( 'Private' ),
601 'publish' => __( 'Published' )
608 * Retrieve all of the WordPress support page statuses.
610 * Pages have a limited set of valid status values, this provides the
611 * post_status values and descriptions.
615 * @return array List of page statuses.
617 function get_page_statuses() {
619 'draft' => __( 'Draft' ),
620 'private' => __( 'Private' ),
621 'publish' => __( 'Published' )
628 * Register a post status. Do not use before init.
630 * A simple function for creating or modifying a post status based on the
631 * parameters given. The function will accept an array (second optional
632 * parameter), along with a string for the post status name.
634 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
637 * @global array $wp_post_statuses Inserts new post status object into the list
639 * @param string $post_status Name of the post status.
640 * @param array|string $args {
641 * Optional. Array or string of post status arguments.
643 * @type bool|string $label A descriptive name for the post status marked
644 * for translation. Defaults to value of $post_status.
645 * @type bool|array $label_count Descriptive text to use for nooped plurals.
646 * Default array of $label, twice
647 * @type bool $exclude_from_search Whether to exclude posts with this post status
648 * from search results. Default is value of $internal.
649 * @type bool $_builtin Whether the status is built-in. Core-use only.
651 * @type bool $public Whether posts of this status should be shown
652 * in the front end of the site. Default false.
653 * @type bool $internal Whether the status is for internal use only.
655 * @type bool $protected Whether posts with this status should be protected.
657 * @type bool $private Whether posts with this status should be private.
659 * @type bool $publicly_queryable Whether posts with this status should be publicly-
660 * queryable. Default is value of $public.
661 * @type bool $show_in_admin_all_list Whether to include posts in the edit listing for
662 * their post type. Default is value of $internal.
663 * @type bool $show_in_admin_status_list Show in the list of statuses with post counts at
664 * the top of the edit listings,
665 * e.g. All (12) | Published (9) | My Custom Status (2)
666 * Default is value of $internal.
670 function register_post_status( $post_status, $args = array() ) {
671 global $wp_post_statuses;
673 if (!is_array($wp_post_statuses))
674 $wp_post_statuses = array();
676 // Args prefixed with an underscore are reserved for internal use.
679 'label_count' => false,
680 'exclude_from_search' => null,
686 'publicly_queryable' => null,
687 'show_in_admin_status_list' => null,
688 'show_in_admin_all_list' => null,
690 $args = wp_parse_args($args, $defaults);
691 $args = (object) $args;
693 $post_status = sanitize_key($post_status);
694 $args->name = $post_status;
696 // Set various defaults.
697 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
698 $args->internal = true;
700 if ( null === $args->public )
701 $args->public = false;
703 if ( null === $args->private )
704 $args->private = false;
706 if ( null === $args->protected )
707 $args->protected = false;
709 if ( null === $args->internal )
710 $args->internal = false;
712 if ( null === $args->publicly_queryable )
713 $args->publicly_queryable = $args->public;
715 if ( null === $args->exclude_from_search )
716 $args->exclude_from_search = $args->internal;
718 if ( null === $args->show_in_admin_all_list )
719 $args->show_in_admin_all_list = !$args->internal;
721 if ( null === $args->show_in_admin_status_list )
722 $args->show_in_admin_status_list = !$args->internal;
724 if ( false === $args->label )
725 $args->label = $post_status;
727 if ( false === $args->label_count )
728 $args->label_count = array( $args->label, $args->label );
730 $wp_post_statuses[$post_status] = $args;
736 * Retrieve a post status object by name.
740 * @global array $wp_post_statuses List of post statuses.
742 * @see register_post_status()
744 * @param string $post_status The name of a registered post status.
745 * @return object|null A post status object.
747 function get_post_status_object( $post_status ) {
748 global $wp_post_statuses;
750 if ( empty($wp_post_statuses[$post_status]) )
753 return $wp_post_statuses[$post_status];
757 * Get a list of post statuses.
761 * @global array $wp_post_statuses List of post statuses.
763 * @see register_post_status()
765 * @param array|string $args Optional. Array or string of post status arguments to compare against
766 * properties of the global `$wp_post_statuses objects`. Default empty array.
767 * @param string $output Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
768 * @param string $operator Optional. The logical operation to perform. 'or' means only one element
769 * from the array needs to match; 'and' means all elements must match.
771 * @return array A list of post status names or objects.
773 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
774 global $wp_post_statuses;
776 $field = ('names' == $output) ? 'name' : false;
778 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
782 * Whether the post type is hierarchical.
784 * A false return value might also mean that the post type does not exist.
788 * @see get_post_type_object()
790 * @param string $post_type Post type name
791 * @return bool Whether post type is hierarchical.
793 function is_post_type_hierarchical( $post_type ) {
794 if ( ! post_type_exists( $post_type ) )
797 $post_type = get_post_type_object( $post_type );
798 return $post_type->hierarchical;
802 * Check if a post type is registered.
806 * @see get_post_type_object()
808 * @param string $post_type Post type name.
809 * @return bool Whether post type is registered.
811 function post_type_exists( $post_type ) {
812 return (bool) get_post_type_object( $post_type );
816 * Retrieve the post type of the current post or of a given post.
820 * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
821 * @return string|false Post type on success, false on failure.
823 function get_post_type( $post = null ) {
824 if ( $post = get_post( $post ) )
825 return $post->post_type;
831 * Retrieve a post type object by name.
835 * @global array $wp_post_types List of post types.
837 * @see register_post_type()
839 * @param string $post_type The name of a registered post type.
840 * @return object|null A post type object.
842 function get_post_type_object( $post_type ) {
843 global $wp_post_types;
845 if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
849 return $wp_post_types[ $post_type ];
853 * Get a list of all registered post type objects.
857 * @global array $wp_post_types List of post types.
859 * @see register_post_type() for accepted arguments.
861 * @param array|string $args Optional. An array of key => value arguments to match against
862 * the post type objects. Default empty array.
863 * @param string $output Optional. The type of output to return. Accepts post type 'names'
864 * or 'objects'. Default 'names'.
865 * @param string $operator Optional. The logical operation to perform. 'or' means only one
866 * element from the array needs to match; 'and' means all elements
867 * must match. Accepts 'or' or 'and'. Default 'and'.
868 * @return array A list of post type names or objects.
870 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
871 global $wp_post_types;
873 $field = ('names' == $output) ? 'name' : false;
875 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
879 * Register a post type. Do not use before init.
881 * A function for creating or modifying a post type based on the
882 * parameters given. The function will accept an array (second optional
883 * parameter), along with a string for the post type name.
886 * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
887 * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing screen and post editing screen.
889 * @global array $wp_post_types List of post types.
890 * @global WP_Rewrite $wp_rewrite Used for default feeds.
891 * @global WP $wp Used to add query vars.
893 * @param string $post_type Post type key, must not exceed 20 characters.
894 * @param array|string $args {
895 * Array or string of arguments for registering a post type.
897 * @type string $label Name of the post type shown in the menu. Usually plural.
898 * Default is value of $labels['name'].
899 * @type array $labels An array of labels for this post type. If not set, post
900 * labels are inherited for non-hierarchical types and page
901 * labels for hierarchical ones. {@see get_post_type_labels()}.
902 * @type string $description A short descriptive summary of what the post type is.
904 * @type bool $public Whether a post type is intended for use publicly either via
905 * the admin interface or by front-end users. While the default
906 * settings of $exclude_from_search, $publicly_queryable, $show_ui,
907 * and $show_in_nav_menus are inherited from public, each does not
908 * rely on this relationship and controls a very specific intention.
910 * @type bool $hierarchical Whether the post type is hierarchical (e.g. page). Default false.
911 * @type bool $exclude_from_search Whether to exclude posts with this post type from front end search
912 * results. Default is the opposite value of $public.
913 * @type bool $publicly_queryable Whether queries can be performed on the front end for the post type
914 * as part of {@see parse_request()}. Endpoints would include:
915 * * ?post_type={post_type_key}
916 * * ?{post_type_key}={single_post_slug}
917 * * ?{post_type_query_var}={single_post_slug}
918 * If not set, the default is inherited from $public.
919 * @type bool $show_ui Whether to generate and allow a UI for managing this post type in the
920 * admin. Default is value of $public.
921 * @type bool $show_in_menu Where to show the post type in the admin menu. To work, $show_ui
922 * must be true. If true, the post type is shown in its own top level
923 * menu. If false, no menu is shown. If a string of an existing top
924 * level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
925 * type will be placed as a sub-menu of that.
926 * Default is value of $show_ui.
927 * @type bool $show_in_nav_menus Makes this post type available for selection in navigation menus.
928 * Default is value $public.
929 * @type bool $show_in_admin_bar Makes this post type available via the admin bar. Default is value
931 * @type int $menu_position The position in the menu order the post type should appear. To work,
932 * $show_in_menu must be true. Default null (at the bottom).
933 * @type string $menu_icon The url to the icon to be used for this menu. Pass a base64-encoded
934 * SVG using a data URI, which will be colored to match the color scheme
935 * -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
936 * of a Dashicons helper class to use a font icon, e.g.
937 * 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
938 * so an icon can be added via CSS. Defaults to use the posts icon.
939 * @type string $capability_type The string to use to build the read, edit, and delete capabilities.
940 * May be passed as an array to allow for alternative plurals when using
941 * this argument as a base to construct the capabilities, e.g.
942 * array('story', 'stories'). Default 'post'.
943 * @type array $capabilities Array of capabilities for this post type. $capability_type is used
944 * as a base to construct capabilities by default.
945 * {@see get_post_type_capabilities()}.
946 * @type bool $map_meta_cap Whether to use the internal default meta capability handling.
948 * @type array $supports An alias for calling {@see add_post_type_support()} directly.
949 * Defaults to array containing 'title' & 'editor'.
950 * @type callable $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
951 * edit form. Do remove_meta_box() and add_meta_box() calls in the
952 * callback. Default null.
953 * @type array $taxonomies An array of taxonomy identifiers that will be registered for the
954 * post type. Taxonomies can be registered later with
955 * {@see register_taxonomy()} or {@see register_taxonomy_for_object_type()}.
956 * Default empty array.
957 * @type bool|string $has_archive Whether there should be post type archives, or if a string, the
958 * archive slug to use. Will generate the proper rewrite rules if
959 * $rewrite is enabled. Default false.
960 * @type bool|array $rewrite {
961 * Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
962 * Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
963 * passed with any of these keys:
965 * @type string $slug Customize the permastruct slug. Defaults to $post_type key.
966 * @type bool $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
968 * @type bool $feeds Whether the feed permastruct should be built for this post type.
969 * Default is value of $has_archive.
970 * @type bool $pages Whether the permastruct should provide for pagination. Default true.
971 * @type const $ep_mask Endpoint mask to assign. If not specified and permalink_epmask is set,
972 * inherits from $permalink_epmask. If not specified and permalink_epmask
973 * is not set, defaults to EP_PERMALINK.
975 * @type string|bool $query_var Sets the query_var key for this post type. Defaults to $post_type
976 * key. If false, a post type cannot be loaded at
977 * ?{query_var}={post_slug}. If specified as a string, the query
978 * ?{query_var_string}={post_slug} will be valid.
979 * @type bool $can_export Whether to allow this post type to be exported. Default true.
980 * @type bool $delete_with_user Whether to delete posts of this type when deleting a user. If true,
981 * posts of this type belonging to the user will be moved to trash
982 * when then user is deleted. If false, posts of this type belonging
983 * to the user will *not* be trashed or deleted. If not set (the default),
984 * posts are trashed if post_type_supports('author'). Otherwise posts
985 * are not trashed or deleted. Default null.
986 * @type bool $_builtin FOR INTERNAL USE ONLY! True if this post type is a native or
987 * "built-in" post_type. Default false.
988 * @type string $_edit_link FOR INTERNAL USE ONLY! URL segment to use for edit link of
989 * this post type. Default 'post.php?post=%d'.
991 * @return object|WP_Error The registered post type object, or an error object.
993 function register_post_type( $post_type, $args = array() ) {
994 global $wp_post_types, $wp_rewrite, $wp;
996 if ( ! is_array( $wp_post_types ) ) {
997 $wp_post_types = array();
1000 // Sanitize post type name
1001 $post_type = sanitize_key( $post_type );
1002 $args = wp_parse_args( $args );
1005 * Filter the arguments for registering a post type.
1009 * @param array $args Array of arguments for registering a post type.
1010 * @param string $post_type Post type key.
1012 $args = apply_filters( 'register_post_type_args', $args, $post_type );
1014 $has_edit_link = ! empty( $args['_edit_link'] );
1016 // Args prefixed with an underscore are reserved for internal use.
1018 'labels' => array(),
1019 'description' => '',
1021 'hierarchical' => false,
1022 'exclude_from_search' => null,
1023 'publicly_queryable' => null,
1025 'show_in_menu' => null,
1026 'show_in_nav_menus' => null,
1027 'show_in_admin_bar' => null,
1028 'menu_position' => null,
1029 'menu_icon' => null,
1030 'capability_type' => 'post',
1031 'capabilities' => array(),
1032 'map_meta_cap' => null,
1033 'supports' => array(),
1034 'register_meta_box_cb' => null,
1035 'taxonomies' => array(),
1036 'has_archive' => false,
1038 'query_var' => true,
1039 'can_export' => true,
1040 'delete_with_user' => null,
1041 '_builtin' => false,
1042 '_edit_link' => 'post.php?post=%d',
1044 $args = array_merge( $defaults, $args );
1045 $args = (object) $args;
1047 $args->name = $post_type;
1049 if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1050 _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2' );
1051 return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1054 // If not set, default to the setting for public.
1055 if ( null === $args->publicly_queryable )
1056 $args->publicly_queryable = $args->public;
1058 // If not set, default to the setting for public.
1059 if ( null === $args->show_ui )
1060 $args->show_ui = $args->public;
1062 // If not set, default to the setting for show_ui.
1063 if ( null === $args->show_in_menu || ! $args->show_ui )
1064 $args->show_in_menu = $args->show_ui;
1066 // If not set, default to the whether the full UI is shown.
1067 if ( null === $args->show_in_admin_bar )
1068 $args->show_in_admin_bar = (bool) $args->show_in_menu;
1070 // If not set, default to the setting for public.
1071 if ( null === $args->show_in_nav_menus )
1072 $args->show_in_nav_menus = $args->public;
1074 // If not set, default to true if not public, false if public.
1075 if ( null === $args->exclude_from_search )
1076 $args->exclude_from_search = !$args->public;
1078 // Back compat with quirky handling in version 3.0. #14122.
1079 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1080 $args->map_meta_cap = true;
1082 // If not set, default to false.
1083 if ( null === $args->map_meta_cap )
1084 $args->map_meta_cap = false;
1086 // If there's no specified edit link and no UI, remove the edit link.
1087 if ( ! $args->show_ui && ! $has_edit_link ) {
1088 $args->_edit_link = '';
1091 $args->cap = get_post_type_capabilities( $args );
1092 unset( $args->capabilities );
1094 if ( is_array( $args->capability_type ) )
1095 $args->capability_type = $args->capability_type[0];
1097 if ( ! empty( $args->supports ) ) {
1098 add_post_type_support( $post_type, $args->supports );
1099 unset( $args->supports );
1100 } elseif ( false !== $args->supports ) {
1101 // Add default features
1102 add_post_type_support( $post_type, array( 'title', 'editor' ) );
1105 if ( false !== $args->query_var ) {
1106 if ( true === $args->query_var )
1107 $args->query_var = $post_type;
1109 $args->query_var = sanitize_title_with_dashes( $args->query_var );
1111 if ( $wp && is_post_type_viewable( $args ) ) {
1112 $wp->add_query_var( $args->query_var );
1116 if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
1117 if ( ! is_array( $args->rewrite ) )
1118 $args->rewrite = array();
1119 if ( empty( $args->rewrite['slug'] ) )
1120 $args->rewrite['slug'] = $post_type;
1121 if ( ! isset( $args->rewrite['with_front'] ) )
1122 $args->rewrite['with_front'] = true;
1123 if ( ! isset( $args->rewrite['pages'] ) )
1124 $args->rewrite['pages'] = true;
1125 if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1126 $args->rewrite['feeds'] = (bool) $args->has_archive;
1127 if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1128 if ( isset( $args->permalink_epmask ) )
1129 $args->rewrite['ep_mask'] = $args->permalink_epmask;
1131 $args->rewrite['ep_mask'] = EP_PERMALINK;
1134 if ( $args->hierarchical )
1135 add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
1137 add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
1139 if ( $args->has_archive ) {
1140 $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1141 if ( $args->rewrite['with_front'] )
1142 $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1144 $archive_slug = $wp_rewrite->root . $archive_slug;
1146 add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1147 if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1148 $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1149 add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1150 add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1152 if ( $args->rewrite['pages'] )
1153 add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1156 $permastruct_args = $args->rewrite;
1157 $permastruct_args['feed'] = $permastruct_args['feeds'];
1158 add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
1161 // Register the post type meta box if a custom callback was specified.
1162 if ( $args->register_meta_box_cb )
1163 add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
1165 $args->labels = get_post_type_labels( $args );
1166 $args->label = $args->labels->name;
1168 $wp_post_types[ $post_type ] = $args;
1170 add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1172 foreach ( $args->taxonomies as $taxonomy ) {
1173 register_taxonomy_for_object_type( $taxonomy, $post_type );
1177 * Fires after a post type is registered.
1181 * @param string $post_type Post type.
1182 * @param object $args Arguments used to register the post type.
1184 do_action( 'registered_post_type', $post_type, $args );
1190 * Build an object with all post type capabilities out of a post type object
1192 * Post type capabilities use the 'capability_type' argument as a base, if the
1193 * capability is not set in the 'capabilities' argument array or if the
1194 * 'capabilities' argument is not supplied.
1196 * The capability_type argument can optionally be registered as an array, with
1197 * the first value being singular and the second plural, e.g. array('story, 'stories')
1198 * Otherwise, an 's' will be added to the value for the plural form. After
1199 * registration, capability_type will always be a string of the singular value.
1201 * By default, seven keys are accepted as part of the capabilities array:
1203 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1204 * generally mapped to corresponding primitive capabilities depending on the
1205 * context, which would be the post being edited/read/deleted and the user or
1206 * role being checked. Thus these capabilities would generally not be granted
1207 * directly to users or roles.
1209 * - edit_posts - Controls whether objects of this post type can be edited.
1210 * - edit_others_posts - Controls whether objects of this type owned by other users
1211 * can be edited. If the post type does not support an author, then this will
1212 * behave like edit_posts.
1213 * - publish_posts - Controls publishing objects of this post type.
1214 * - read_private_posts - Controls whether private objects can be read.
1216 * These four primitive capabilities are checked in core in various locations.
1217 * There are also seven other primitive capabilities which are not referenced
1218 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1219 * meta capabilities and translates them into one or more primitive capabilities
1220 * that must then be checked against the user or role, depending on the context.
1222 * - read - Controls whether objects of this post type can be read.
1223 * - delete_posts - Controls whether objects of this post type can be deleted.
1224 * - delete_private_posts - Controls whether private objects can be deleted.
1225 * - delete_published_posts - Controls whether published objects can be deleted.
1226 * - delete_others_posts - Controls whether objects owned by other users can be
1227 * can be deleted. If the post type does not support an author, then this will
1228 * behave like delete_posts.
1229 * - edit_private_posts - Controls whether private objects can be edited.
1230 * - edit_published_posts - Controls whether published objects can be edited.
1232 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1233 * only assigned by default if the post type is registered with the 'map_meta_cap'
1234 * argument set to true (default is false).
1238 * @see register_post_type()
1239 * @see map_meta_cap()
1241 * @param object $args Post type registration arguments.
1242 * @return object object with all the capabilities as member variables.
1244 function get_post_type_capabilities( $args ) {
1245 if ( ! is_array( $args->capability_type ) )
1246 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1248 // Singular base for meta capabilities, plural base for primitive capabilities.
1249 list( $singular_base, $plural_base ) = $args->capability_type;
1251 $default_capabilities = array(
1252 // Meta capabilities
1253 'edit_post' => 'edit_' . $singular_base,
1254 'read_post' => 'read_' . $singular_base,
1255 'delete_post' => 'delete_' . $singular_base,
1256 // Primitive capabilities used outside of map_meta_cap():
1257 'edit_posts' => 'edit_' . $plural_base,
1258 'edit_others_posts' => 'edit_others_' . $plural_base,
1259 'publish_posts' => 'publish_' . $plural_base,
1260 'read_private_posts' => 'read_private_' . $plural_base,
1263 // Primitive capabilities used within map_meta_cap():
1264 if ( $args->map_meta_cap ) {
1265 $default_capabilities_for_mapping = array(
1267 'delete_posts' => 'delete_' . $plural_base,
1268 'delete_private_posts' => 'delete_private_' . $plural_base,
1269 'delete_published_posts' => 'delete_published_' . $plural_base,
1270 'delete_others_posts' => 'delete_others_' . $plural_base,
1271 'edit_private_posts' => 'edit_private_' . $plural_base,
1272 'edit_published_posts' => 'edit_published_' . $plural_base,
1274 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1277 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1279 // Post creation capability simply maps to edit_posts by default:
1280 if ( ! isset( $capabilities['create_posts'] ) )
1281 $capabilities['create_posts'] = $capabilities['edit_posts'];
1283 // Remember meta capabilities for future reference.
1284 if ( $args->map_meta_cap )
1285 _post_type_meta_capabilities( $capabilities );
1287 return (object) $capabilities;
1291 * Store or return a list of post type meta caps for map_meta_cap().
1296 * @staticvar array $meta_caps
1298 * @param array|void $capabilities Post type meta capabilities.
1300 function _post_type_meta_capabilities( $capabilities = null ) {
1301 static $meta_caps = array();
1302 if ( null === $capabilities )
1304 foreach ( $capabilities as $core => $custom ) {
1305 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1306 $meta_caps[ $custom ] = $core;
1311 * Build an object with all post type labels out of a post type object
1313 * Accepted keys of the label array in the post type object:
1315 * - name - general name for the post type, usually plural. The same and overridden
1316 * by $post_type_object->label. Default is Posts/Pages
1317 * - singular_name - name for one object of this post type. Default is Post/Page
1318 * - add_new - Default is Add New for both hierarchical and non-hierarchical types.
1319 * When internationalizing this string, please use a gettext context
1320 * {@link https://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context}
1321 * matching your post type. Example: `_x( 'Add New', 'product' );`.
1322 * - add_new_item - Default is Add New Post/Add New Page.
1323 * - edit_item - Default is Edit Post/Edit Page.
1324 * - new_item - Default is New Post/New Page.
1325 * - view_item - Default is View Post/View Page.
1326 * - search_items - Default is Search Posts/Search Pages.
1327 * - not_found - Default is No posts found/No pages found.
1328 * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash.
1329 * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical
1330 * ones the default is 'Parent Page:'.
1331 * - all_items - String for the submenu. Default is All Posts/All Pages.
1332 * - archives - String for use with archives in nav menus. Default is Post Archives/Page Archives.
1333 * - insert_into_item - String for the media frame button. Default is Insert into post/Insert into page.
1334 * - uploaded_to_this_item - String for the media frame filter. Default is Uploaded to this post/Uploaded to this page.
1335 * - featured_image - Default is Featured Image.
1336 * - set_featured_image - Default is Set featured image.
1337 * - remove_featured_image - Default is Remove featured image.
1338 * - use_featured_image - Default is Use as featured image.
1339 * - menu_name - Default is the same as `name`.
1340 * - filter_items_list - String for the table views hidden heading.
1341 * - items_list_navigation - String for the table pagination hidden heading.
1342 * - items_list - String for the table hidden heading.
1344 * Above, the first default value is for non-hierarchical post types (like posts)
1345 * and the second one is for hierarchical post types (like pages).
1348 * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
1349 * and `use_featured_image` labels.
1350 * @since 4.4.0 Added the `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
1351 * `items_list_navigation`, and `items_list` labels.
1355 * @param object $post_type_object Post type object.
1356 * @return object object with all the labels as member variables.
1358 function get_post_type_labels( $post_type_object ) {
1359 $nohier_vs_hier_defaults = array(
1360 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1361 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1362 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1363 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1364 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1365 'new_item' => array( __('New Post'), __('New Page') ),
1366 'view_item' => array( __('View Post'), __('View Page') ),
1367 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1368 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1369 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1370 'parent_item_colon' => array( null, __('Parent Page:') ),
1371 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ),
1372 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ),
1373 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ),
1374 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ),
1375 'featured_image' => array( __( 'Featured Image' ), __( 'Featured Image' ) ),
1376 'set_featured_image' => array( __( 'Set featured image' ), __( 'Set featured image' ) ),
1377 'remove_featured_image' => array( __( 'Remove featured image' ), __( 'Remove featured image' ) ),
1378 'use_featured_image' => array( __( 'Use as featured image' ), __( 'Use as featured image' ) ),
1379 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ),
1380 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ),
1381 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ),
1383 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1385 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1387 $post_type = $post_type_object->name;
1389 $default_labels = clone $labels;
1392 * Filter the labels of a specific post type.
1394 * The dynamic portion of the hook name, `$post_type`, refers to
1395 * the post type slug.
1399 * @see get_post_type_labels() for the full list of labels.
1401 * @param object $labels Object with labels for the post type as member variables.
1403 $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
1405 // Ensure that the filtered labels contain all required default values.
1406 $labels = (object) array_merge( (array) $default_labels, (array) $labels );
1412 * Build an object with custom-something object (post type, taxonomy) labels
1413 * out of a custom-something object
1418 * @param object $object A custom-something object.
1419 * @param array $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
1420 * @return object Object containing labels for the given custom-something object.
1422 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1423 $object->labels = (array) $object->labels;
1425 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1426 $object->labels['name'] = $object->label;
1428 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1429 $object->labels['singular_name'] = $object->labels['name'];
1431 if ( ! isset( $object->labels['name_admin_bar'] ) )
1432 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1434 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1435 $object->labels['menu_name'] = $object->labels['name'];
1437 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1438 $object->labels['all_items'] = $object->labels['menu_name'];
1440 if ( !isset( $object->labels['archives'] ) && isset( $object->labels['all_items'] ) ) {
1441 $object->labels['archives'] = $object->labels['all_items'];
1444 $defaults = array();
1445 foreach ( $nohier_vs_hier_defaults as $key => $value ) {
1446 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1448 $labels = array_merge( $defaults, $object->labels );
1449 $object->labels = (object) $object->labels;
1451 return (object) $labels;
1455 * Add submenus for post types.
1460 function _add_post_type_submenus() {
1461 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1462 $ptype_obj = get_post_type_object( $ptype );
1464 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1466 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" );
1471 * Register support of certain features for a post type.
1473 * All core features are directly associated with a functional area of the edit
1474 * screen, such as the editor or a meta box. Features include: 'title', 'editor',
1475 * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
1476 * 'thumbnail', 'custom-fields', and 'post-formats'.
1478 * Additionally, the 'revisions' feature dictates whether the post type will
1479 * store revisions, and the 'comments' feature dictates whether the comments
1480 * count will show on the edit screen.
1484 * @global array $_wp_post_type_features
1486 * @param string $post_type The post type for which to add the feature.
1487 * @param string|array $feature The feature being added, accepts an array of
1488 * feature strings or a single string.
1490 function add_post_type_support( $post_type, $feature ) {
1491 global $_wp_post_type_features;
1493 $features = (array) $feature;
1494 foreach ($features as $feature) {
1495 if ( func_num_args() == 2 )
1496 $_wp_post_type_features[$post_type][$feature] = true;
1498 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1503 * Remove support for a feature from a post type.
1507 * @global array $_wp_post_type_features
1509 * @param string $post_type The post type for which to remove the feature.
1510 * @param string $feature The feature being removed.
1512 function remove_post_type_support( $post_type, $feature ) {
1513 global $_wp_post_type_features;
1515 unset( $_wp_post_type_features[ $post_type ][ $feature ] );
1519 * Get all the post type features
1523 * @global array $_wp_post_type_features
1525 * @param string $post_type The post type.
1526 * @return array Post type supports list.
1528 function get_all_post_type_supports( $post_type ) {
1529 global $_wp_post_type_features;
1531 if ( isset( $_wp_post_type_features[$post_type] ) )
1532 return $_wp_post_type_features[$post_type];
1538 * Check a post type's support for a given feature.
1542 * @global array $_wp_post_type_features
1544 * @param string $post_type The post type being checked.
1545 * @param string $feature The feature being checked.
1546 * @return bool Whether the post type supports the given feature.
1548 function post_type_supports( $post_type, $feature ) {
1549 global $_wp_post_type_features;
1551 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1555 * Update the post type for the post ID.
1557 * The page or post cache will be cleaned for the post ID.
1561 * @global wpdb $wpdb WordPress database abstraction object.
1563 * @param int $post_id Optional. Post ID to change post type. Default 0.
1564 * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
1565 * name a few. Default 'post'.
1566 * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
1568 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1571 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1572 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1574 clean_post_cache( $post_id );
1580 * Determines whether a post type is considered "viewable".
1582 * For built-in post types such as posts and pages, the 'public' value will be evaluated.
1583 * For all others, the 'publicly_queryable' value will be used.
1587 * @param object $post_type_object Post type object.
1588 * @return bool Whether the post type should be considered viewable.
1590 function is_post_type_viewable( $post_type_object ) {
1591 return $post_type_object->publicly_queryable || ( $post_type_object->_builtin && $post_type_object->public );
1595 * Retrieve list of latest posts or posts matching criteria.
1597 * The defaults are as follows:
1601 * @see WP_Query::parse_query()
1603 * @param array $args {
1604 * Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all
1605 * available arguments.
1607 * @type int $numberposts Total number of posts to retrieve. Is an alias of $posts_per_page
1608 * in WP_Query. Accepts -1 for all. Default 5.
1609 * @type int|string $category Category ID or comma-separated list of IDs (this or any children).
1610 * Is an alias of $cat in WP_Query. Default 0.
1611 * @type array $include An array of post IDs to retrieve, sticky posts will be included.
1612 * Is an alias of $post__in in WP_Query. Default empty array.
1613 * @type array $exclude An array of post IDs not to retrieve. Default empty array.
1614 * @type bool $suppress_filters Whether to suppress filters. Default true.
1616 * @return array List of posts.
1618 function get_posts( $args = null ) {
1621 'category' => 0, 'orderby' => 'date',
1622 'order' => 'DESC', 'include' => array(),
1623 'exclude' => array(), 'meta_key' => '',
1624 'meta_value' =>'', 'post_type' => 'post',
1625 'suppress_filters' => true
1628 $r = wp_parse_args( $args, $defaults );
1629 if ( empty( $r['post_status'] ) )
1630 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1631 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1632 $r['posts_per_page'] = $r['numberposts'];
1633 if ( ! empty($r['category']) )
1634 $r['cat'] = $r['category'];
1635 if ( ! empty($r['include']) ) {
1636 $incposts = wp_parse_id_list( $r['include'] );
1637 $r['posts_per_page'] = count($incposts); // only the number of posts included
1638 $r['post__in'] = $incposts;
1639 } elseif ( ! empty($r['exclude']) )
1640 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1642 $r['ignore_sticky_posts'] = true;
1643 $r['no_found_rows'] = true;
1645 $get_posts = new WP_Query;
1646 return $get_posts->query($r);
1651 // Post meta functions
1655 * Add meta data field to a post.
1657 * Post meta data is called "Custom Fields" on the Administration Screen.
1661 * @param int $post_id Post ID.
1662 * @param string $meta_key Metadata name.
1663 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1664 * @param bool $unique Optional. Whether the same key should not be added.
1666 * @return int|false Meta ID on success, false on failure.
1668 function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
1669 // Make sure meta is added to the post, not a revision.
1670 if ( $the_post = wp_is_post_revision($post_id) )
1671 $post_id = $the_post;
1673 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1677 * Remove metadata matching criteria from a post.
1679 * You can match based on the key, or key and value. Removing based on key and
1680 * value, will keep from removing duplicate metadata with the same key. It also
1681 * allows removing all metadata matching key, if needed.
1685 * @param int $post_id Post ID.
1686 * @param string $meta_key Metadata name.
1687 * @param mixed $meta_value Optional. Metadata value. Must be serializable if
1688 * non-scalar. Default empty.
1689 * @return bool True on success, false on failure.
1691 function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
1692 // Make sure meta is added to the post, not a revision.
1693 if ( $the_post = wp_is_post_revision($post_id) )
1694 $post_id = $the_post;
1696 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1700 * Retrieve post meta field for a post.
1704 * @param int $post_id Post ID.
1705 * @param string $key Optional. The meta key to retrieve. By default, returns
1706 * data for all keys. Default empty.
1707 * @param bool $single Optional. Whether to return a single value. Default false.
1708 * @return mixed Will be an array if $single is false. Will be value of meta data
1709 * field if $single is true.
1711 function get_post_meta( $post_id, $key = '', $single = false ) {
1712 return get_metadata('post', $post_id, $key, $single);
1716 * Update post meta field based on post ID.
1718 * Use the $prev_value parameter to differentiate between meta fields with the
1719 * same key and post ID.
1721 * If the meta field for the post does not exist, it will be added.
1725 * @param int $post_id Post ID.
1726 * @param string $meta_key Metadata key.
1727 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1728 * @param mixed $prev_value Optional. Previous value to check before removing.
1730 * @return int|bool Meta ID if the key didn't exist, true on successful update,
1733 function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
1734 // Make sure meta is added to the post, not a revision.
1735 if ( $the_post = wp_is_post_revision($post_id) )
1736 $post_id = $the_post;
1738 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1742 * Delete everything from post meta matching meta key.
1746 * @param string $post_meta_key Key to search for when deleting.
1747 * @return bool Whether the post meta key was deleted from the database.
1749 function delete_post_meta_by_key( $post_meta_key ) {
1750 return delete_metadata( 'post', null, $post_meta_key, '', true );
1754 * Retrieve post meta fields, based on post ID.
1756 * The post meta fields are retrieved from the cache where possible,
1757 * so the function is optimized to be called more than once.
1761 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1762 * @return array Post meta for the given post.
1764 function get_post_custom( $post_id = 0 ) {
1765 $post_id = absint( $post_id );
1767 $post_id = get_the_ID();
1769 return get_post_meta( $post_id );
1773 * Retrieve meta field names for a post.
1775 * If there are no meta fields, then nothing (null) will be returned.
1779 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1780 * @return array|void Array of the keys, if retrieved.
1782 function get_post_custom_keys( $post_id = 0 ) {
1783 $custom = get_post_custom( $post_id );
1785 if ( !is_array($custom) )
1788 if ( $keys = array_keys($custom) )
1793 * Retrieve values for a custom post field.
1795 * The parameters must not be considered optional. All of the post meta fields
1796 * will be retrieved and only the meta field key values returned.
1800 * @param string $key Optional. Meta field key. Default empty.
1801 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1802 * @return array|null Meta field values.
1804 function get_post_custom_values( $key = '', $post_id = 0 ) {
1808 $custom = get_post_custom($post_id);
1810 return isset($custom[$key]) ? $custom[$key] : null;
1814 * Check if post is sticky.
1816 * Sticky posts should remain at the top of The Loop. If the post ID is not
1817 * given, then The Loop ID for the current post will be used.
1821 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1822 * @return bool Whether post is sticky.
1824 function is_sticky( $post_id = 0 ) {
1825 $post_id = absint( $post_id );
1828 $post_id = get_the_ID();
1830 $stickies = get_option( 'sticky_posts' );
1832 if ( ! is_array( $stickies ) )
1835 if ( in_array( $post_id, $stickies ) )
1842 * Sanitize every post field.
1844 * If the context is 'raw', then the post object or array will get minimal
1845 * sanitization of the integer fields.
1849 * @see sanitize_post_field()
1851 * @param object|WP_Post|array $post The Post Object or Array
1852 * @param string $context Optional. How to sanitize post fields.
1853 * Accepts 'raw', 'edit', 'db', or 'display'.
1854 * Default 'display'.
1855 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the
1856 * same type as $post).
1858 function sanitize_post( $post, $context = 'display' ) {
1859 if ( is_object($post) ) {
1860 // Check if post already filtered for this context.
1861 if ( isset($post->filter) && $context == $post->filter )
1863 if ( !isset($post->ID) )
1865 foreach ( array_keys(get_object_vars($post)) as $field )
1866 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1867 $post->filter = $context;
1868 } elseif ( is_array( $post ) ) {
1869 // Check if post already filtered for this context.
1870 if ( isset($post['filter']) && $context == $post['filter'] )
1872 if ( !isset($post['ID']) )
1874 foreach ( array_keys($post) as $field )
1875 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1876 $post['filter'] = $context;
1882 * Sanitize post field based on context.
1884 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and
1885 * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
1886 * are treated like 'display' when calling filters.
1889 * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
1891 * @param string $field The Post Object field name.
1892 * @param mixed $value The Post Object value.
1893 * @param int $post_id Post ID.
1894 * @param string $context Optional. How to sanitize post fields. Looks for 'raw', 'edit',
1895 * 'db', 'display', 'attribute' and 'js'. Default 'display'.
1896 * @return mixed Sanitized value.
1898 function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
1899 $int_fields = array('ID', 'post_parent', 'menu_order');
1900 if ( in_array($field, $int_fields) )
1901 $value = (int) $value;
1903 // Fields which contain arrays of integers.
1904 $array_int_fields = array( 'ancestors' );
1905 if ( in_array($field, $array_int_fields) ) {
1906 $value = array_map( 'absint', $value);
1910 if ( 'raw' == $context )
1914 if ( false !== strpos($field, 'post_') ) {
1916 $field_no_prefix = str_replace('post_', '', $field);
1919 if ( 'edit' == $context ) {
1920 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1925 * Filter the value of a specific post field to edit.
1927 * The dynamic portion of the hook name, `$field`, refers to the post
1932 * @param mixed $value Value of the post field.
1933 * @param int $post_id Post ID.
1935 $value = apply_filters( "edit_{$field}", $value, $post_id );
1938 * Filter the value of a specific post field to edit.
1940 * The dynamic portion of the hook name, `$field_no_prefix`, refers to
1941 * the post field name.
1945 * @param mixed $value Value of the post field.
1946 * @param int $post_id Post ID.
1948 $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
1950 $value = apply_filters( "edit_post_{$field}", $value, $post_id );
1953 if ( in_array($field, $format_to_edit) ) {
1954 if ( 'post_content' == $field )
1955 $value = format_to_edit($value, user_can_richedit());
1957 $value = format_to_edit($value);
1959 $value = esc_attr($value);
1961 } elseif ( 'db' == $context ) {
1965 * Filter the value of a specific post field before saving.
1967 * The dynamic portion of the hook name, `$field`, refers to the post
1972 * @param mixed $value Value of the post field.
1974 $value = apply_filters( "pre_{$field}", $value );
1977 * Filter the value of a specific field before saving.
1979 * The dynamic portion of the hook name, `$field_no_prefix`, refers
1980 * to the post field name.
1984 * @param mixed $value Value of the post field.
1986 $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
1988 $value = apply_filters( "pre_post_{$field}", $value );
1991 * Filter the value of a specific post field before saving.
1993 * The dynamic portion of the hook name, `$field`, refers to the post
1998 * @param mixed $value Value of the post field.
2000 $value = apply_filters( "{$field}_pre", $value );
2004 // Use display filters by default.
2008 * Filter the value of a specific post field for display.
2010 * The dynamic portion of the hook name, `$field`, refers to the post
2015 * @param mixed $value Value of the prefixed post field.
2016 * @param int $post_id Post ID.
2017 * @param string $context Context for how to sanitize the field. Possible
2018 * values include 'raw', 'edit', 'db', 'display',
2019 * 'attribute' and 'js'.
2021 $value = apply_filters( $field, $value, $post_id, $context );
2023 $value = apply_filters( "post_{$field}", $value, $post_id, $context );
2027 if ( 'attribute' == $context )
2028 $value = esc_attr($value);
2029 elseif ( 'js' == $context )
2030 $value = esc_js($value);
2036 * Make a post sticky.
2038 * Sticky posts should be displayed at the top of the front page.
2042 * @param int $post_id Post ID.
2044 function stick_post( $post_id ) {
2045 $stickies = get_option('sticky_posts');
2047 if ( !is_array($stickies) )
2048 $stickies = array($post_id);
2050 if ( ! in_array($post_id, $stickies) )
2051 $stickies[] = $post_id;
2053 update_option('sticky_posts', $stickies);
2059 * Sticky posts should be displayed at the top of the front page.
2063 * @param int $post_id Post ID.
2065 function unstick_post( $post_id ) {
2066 $stickies = get_option('sticky_posts');
2068 if ( !is_array($stickies) )
2071 if ( ! in_array($post_id, $stickies) )
2074 $offset = array_search($post_id, $stickies);
2075 if ( false === $offset )
2078 array_splice($stickies, $offset, 1);
2080 update_option('sticky_posts', $stickies);
2084 * Return the cache key for wp_count_posts() based on the passed arguments.
2088 * @param string $type Optional. Post type to retrieve count Default 'post'.
2089 * @param string $perm Optional. 'readable' or empty. Default empty.
2090 * @return string The cache key.
2092 function _count_posts_cache_key( $type = 'post', $perm = '' ) {
2093 $cache_key = 'posts-' . $type;
2094 if ( 'readable' == $perm && is_user_logged_in() ) {
2095 $post_type_object = get_post_type_object( $type );
2096 if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2097 $cache_key .= '_' . $perm . '_' . get_current_user_id();
2104 * Count number of posts of a post type and if user has permissions to view.
2106 * This function provides an efficient method of finding the amount of post's
2107 * type a blog has. Another method is to count the amount of items in
2108 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2109 * when developing for 2.5+, use this function instead.
2111 * The $perm parameter checks for 'readable' value and if the user can read
2112 * private posts, it will display that for the user that is signed in.
2116 * @global wpdb $wpdb WordPress database abstraction object.
2118 * @param string $type Optional. Post type to retrieve count. Default 'post'.
2119 * @param string $perm Optional. 'readable' or empty. Default empty.
2120 * @return object Number of posts for each status.
2122 function wp_count_posts( $type = 'post', $perm = '' ) {
2125 if ( ! post_type_exists( $type ) )
2126 return new stdClass;
2128 $cache_key = _count_posts_cache_key( $type, $perm );
2130 $counts = wp_cache_get( $cache_key, 'counts' );
2131 if ( false !== $counts ) {
2132 /** This filter is documented in wp-includes/post.php */
2133 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2136 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2137 if ( 'readable' == $perm && is_user_logged_in() ) {
2138 $post_type_object = get_post_type_object($type);
2139 if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2140 $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
2141 get_current_user_id()
2145 $query .= ' GROUP BY post_status';
2147 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2148 $counts = array_fill_keys( get_post_stati(), 0 );
2150 foreach ( $results as $row ) {
2151 $counts[ $row['post_status'] ] = $row['num_posts'];
2154 $counts = (object) $counts;
2155 wp_cache_set( $cache_key, $counts, 'counts' );
2158 * Modify returned post counts by status for the current post type.
2162 * @param object $counts An object containing the current post_type's post
2164 * @param string $type Post type.
2165 * @param string $perm The permission to determine if the posts are 'readable'
2166 * by the current user.
2168 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2172 * Count number of attachments for the mime type(s).
2174 * If you set the optional mime_type parameter, then an array will still be
2175 * returned, but will only have the item you are looking for. It does not give
2176 * you the number of attachments that are children of a post. You can get that
2177 * by counting the number of children that post has.
2181 * @global wpdb $wpdb WordPress database abstraction object.
2183 * @param string|array $mime_type Optional. Array or comma-separated list of
2184 * MIME patterns. Default empty.
2185 * @return object An object containing the attachment counts by mime type.
2187 function wp_count_attachments( $mime_type = '' ) {
2190 $and = wp_post_mime_type_where( $mime_type );
2191 $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 );
2194 foreach ( (array) $count as $row ) {
2195 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2197 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2200 * Modify returned attachment counts by mime type.
2204 * @param object $counts An object containing the attachment counts by
2206 * @param string $mime_type The mime type pattern used to filter the attachments
2209 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2213 * Get default post mime types.
2217 * @return array List of post mime types.
2219 function get_post_mime_types() {
2220 $post_mime_types = array( // array( adj, noun )
2221 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2222 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2223 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2227 * Filter the default list of post mime types.
2231 * @param array $post_mime_types Default list of post mime types.
2233 return apply_filters( 'post_mime_types', $post_mime_types );
2237 * Check a MIME-Type against a list.
2239 * If the wildcard_mime_types parameter is a string, it must be comma separated
2240 * list. If the real_mime_types is a string, it is also comma separated to
2245 * @param string|array $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
2246 * or flash (same as *flash*).
2247 * @param string|array $real_mime_types Real post mime type values.
2248 * @return array array(wildcard=>array(real types)).
2250 function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
2252 if ( is_string( $wildcard_mime_types ) ) {
2253 $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
2255 if ( is_string( $real_mime_types ) ) {
2256 $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
2259 $patternses = array();
2260 $wild = '[-._a-z0-9]*';
2262 foreach ( (array) $wildcard_mime_types as $type ) {
2263 $mimes = array_map( 'trim', explode( ',', $type ) );
2264 foreach ( $mimes as $mime ) {
2265 $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
2266 $patternses[][$type] = "^$regex$";
2267 if ( false === strpos( $mime, '/' ) ) {
2268 $patternses[][$type] = "^$regex/";
2269 $patternses[][$type] = $regex;
2273 asort( $patternses );
2275 foreach ( $patternses as $patterns ) {
2276 foreach ( $patterns as $type => $pattern ) {
2277 foreach ( (array) $real_mime_types as $real ) {
2278 if ( preg_match( "#$pattern#", $real ) && ( empty( $matches[$type] ) || false === array_search( $real, $matches[$type] ) ) ) {
2279 $matches[$type][] = $real;
2288 * Convert MIME types into SQL.
2292 * @param string|array $post_mime_types List of mime types or comma separated string
2294 * @param string $table_alias Optional. Specify a table alias, if needed.
2296 * @return string The SQL AND clause for mime searching.
2298 function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
2300 $wildcards = array('', '%', '%/%');
2301 if ( is_string($post_mime_types) )
2302 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2306 foreach ( (array) $post_mime_types as $mime_type ) {
2307 $mime_type = preg_replace('/\s/', '', $mime_type);
2308 $slashpos = strpos($mime_type, '/');
2309 if ( false !== $slashpos ) {
2310 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2311 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2312 if ( empty($mime_subgroup) )
2313 $mime_subgroup = '*';
2315 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2316 $mime_pattern = "$mime_group/$mime_subgroup";
2318 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2319 if ( false === strpos($mime_pattern, '*') )
2320 $mime_pattern .= '/*';
2323 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2325 if ( in_array( $mime_type, $wildcards ) )
2328 if ( false !== strpos($mime_pattern, '%') )
2329 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2331 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2333 if ( !empty($wheres) )
2334 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2339 * Trash or delete a post or page.
2341 * When the post and page is permanently deleted, everything that is tied to
2342 * it is deleted also. This includes comments, post meta fields, and terms
2343 * associated with the post.
2345 * The post or page is moved to trash instead of permanently deleted unless
2346 * trash is disabled, item is already in the trash, or $force_delete is true.
2350 * @global wpdb $wpdb WordPress database abstraction object.
2351 * @see wp_delete_attachment()
2352 * @see wp_trash_post()
2354 * @param int $postid Optional. Post ID. Default 0.
2355 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
2357 * @return array|false|WP_Post False on failure.
2359 function wp_delete_post( $postid = 0, $force_delete = false ) {
2362 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2365 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2366 return wp_trash_post( $postid );
2368 if ( $post->post_type == 'attachment' )
2369 return wp_delete_attachment( $postid, $force_delete );
2372 * Filter whether a post deletion should take place.
2376 * @param bool $delete Whether to go forward with deletion.
2377 * @param WP_Post $post Post object.
2378 * @param bool $force_delete Whether to bypass the trash.
2380 $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
2381 if ( null !== $check ) {
2386 * Fires before a post is deleted, at the start of wp_delete_post().
2390 * @see wp_delete_post()
2392 * @param int $postid Post ID.
2394 do_action( 'before_delete_post', $postid );
2396 delete_post_meta($postid,'_wp_trash_meta_status');
2397 delete_post_meta($postid,'_wp_trash_meta_time');
2399 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2401 $parent_data = array( 'post_parent' => $post->post_parent );
2402 $parent_where = array( 'post_parent' => $postid );
2404 if ( is_post_type_hierarchical( $post->post_type ) ) {
2405 // Point children of this page to its parent, also clean the cache of affected children.
2406 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2407 $children = $wpdb->get_results( $children_query );
2409 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2412 // Do raw query. wp_get_post_revisions() is filtered.
2413 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2414 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2415 foreach ( $revision_ids as $revision_id )
2416 wp_delete_post_revision( $revision_id );
2418 // Point all attachments to this post up one level.
2419 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2421 wp_defer_comment_counting( true );
2423 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2424 foreach ( $comment_ids as $comment_id ) {
2425 wp_delete_comment( $comment_id, true );
2428 wp_defer_comment_counting( false );
2430 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2431 foreach ( $post_meta_ids as $mid )
2432 delete_metadata_by_mid( 'post', $mid );
2435 * Fires immediately before a post is deleted from the database.
2439 * @param int $postid Post ID.
2441 do_action( 'delete_post', $postid );
2442 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2448 * Fires immediately after a post is deleted from the database.
2452 * @param int $postid Post ID.
2454 do_action( 'deleted_post', $postid );
2456 clean_post_cache( $post );
2458 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2459 foreach ( $children as $child )
2460 clean_post_cache( $child );
2463 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2466 * Fires after a post is deleted, at the conclusion of wp_delete_post().
2470 * @see wp_delete_post()
2472 * @param int $postid Post ID.
2474 do_action( 'after_delete_post', $postid );
2480 * Reset the page_on_front, show_on_front, and page_for_post settings when
2481 * a linked page is deleted or trashed.
2483 * Also ensures the post is no longer sticky.
2488 * @param int $post_id Post ID.
2490 function _reset_front_page_settings_for_post( $post_id ) {
2491 $post = get_post( $post_id );
2492 if ( 'page' == $post->post_type ) {
2494 * If the page is defined in option page_on_front or post_for_posts,
2495 * adjust the corresponding options.
2497 if ( get_option( 'page_on_front' ) == $post->ID ) {
2498 update_option( 'show_on_front', 'posts' );
2499 update_option( 'page_on_front', 0 );
2501 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2502 delete_option( 'page_for_posts', 0 );
2505 unstick_post( $post->ID );
2509 * Move a post or page to the Trash
2511 * If trash is disabled, the post or page is permanently deleted.
2515 * @see wp_delete_post()
2517 * @param int $post_id Optional. Post ID. Default is ID of the global $post
2518 * if EMPTY_TRASH_DAYS equals true.
2519 * @return false|array|WP_Post|null Post data array, otherwise false.
2521 function wp_trash_post( $post_id = 0 ) {
2522 if ( !EMPTY_TRASH_DAYS )
2523 return wp_delete_post($post_id, true);
2525 if ( !$post = get_post($post_id, ARRAY_A) )
2528 if ( $post['post_status'] == 'trash' )
2532 * Fires before a post is sent to the trash.
2536 * @param int $post_id Post ID.
2538 do_action( 'wp_trash_post', $post_id );
2540 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2541 add_post_meta($post_id,'_wp_trash_meta_time', time());
2543 $post['post_status'] = 'trash';
2544 wp_insert_post( wp_slash( $post ) );
2546 wp_trash_post_comments($post_id);
2549 * Fires after a post is sent to the trash.
2553 * @param int $post_id Post ID.
2555 do_action( 'trashed_post', $post_id );
2561 * Restore a post or page from the Trash.
2565 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2566 * @return WP_Post|false WP_Post object. False on failure.
2568 function wp_untrash_post( $post_id = 0 ) {
2569 if ( !$post = get_post($post_id, ARRAY_A) )
2572 if ( $post['post_status'] != 'trash' )
2576 * Fires before a post is restored from the trash.
2580 * @param int $post_id Post ID.
2582 do_action( 'untrash_post', $post_id );
2584 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2586 $post['post_status'] = $post_status;
2588 delete_post_meta($post_id, '_wp_trash_meta_status');
2589 delete_post_meta($post_id, '_wp_trash_meta_time');
2591 wp_insert_post( wp_slash( $post ) );
2593 wp_untrash_post_comments($post_id);
2596 * Fires after a post is restored from the trash.
2600 * @param int $post_id Post ID.
2602 do_action( 'untrashed_post', $post_id );
2608 * Moves comments for a post to the trash.
2612 * @global wpdb $wpdb WordPress database abstraction object.
2614 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2615 * @return mixed|void False on failure.
2617 function wp_trash_post_comments( $post = null ) {
2620 $post = get_post($post);
2624 $post_id = $post->ID;
2627 * Fires before comments are sent to the trash.
2631 * @param int $post_id Post ID.
2633 do_action( 'trash_post_comments', $post_id );
2635 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2636 if ( empty($comments) )
2639 // Cache current status for each comment.
2640 $statuses = array();
2641 foreach ( $comments as $comment )
2642 $statuses[$comment->comment_ID] = $comment->comment_approved;
2643 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2645 // Set status for all comments to post-trashed.
2646 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2648 clean_comment_cache( array_keys($statuses) );
2651 * Fires after comments are sent to the trash.
2655 * @param int $post_id Post ID.
2656 * @param array $statuses Array of comment statuses.
2658 do_action( 'trashed_post_comments', $post_id, $statuses );
2664 * Restore comments for a post from the trash.
2668 * @global wpdb $wpdb WordPress database abstraction object.
2670 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2673 function wp_untrash_post_comments( $post = null ) {
2676 $post = get_post($post);
2680 $post_id = $post->ID;
2682 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2684 if ( empty($statuses) )
2688 * Fires before comments are restored for a post from the trash.
2692 * @param int $post_id Post ID.
2694 do_action( 'untrash_post_comments', $post_id );
2696 // Restore each comment to its original status.
2697 $group_by_status = array();
2698 foreach ( $statuses as $comment_id => $comment_status )
2699 $group_by_status[$comment_status][] = $comment_id;
2701 foreach ( $group_by_status as $status => $comments ) {
2702 // Sanity check. This shouldn't happen.
2703 if ( 'post-trashed' == $status ) {
2706 $comments_in = implode( ', ', array_map( 'intval', $comments ) );
2707 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
2710 clean_comment_cache( array_keys($statuses) );
2712 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2715 * Fires after comments are restored for a post from the trash.
2719 * @param int $post_id Post ID.
2721 do_action( 'untrashed_post_comments', $post_id );
2725 * Retrieve the list of categories for a post.
2727 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2728 * away from the complexity of the taxonomy layer.
2732 * @see wp_get_object_terms()
2734 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2735 * global $post. Default 0.
2736 * @param array $args Optional. Category arguments. Default empty.
2737 * @return array List of categories.
2739 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2740 $post_id = (int) $post_id;
2742 $defaults = array('fields' => 'ids');
2743 $args = wp_parse_args( $args, $defaults );
2745 $cats = wp_get_object_terms($post_id, 'category', $args);
2750 * Retrieve the tags for a post.
2752 * There is only one default for this function, called 'fields' and by default
2753 * is set to 'all'. There are other defaults that can be overridden in
2754 * {@link wp_get_object_terms()}.
2758 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2759 * global $post. Default 0.
2760 * @param array $args Optional. Overwrite the defaults
2761 * @return array List of post tags.
2763 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2764 return wp_get_post_terms( $post_id, 'post_tag', $args);
2768 * Retrieve the terms for a post.
2770 * There is only one default for this function, called 'fields' and by default
2771 * is set to 'all'. There are other defaults that can be overridden in
2772 * {@link wp_get_object_terms()}.
2776 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2777 * global $post. Default 0.
2778 * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
2779 * @param array $args Optional. {@link wp_get_object_terms()} arguments. Default empty array.
2780 * @return array|WP_Error List of post terms or empty array if no terms were found. WP_Error object
2781 * if `$taxonomy` doesn't exist.
2783 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2784 $post_id = (int) $post_id;
2786 $defaults = array('fields' => 'all');
2787 $args = wp_parse_args( $args, $defaults );
2789 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2795 * Retrieve a number of recent posts.
2801 * @param array $args Optional. Arguments to retrieve posts. Default empty array.
2802 * @param string $output Optional. Type of output. Accepts ARRAY_A or ''. Default ARRAY_A.
2803 * @return array|false Associative array if $output equals ARRAY_A, array or false if no results.
2805 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2807 if ( is_numeric( $args ) ) {
2808 _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2809 $args = array( 'numberposts' => absint( $args ) );
2812 // Set default arguments.
2814 'numberposts' => 10, 'offset' => 0,
2815 'category' => 0, 'orderby' => 'post_date',
2816 'order' => 'DESC', 'include' => '',
2817 'exclude' => '', 'meta_key' => '',
2818 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2819 'suppress_filters' => true
2822 $r = wp_parse_args( $args, $defaults );
2824 $results = get_posts( $r );
2826 // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
2827 if ( ARRAY_A == $output ){
2828 foreach ( $results as $key => $result ) {
2829 $results[$key] = get_object_vars( $result );
2831 return $results ? $results : array();
2834 return $results ? $results : false;
2839 * Insert or update a post.
2841 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2843 * You can set the post date manually, by setting the values for 'post_date'
2844 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2845 * setting the value for 'comment_status' key.
2848 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
2849 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
2851 * @see sanitize_post()
2852 * @global wpdb $wpdb WordPress database abstraction object.
2854 * @param array $postarr {
2855 * An array of elements that make up a post to update or insert.
2857 * @type int $ID The post ID. If equal to something other than 0,
2858 * the post with that ID will be updated. Default 0.
2859 * @type int $post_author The ID of the user who added the post. Default is
2860 * the current user ID.
2861 * @type string $post_date The date of the post. Default is the current time.
2862 * @type string $post_date_gmt The date of the post in the GMT timezone. Default is
2863 * the value of `$post_date`.
2864 * @type mixed $post_content The post content. Default empty.
2865 * @type string $post_content_filtered The filtered post content. Default empty.
2866 * @type string $post_title The post title. Default empty.
2867 * @type string $post_excerpt The post excerpt. Default empty.
2868 * @type string $post_status The post status. Default 'draft'.
2869 * @type string $post_type The post type. Default 'post'.
2870 * @type string $comment_status Whether the post can accept comments. Accepts 'open' or 'closed'.
2871 * Default is the value of 'default_comment_status' option.
2872 * @type string $ping_status Whether the post can accept pings. Accepts 'open' or 'closed'.
2873 * Default is the value of 'default_ping_status' option.
2874 * @type string $post_password The password to access the post. Default empty.
2875 * @type string $post_name The post name. Default is the sanitized post title.
2876 * @type string $to_ping Space or carriage return-separated list of URLs to ping.
2878 * @type string $pinged Space or carriage return-separated list of URLs that have
2879 * been pinged. Default empty.
2880 * @type string $post_modified The date when the post was last modified. Default is
2882 * @type string $post_modified_gmt The date when the post was last modified in the GMT
2883 * timezone. Default is the current time.
2884 * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
2885 * @type int $menu_order The order the post should be displayed in. Default 0.
2886 * @type string $post_mime_type The mime type of the post. Default empty.
2887 * @type string $guid Global Unique ID for referencing the post. Default empty.
2888 * @type array $tax_input Array of taxonomy terms keyed by their taxonomy name. Default empty.
2889 * @type array $meta_input Array of post meta values keyed by their post meta key. Default empty.
2891 * @param bool $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
2892 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2894 function wp_insert_post( $postarr, $wp_error = false ) {
2897 $user_id = get_current_user_id();
2900 'post_author' => $user_id,
2901 'post_content' => '',
2902 'post_content_filtered' => '',
2904 'post_excerpt' => '',
2905 'post_status' => 'draft',
2906 'post_type' => 'post',
2907 'comment_status' => '',
2908 'ping_status' => '',
2909 'post_password' => '',
2919 $postarr = wp_parse_args($postarr, $defaults);
2921 unset( $postarr[ 'filter' ] );
2923 $postarr = sanitize_post($postarr, 'db');
2925 // Are we updating or creating?
2928 $guid = $postarr['guid'];
2930 if ( ! empty( $postarr['ID'] ) ) {
2933 // Get the post ID and GUID.
2934 $post_ID = $postarr['ID'];
2935 $post_before = get_post( $post_ID );
2936 if ( is_null( $post_before ) ) {
2938 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2943 $guid = get_post_field( 'guid', $post_ID );
2944 $previous_status = get_post_field('post_status', $post_ID );
2946 $previous_status = 'new';
2949 $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
2951 $post_title = $postarr['post_title'];
2952 $post_content = $postarr['post_content'];
2953 $post_excerpt = $postarr['post_excerpt'];
2954 if ( isset( $postarr['post_name'] ) ) {
2955 $post_name = $postarr['post_name'];
2958 $maybe_empty = 'attachment' !== $post_type
2959 && ! $post_content && ! $post_title && ! $post_excerpt
2960 && post_type_supports( $post_type, 'editor' )
2961 && post_type_supports( $post_type, 'title' )
2962 && post_type_supports( $post_type, 'excerpt' );
2965 * Filter whether the post should be considered "empty".
2967 * The post is considered "empty" if both:
2968 * 1. The post type supports the title, editor, and excerpt fields
2969 * 2. The title, editor, and excerpt fields are all empty
2971 * Returning a truthy value to the filter will effectively short-circuit
2972 * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
2973 * will be returned instead.
2977 * @param bool $maybe_empty Whether the post should be considered "empty".
2978 * @param array $postarr Array of post data.
2980 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2982 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2988 $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
2989 if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash' ) ) ) {
2990 $post_status = 'inherit';
2993 if ( ! empty( $postarr['post_category'] ) ) {
2994 // Filter out empty terms.
2995 $post_category = array_filter( $postarr['post_category'] );
2998 // Make sure we set a valid category.
2999 if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
3000 // 'post' requires at least one category.
3001 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3002 $post_category = array( get_option('default_category') );
3004 $post_category = array();
3008 // Don't allow contributors to set the post slug for pending review posts.
3009 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
3014 * Create a valid post name. Drafts and pending posts are allowed to have
3015 * an empty post name.
3017 if ( empty($post_name) ) {
3018 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3019 $post_name = sanitize_title($post_title);
3024 // On updates, we need to check to see if it's using the old, fixed sanitization context.
3025 $check_name = sanitize_title( $post_name, '', 'old-save' );
3026 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
3027 $post_name = $check_name;
3028 } else { // new post, or slug has changed.
3029 $post_name = sanitize_title($post_name);
3034 * If the post date is empty (due to having been new or a draft) and status
3035 * is not 'draft' or 'pending', set date to now.
3037 if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
3038 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3039 $post_date = current_time( 'mysql' );
3041 $post_date = get_date_from_gmt( $postarr['post_date_gmt'] );
3044 $post_date = $postarr['post_date'];
3047 // Validate the date.
3048 $mm = substr( $post_date, 5, 2 );
3049 $jj = substr( $post_date, 8, 2 );
3050 $aa = substr( $post_date, 0, 4 );
3051 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
3052 if ( ! $valid_date ) {
3054 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
3060 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3061 if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3062 $post_date_gmt = get_gmt_from_date( $post_date );
3064 $post_date_gmt = '0000-00-00 00:00:00';
3067 $post_date_gmt = $postarr['post_date_gmt'];
3070 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
3071 $post_modified = current_time( 'mysql' );
3072 $post_modified_gmt = current_time( 'mysql', 1 );
3074 $post_modified = $post_date;
3075 $post_modified_gmt = $post_date_gmt;
3078 if ( 'attachment' !== $post_type ) {
3079 if ( 'publish' == $post_status ) {
3080 $now = gmdate('Y-m-d H:i:59');
3081 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
3082 $post_status = 'future';
3084 } elseif ( 'future' == $post_status ) {
3085 $now = gmdate('Y-m-d H:i:59');
3086 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) {
3087 $post_status = 'publish';
3093 if ( empty( $postarr['comment_status'] ) ) {
3095 $comment_status = 'closed';
3097 $comment_status = get_default_comment_status( $post_type );
3100 $comment_status = $postarr['comment_status'];
3103 // These variables are needed by compact() later.
3104 $post_content_filtered = $postarr['post_content_filtered'];
3105 $post_author = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
3106 $ping_status = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
3107 $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
3108 $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
3109 $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
3112 * The 'wp_insert_post_parent' filter expects all variables to be present.
3113 * Previously, these variables would have already been extracted
3115 if ( isset( $postarr['menu_order'] ) ) {
3116 $menu_order = (int) $postarr['menu_order'];
3121 $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
3122 if ( 'private' == $post_status ) {
3123 $post_password = '';
3126 if ( isset( $postarr['post_parent'] ) ) {
3127 $post_parent = (int) $postarr['post_parent'];
3133 * Filter the post parent -- used to check for and prevent hierarchy loops.
3137 * @param int $post_parent Post parent ID.
3138 * @param int $post_ID Post ID.
3139 * @param array $new_postarr Array of parsed post data.
3140 * @param array $postarr Array of sanitized, but otherwise unmodified post data.
3142 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
3144 $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
3147 $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
3149 // Expected_slashed (everything!).
3150 $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' );
3152 $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
3154 foreach ( $emoji_fields as $emoji_field ) {
3155 if ( isset( $data[ $emoji_field ] ) ) {
3156 $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
3157 if ( 'utf8' === $charset ) {
3158 $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
3163 if ( 'attachment' === $post_type ) {
3165 * Filter attachment post data before it is updated in or added to the database.
3169 * @param array $data An array of sanitized attachment post data.
3170 * @param array $postarr An array of unsanitized attachment post data.
3172 $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
3175 * Filter slashed post data just before it is inserted into the database.
3179 * @param array $data An array of slashed post data.
3180 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3182 $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
3184 $data = wp_unslash( $data );
3185 $where = array( 'ID' => $post_ID );
3189 * Fires immediately before an existing post is updated in the database.
3193 * @param int $post_ID Post ID.
3194 * @param array $data Array of unslashed post data.
3196 do_action( 'pre_post_update', $post_ID, $data );
3197 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
3199 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
3205 // If there is a suggested ID, use it if not already present.
3206 if ( ! empty( $import_id ) ) {
3207 $import_id = (int) $import_id;
3208 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3209 $data['ID'] = $import_id;
3212 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
3214 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
3219 $post_ID = (int) $wpdb->insert_id;
3221 // Use the newly generated $post_ID.
3222 $where = array( 'ID' => $post_ID );
3225 if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
3226 $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_ID ), $post_ID, $data['post_status'], $post_type, $post_parent );
3227 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
3228 clean_post_cache( $post_ID );
3231 if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
3232 wp_set_post_categories( $post_ID, $post_category );
3235 if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
3236 wp_set_post_tags( $post_ID, $postarr['tags_input'] );
3239 // New-style support for all custom taxonomies.
3240 if ( ! empty( $postarr['tax_input'] ) ) {
3241 foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
3242 $taxonomy_obj = get_taxonomy($taxonomy);
3243 if ( ! $taxonomy_obj ) {
3244 /* translators: %s: taxonomy name */
3245 _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
3249 // array = hierarchical, string = non-hierarchical.
3250 if ( is_array( $tags ) ) {
3251 $tags = array_filter($tags);
3253 if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
3254 wp_set_post_terms( $post_ID, $tags, $taxonomy );
3259 if ( ! empty( $postarr['meta_input'] ) ) {
3260 foreach ( $postarr['meta_input'] as $field => $value ) {
3261 update_post_meta( $post_ID, $field, $value );
3265 $current_guid = get_post_field( 'guid', $post_ID );
3268 if ( ! $update && '' == $current_guid ) {
3269 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
3272 if ( 'attachment' === $postarr['post_type'] ) {
3273 if ( ! empty( $postarr['file'] ) ) {
3274 update_attached_file( $post_ID, $postarr['file'] );
3277 if ( ! empty( $postarr['context'] ) ) {
3278 add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
3282 clean_post_cache( $post_ID );
3284 $post = get_post( $post_ID );
3286 if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
3287 $post->page_template = $postarr['page_template'];
3288 $page_templates = wp_get_theme()->get_page_templates( $post );
3289 if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
3291 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
3293 update_post_meta( $post_ID, '_wp_page_template', 'default' );
3295 update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
3299 if ( 'attachment' !== $postarr['post_type'] ) {
3300 wp_transition_post_status( $data['post_status'], $previous_status, $post );
3304 * Fires once an existing attachment has been updated.
3308 * @param int $post_ID Attachment ID.
3310 do_action( 'edit_attachment', $post_ID );
3311 $post_after = get_post( $post_ID );
3314 * Fires once an existing attachment has been updated.
3318 * @param int $post_ID Post ID.
3319 * @param WP_Post $post_after Post object following the update.
3320 * @param WP_Post $post_before Post object before the update.
3322 do_action( 'attachment_updated', $post_ID, $post_after, $post_before );
3326 * Fires once an attachment has been added.
3330 * @param int $post_ID Attachment ID.
3332 do_action( 'add_attachment', $post_ID );
3340 * Fires once an existing post has been updated.
3344 * @param int $post_ID Post ID.
3345 * @param WP_Post $post Post object.
3347 do_action( 'edit_post', $post_ID, $post );
3348 $post_after = get_post($post_ID);
3351 * Fires once an existing post has been updated.
3355 * @param int $post_ID Post ID.
3356 * @param WP_Post $post_after Post object following the update.
3357 * @param WP_Post $post_before Post object before the update.
3359 do_action( 'post_updated', $post_ID, $post_after, $post_before);
3363 * Fires once a post has been saved.
3365 * The dynamic portion of the hook name, `$post->post_type`, refers to
3366 * the post type slug.
3370 * @param int $post_ID Post ID.
3371 * @param WP_Post $post Post object.
3372 * @param bool $update Whether this is an existing post being updated or not.
3374 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
3377 * Fires once a post has been saved.
3381 * @param int $post_ID Post ID.
3382 * @param WP_Post $post Post object.
3383 * @param bool $update Whether this is an existing post being updated or not.
3385 do_action( 'save_post', $post_ID, $post, $update );
3388 * Fires once a post has been saved.
3392 * @param int $post_ID Post ID.
3393 * @param WP_Post $post Post object.
3394 * @param bool $update Whether this is an existing post being updated or not.
3396 do_action( 'wp_insert_post', $post_ID, $post, $update );
3402 * Update a post with new post data.
3404 * The date does not have to be set for drafts. You can set the date and it will
3405 * not be overridden.
3409 * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
3410 * objects are not. Default array.
3411 * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
3412 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
3414 function wp_update_post( $postarr = array(), $wp_error = false ) {
3415 if ( is_object($postarr) ) {
3416 // Non-escaped post was passed.
3417 $postarr = get_object_vars($postarr);
3418 $postarr = wp_slash($postarr);
3421 // First, get all of the original fields.
3422 $post = get_post($postarr['ID'], ARRAY_A);
3424 if ( is_null( $post ) ) {
3426 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3430 // Escape data pulled from DB.
3431 $post = wp_slash($post);
3433 // Passed post category list overwrites existing category list if not empty.
3434 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3435 && 0 != count($postarr['post_category']) )
3436 $post_cats = $postarr['post_category'];
3438 $post_cats = $post['post_category'];
3440 // Drafts shouldn't be assigned a date unless explicitly done so by the user.
3441 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3442 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3445 $clear_date = false;
3447 // Merge old and new fields with new fields overwriting old ones.
3448 $postarr = array_merge($post, $postarr);
3449 $postarr['post_category'] = $post_cats;
3450 if ( $clear_date ) {
3451 $postarr['post_date'] = current_time('mysql');
3452 $postarr['post_date_gmt'] = '';
3455 if ($postarr['post_type'] == 'attachment')
3456 return wp_insert_attachment($postarr);
3458 return wp_insert_post( $postarr, $wp_error );
3462 * Publish a post by transitioning the post status.
3466 * @global wpdb $wpdb WordPress database abstraction object.
3468 * @param int|WP_Post $post Post ID or post object.
3470 function wp_publish_post( $post ) {
3473 if ( ! $post = get_post( $post ) )
3476 if ( 'publish' == $post->post_status )
3479 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3481 clean_post_cache( $post->ID );
3483 $old_status = $post->post_status;
3484 $post->post_status = 'publish';
3485 wp_transition_post_status( 'publish', $old_status, $post );
3487 /** This action is documented in wp-includes/post.php */
3488 do_action( 'edit_post', $post->ID, $post );
3490 /** This action is documented in wp-includes/post.php */
3491 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3493 /** This action is documented in wp-includes/post.php */
3494 do_action( 'save_post', $post->ID, $post, true );
3496 /** This action is documented in wp-includes/post.php */
3497 do_action( 'wp_insert_post', $post->ID, $post, true );
3501 * Publish future post and make sure post ID has future post status.
3503 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3504 * from publishing drafts, etc.
3508 * @param int|WP_Post $post_id Post ID or post object.
3510 function check_and_publish_future_post( $post_id ) {
3511 $post = get_post($post_id);
3516 if ( 'future' != $post->post_status )
3519 $time = strtotime( $post->post_date_gmt . ' GMT' );
3521 // Uh oh, someone jumped the gun!
3522 if ( $time > time() ) {
3523 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3524 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3528 // wp_publish_post(_ returns no meaningful value.
3529 wp_publish_post( $post_id );
3533 * Computes a unique slug for the post, when given the desired slug and some post details.
3537 * @global wpdb $wpdb WordPress database abstraction object.
3538 * @global WP_Rewrite $wp_rewrite
3540 * @param string $slug The desired slug (post_name).
3541 * @param int $post_ID Post ID.
3542 * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
3543 * @param string $post_type Post type.
3544 * @param int $post_parent Post parent ID.
3545 * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3547 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3548 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3551 global $wpdb, $wp_rewrite;
3553 $original_slug = $slug;
3555 $feeds = $wp_rewrite->feeds;
3556 if ( ! is_array( $feeds ) )
3559 if ( 'attachment' == $post_type ) {
3560 // Attachment slugs must be unique across all types.
3561 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3562 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3565 * Filter whether the post slug would make a bad attachment slug.
3569 * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
3570 * @param string $slug The post slug.
3572 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3575 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3576 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3578 } while ( $post_name_check );
3579 $slug = $alt_post_name;
3581 } elseif ( is_post_type_hierarchical( $post_type ) ) {
3582 if ( 'nav_menu_item' == $post_type )
3586 * Page slugs must be unique within their own trees. Pages are in a separate
3587 * namespace than posts so page slugs are allowed to overlap post slugs.
3589 $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";
3590 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
3593 * Filter whether the post slug would make a bad hierarchical post slug.
3597 * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
3598 * @param string $slug The post slug.
3599 * @param string $post_type Post type.
3600 * @param int $post_parent Post parent ID.
3602 if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
3605 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3606 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
3608 } while ( $post_name_check );
3609 $slug = $alt_post_name;
3612 // Post slugs must be unique across all posts.
3613 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3614 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3616 // Prevent new post slugs that could result in URLs that conflict with date archives.
3617 $post = get_post( $post_ID );
3618 $conflicts_with_date_archive = false;
3619 if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) && $slug_num = intval( $slug ) ) {
3620 $permastructs = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
3621 $postname_index = array_search( '%postname%', $permastructs );
3624 * Potential date clashes are as follows:
3626 * - Any integer in the first permastruct position could be a year.
3627 * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
3628 * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
3630 if ( 0 === $postname_index ||
3631 ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
3632 ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
3634 $conflicts_with_date_archive = true;
3639 * Filter whether the post slug would be bad as a flat slug.
3643 * @param bool $bad_slug Whether the post slug would be bad as a flat slug.
3644 * @param string $slug The post slug.
3645 * @param string $post_type Post type.
3647 if ( $post_name_check || in_array( $slug, $feeds ) || $conflicts_with_date_archive || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3650 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3651 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3653 } while ( $post_name_check );
3654 $slug = $alt_post_name;
3659 * Filter the unique post slug.
3663 * @param string $slug The post slug.
3664 * @param int $post_ID Post ID.
3665 * @param string $post_status The post status.
3666 * @param string $post_type Post type.
3667 * @param int $post_parent Post parent ID
3668 * @param string $original_slug The original post slug.
3670 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3674 * Truncate a post slug.
3679 * @see utf8_uri_encode()
3681 * @param string $slug The slug to truncate.
3682 * @param int $length Optional. Max length of the slug. Default 200 (characters).
3683 * @return string The truncated slug.
3685 function _truncate_post_slug( $slug, $length = 200 ) {
3686 if ( strlen( $slug ) > $length ) {
3687 $decoded_slug = urldecode( $slug );
3688 if ( $decoded_slug === $slug )
3689 $slug = substr( $slug, 0, $length );
3691 $slug = utf8_uri_encode( $decoded_slug, $length );
3694 return rtrim( $slug, '-' );
3698 * Add tags to a post.
3700 * @see wp_set_post_tags()
3704 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3705 * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
3706 * separated by commas. Default empty.
3707 * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3709 function wp_add_post_tags( $post_id = 0, $tags = '' ) {
3710 return wp_set_post_tags($post_id, $tags, true);
3714 * Set the tags for a post.
3718 * @see wp_set_object_terms()
3720 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3721 * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
3722 * separated by commas. Default empty.
3723 * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
3724 * replace the tags with the new tags. Default false.
3725 * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3727 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3728 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3732 * Set the terms for a post.
3736 * @see wp_set_object_terms()
3738 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3739 * @param string|array $tags Optional. An array of terms to set for the post, or a string of terms
3740 * separated by commas. Default empty.
3741 * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
3742 * @param bool $append Optional. If true, don't delete existing terms, just add on. If false,
3743 * replace the terms with the new terms. Default false.
3744 * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3746 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3747 $post_id = (int) $post_id;
3755 if ( ! is_array( $tags ) ) {
3756 $comma = _x( ',', 'tag delimiter' );
3757 if ( ',' !== $comma )
3758 $tags = str_replace( $comma, ',', $tags );
3759 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3763 * Hierarchical taxonomies must always pass IDs rather than names so that
3764 * children with the same names but different parents aren't confused.
3766 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3767 $tags = array_unique( array_map( 'intval', $tags ) );
3770 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3774 * Set categories for a post.
3776 * If the post categories parameter is not set, then the default category is
3781 * @param int $post_ID Optional. The Post ID. Does not default to the ID
3782 * of the global $post. Default 0.
3783 * @param array|int $post_categories Optional. List of categories or ID of category.
3784 * Default empty array.
3785 * @param bool $append If true, don't delete existing categories, just add on.
3786 * If false, replace the categories with the new categories.
3787 * @return array|bool|WP_Error
3789 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3790 $post_ID = (int) $post_ID;
3791 $post_type = get_post_type( $post_ID );
3792 $post_status = get_post_status( $post_ID );
3793 // If $post_categories isn't already an array, make it one:
3794 $post_categories = (array) $post_categories;
3795 if ( empty( $post_categories ) ) {
3796 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3797 $post_categories = array( get_option('default_category') );
3800 $post_categories = array();
3802 } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) {
3806 return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3810 * Fires actions related to the transitioning of a post's status.
3812 * When a post is saved, the post status is "transitioned" from one status to another,
3813 * though this does not always mean the status has actually changed before and after
3814 * the save. This function fires a number of action hooks related to that transition:
3815 * the generic 'transition_post_status' action, as well as the dynamic hooks
3816 * `"{$old_status}_to_{$new_status}"` and `"{$new_status}_{$post->post_type}"`. Note
3817 * that the function does not transition the post object in the database.
3819 * For instance: When publishing a post for the first time, the post status may transition
3820 * from 'draft' – or some other status – to 'publish'. However, if a post is already
3821 * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
3822 * before and after the transition.
3826 * @param string $new_status Transition to this post status.
3827 * @param string $old_status Previous post status.
3828 * @param WP_Post $post Post data.
3830 function wp_transition_post_status( $new_status, $old_status, $post ) {
3832 * Fires when a post is transitioned from one status to another.
3836 * @param string $new_status New post status.
3837 * @param string $old_status Old post status.
3838 * @param WP_Post $post Post object.
3840 do_action( 'transition_post_status', $new_status, $old_status, $post );
3843 * Fires when a post is transitioned from one status to another.
3845 * The dynamic portions of the hook name, `$new_status` and `$old status`,
3846 * refer to the old and new post statuses, respectively.
3850 * @param WP_Post $post Post object.
3852 do_action( "{$old_status}_to_{$new_status}", $post );
3855 * Fires when a post is transitioned from one status to another.
3857 * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
3858 * refer to the new post status and post type, respectively.
3860 * Please note: When this action is hooked using a particular post status (like
3861 * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
3862 * first transitioned to that status from something else, as well as upon
3863 * subsequent post updates (old and new status are both the same).
3865 * Therefore, if you are looking to only fire a callback when a post is first
3866 * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
3870 * @param int $post_id Post ID.
3871 * @param WP_Post $post Post object.
3873 do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
3877 // Comment, trackback, and pingback functions.
3881 * Add a URL to those already pinged.
3885 * @global wpdb $wpdb WordPress database abstraction object.
3887 * @param int $post_id Post ID.
3888 * @param string $uri Ping URI.
3889 * @return int|false How many rows were updated.
3891 function add_ping( $post_id, $uri ) {
3893 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3894 $pung = trim($pung);
3895 $pung = preg_split('/\s/', $pung);
3897 $new = implode("\n", $pung);
3900 * Filter the new ping URL to add for the given post.
3904 * @param string $new New ping URL to add.
3906 $new = apply_filters( 'add_ping', $new );
3908 // expected_slashed ($new).
3909 $new = wp_unslash($new);
3910 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3914 * Retrieve enclosures already enclosed for a post.
3918 * @param int $post_id Post ID.
3919 * @return array List of enclosures.
3921 function get_enclosed( $post_id ) {
3922 $custom_fields = get_post_custom( $post_id );
3924 if ( !is_array( $custom_fields ) )
3927 foreach ( $custom_fields as $key => $val ) {
3928 if ( 'enclosure' != $key || !is_array( $val ) )
3930 foreach ( $val as $enc ) {
3931 $enclosure = explode( "\n", $enc );
3932 $pung[] = trim( $enclosure[ 0 ] );
3937 * Filter the list of enclosures already enclosed for the given post.
3941 * @param array $pung Array of enclosures for the given post.
3942 * @param int $post_id Post ID.
3944 return apply_filters( 'get_enclosed', $pung, $post_id );
3948 * Retrieve URLs already pinged for a post.
3952 * @global wpdb $wpdb WordPress database abstraction object.
3954 * @param int $post_id Post ID.
3957 function get_pung( $post_id ) {
3959 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3960 $pung = trim($pung);
3961 $pung = preg_split('/\s/', $pung);
3964 * Filter the list of already-pinged URLs for the given post.
3968 * @param array $pung Array of URLs already pinged for the given post.
3970 return apply_filters( 'get_pung', $pung );
3974 * Retrieve URLs that need to be pinged.
3978 * @global wpdb $wpdb WordPress database abstraction object.
3980 * @param int $post_id Post ID
3983 function get_to_ping( $post_id ) {
3985 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
3986 $to_ping = sanitize_trackback_urls( $to_ping );
3987 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
3990 * Filter the list of URLs yet to ping for the given post.
3994 * @param array $to_ping List of URLs yet to ping.
3996 return apply_filters( 'get_to_ping', $to_ping );
4000 * Do trackbacks for a list of URLs.
4004 * @param string $tb_list Comma separated list of URLs.
4005 * @param int $post_id Post ID.
4007 function trackback_url_list( $tb_list, $post_id ) {
4008 if ( ! empty( $tb_list ) ) {
4010 $postdata = get_post( $post_id, ARRAY_A );
4013 $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
4015 if ( strlen( $excerpt ) > 255 ) {
4016 $excerpt = substr( $excerpt, 0, 252 ) . '…';
4019 $trackback_urls = explode( ',', $tb_list );
4020 foreach ( (array) $trackback_urls as $tb_url ) {
4021 $tb_url = trim( $tb_url );
4022 trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
4032 * Get a list of page IDs.
4036 * @global wpdb $wpdb WordPress database abstraction object.
4038 * @return array List of page IDs.
4040 function get_all_page_ids() {
4043 $page_ids = wp_cache_get('all_page_ids', 'posts');
4044 if ( ! is_array( $page_ids ) ) {
4045 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
4046 wp_cache_add('all_page_ids', $page_ids, 'posts');
4053 * Retrieves page data given a page ID or page object.
4055 * Use get_post() instead of get_page().
4058 * @deprecated 3.5.0 Use get_post()
4060 * @param mixed $page Page object or page ID. Passed by reference.
4061 * @param string $output Optional. What to output. Accepts OBJECT, ARRAY_A, or ARRAY_N.
4063 * @param string $filter Optional. How the return value should be filtered. Accepts 'raw',
4064 * 'edit', 'db', 'display'. Default 'raw'.
4065 * @return WP_Post|array|null WP_Post on success or null on failure.
4067 function get_page( $page, $output = OBJECT, $filter = 'raw') {
4068 return get_post( $page, $output, $filter );
4072 * Retrieves a page given its path.
4076 * @global wpdb $wpdb WordPress database abstraction object.
4078 * @param string $page_path Page path.
4079 * @param string $output Optional. Output type. Accepts OBJECT, ARRAY_N, or ARRAY_A.
4081 * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4082 * @return WP_Post|array|void WP_Post on success.
4084 function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
4087 $page_path = rawurlencode(urldecode($page_path));
4088 $page_path = str_replace('%2F', '/', $page_path);
4089 $page_path = str_replace('%20', ' ', $page_path);
4090 $parts = explode( '/', trim( $page_path, '/' ) );
4091 $parts = esc_sql( $parts );
4092 $parts = array_map( 'sanitize_title_for_query', $parts );
4094 $in_string = "'" . implode( "','", $parts ) . "'";
4096 if ( is_array( $post_type ) ) {
4097 $post_types = $post_type;
4099 $post_types = array( $post_type, 'attachment' );
4102 $post_types = esc_sql( $post_types );
4103 $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
4105 SELECT ID, post_name, post_parent, post_type
4107 WHERE post_name IN ($in_string)
4108 AND post_type IN ($post_type_in_string)
4111 $pages = $wpdb->get_results( $sql, OBJECT_K );
4113 $revparts = array_reverse( $parts );
4116 foreach ( (array) $pages as $page ) {
4117 if ( $page->post_name == $revparts[0] ) {
4120 while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
4122 $parent = $pages[ $p->post_parent ];
4123 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
4128 if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
4129 $foundid = $page->ID;
4130 if ( $page->post_type == $post_type )
4137 return get_post( $foundid, $output );
4142 * Retrieve a page given its title.
4146 * @global wpdb $wpdb WordPress database abstraction object.
4148 * @param string $page_title Page title
4149 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
4151 * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4152 * @return WP_Post|array|void WP_Post on success or null on failure
4154 function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
4157 if ( is_array( $post_type ) ) {
4158 $post_type = esc_sql( $post_type );
4159 $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
4160 $sql = $wpdb->prepare( "
4163 WHERE post_title = %s
4164 AND post_type IN ($post_type_in_string)
4167 $sql = $wpdb->prepare( "
4170 WHERE post_title = %s
4172 ", $page_title, $post_type );
4175 $page = $wpdb->get_var( $sql );
4178 return get_post( $page, $output );
4183 * Identify descendants of a given page ID in a list of page objects.
4185 * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
4189 * @param int $page_id Page ID.
4190 * @param array $pages List of page objects from which descendants should be identified.
4191 * @return array List of page children.
4193 function get_page_children( $page_id, $pages ) {
4194 // Build a hash of ID -> children.
4195 $children = array();
4196 foreach ( (array) $pages as $page ) {
4197 $children[ intval( $page->post_parent ) ][] = $page;
4200 $page_list = array();
4202 // Start the search by looking at immediate children.
4203 if ( isset( $children[ $page_id ] ) ) {
4204 // Always start at the end of the stack in order to preserve original `$pages` order.
4205 $to_look = array_reverse( $children[ $page_id ] );
4207 while ( $to_look ) {
4208 $p = array_pop( $to_look );
4210 if ( isset( $children[ $p->ID ] ) ) {
4211 foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
4212 // Append to the `$to_look` stack to descend the tree.
4213 $to_look[] = $child;
4223 * Order the pages with children under parents in a flat list.
4225 * It uses auxiliary structure to hold parent-children relationships and
4226 * runs in O(N) complexity
4230 * @param array $pages Posts array, passed by reference.
4231 * @param int $page_id Optional. Parent page ID. Default 0.
4232 * @return array A list arranged by hierarchy. Children immediately follow their parents.
4234 function get_page_hierarchy( &$pages, $page_id = 0 ) {
4235 if ( empty( $pages ) ) {
4239 $children = array();
4240 foreach ( (array) $pages as $p ) {
4241 $parent_id = intval( $p->post_parent );
4242 $children[ $parent_id ][] = $p;
4246 _page_traverse_name( $page_id, $children, $result );
4252 * Traverse and return all the nested children post names of a root page.
4254 * $children contains parent-children relations
4258 * @see _page_traverse_name()
4260 * @param int $page_id Page ID.
4261 * @param array &$children Parent-children relations, passed by reference.
4262 * @param array &$result Result, passed by reference.
4264 function _page_traverse_name( $page_id, &$children, &$result ){
4265 if ( isset( $children[ $page_id ] ) ){
4266 foreach ( (array)$children[ $page_id ] as $child ) {
4267 $result[ $child->ID ] = $child->post_name;
4268 _page_traverse_name( $child->ID, $children, $result );
4274 * Build URI for a page.
4276 * Sub pages will be in the "directory" under the parent page post name.
4280 * @param WP_Post|object|int $page Page object or page ID.
4281 * @return string|false Page URI, false on error.
4283 function get_page_uri( $page ) {
4284 $page = get_post( $page );
4289 $uri = $page->post_name;
4291 foreach ( $page->ancestors as $parent ) {
4292 $parent = get_post( $parent );
4294 $uri = $parent->post_name . '/' . $uri;
4299 * Filter the URI for a page.
4303 * @param string $uri Page URI.
4304 * @param WP_Post $page Page object.
4306 return apply_filters( 'get_page_uri', $uri, $page );
4310 * Retrieve a list of pages.
4312 * @global wpdb $wpdb WordPress database abstraction object.
4316 * @param array|string $args {
4317 * Optional. Array or string of arguments to retrieve pages.
4319 * @type int $child_of Page ID to return child and grandchild pages of. Note: The value
4320 * of `$hierarchical` has no bearing on whether `$child_of` returns
4321 * hierarchical results. Default 0, or no restriction.
4322 * @type string $sort_order How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
4323 * @type string $sort_column What columns to sort pages by, comma-separated. Accepts 'post_author',
4324 * 'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
4325 * 'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
4326 * 'post_' can be omitted for any values that start with it.
4327 * Default 'post_title'.
4328 * @type bool $hierarchical Whether to return pages hierarchically. If false in conjunction with
4329 * `$child_of` also being false, both arguments will be disregarded.
4331 * @type array $exclude Array of page IDs to exclude. Default empty array.
4332 * @type array $include Array of page IDs to include. Cannot be used with `$child_of`,
4333 * `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
4334 * Default empty array.
4335 * @type string $meta_key Only include pages with this meta key. Default empty.
4336 * @type string $meta_value Only include pages with this meta value. Requires `$meta_key`.
4338 * @type string $authors A comma-separated list of author IDs. Default empty.
4339 * @type int $parent Page ID to return direct children of. Default -1, or no restriction.
4340 * @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude.
4341 * Default empty array.
4342 * @type int $number The number of pages to return. Default 0, or all pages.
4343 * @type int $offset The number of pages to skip before returning. Requires `$number`.
4345 * @type string $post_type The post type to query. Default 'page'.
4346 * @type string $post_status A comma-separated list of post status types to include.
4347 * Default 'publish'.
4349 * @return array|false List of pages matching defaults or `$args`.
4351 function get_pages( $args = array() ) {
4355 'child_of' => 0, 'sort_order' => 'ASC',
4356 'sort_column' => 'post_title', 'hierarchical' => 1,
4357 'exclude' => array(), 'include' => array(),
4358 'meta_key' => '', 'meta_value' => '',
4359 'authors' => '', 'parent' => -1, 'exclude_tree' => array(),
4360 'number' => '', 'offset' => 0,
4361 'post_type' => 'page', 'post_status' => 'publish',
4364 $r = wp_parse_args( $args, $defaults );
4366 $number = (int) $r['number'];
4367 $offset = (int) $r['offset'];
4368 $child_of = (int) $r['child_of'];
4369 $hierarchical = $r['hierarchical'];
4370 $exclude = $r['exclude'];
4371 $meta_key = $r['meta_key'];
4372 $meta_value = $r['meta_value'];
4373 $parent = $r['parent'];
4374 $post_status = $r['post_status'];
4376 // Make sure the post type is hierarchical.
4377 $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
4378 if ( ! in_array( $r['post_type'], $hierarchical_post_types ) ) {
4382 if ( $parent > 0 && ! $child_of ) {
4383 $hierarchical = false;
4386 // Make sure we have a valid post status.
4387 if ( ! is_array( $post_status ) ) {
4388 $post_status = explode( ',', $post_status );
4390 if ( array_diff( $post_status, get_post_stati() ) ) {
4394 // $args can be whatever, only use the args defined in defaults to compute the key.
4395 $key = md5( serialize( wp_array_slice_assoc( $r, array_keys( $defaults ) ) ) );
4396 $last_changed = wp_cache_get( 'last_changed', 'posts' );
4397 if ( ! $last_changed ) {
4398 $last_changed = microtime();
4399 wp_cache_set( 'last_changed', $last_changed, 'posts' );
4402 $cache_key = "get_pages:$key:$last_changed";
4403 if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
4404 // Convert to WP_Post instances.
4405 $pages = array_map( 'get_post', $cache );
4406 /** This filter is documented in wp-includes/post.php */
4407 $pages = apply_filters( 'get_pages', $pages, $r );
4412 if ( ! empty( $r['include'] ) ) {
4413 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
4418 $hierarchical = false;
4419 $incpages = wp_parse_id_list( $r['include'] );
4420 if ( ! empty( $incpages ) ) {
4421 $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
4426 if ( ! empty( $exclude ) ) {
4427 $expages = wp_parse_id_list( $exclude );
4428 if ( ! empty( $expages ) ) {
4429 $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
4434 if ( ! empty( $r['authors'] ) ) {
4435 $post_authors = preg_split( '/[\s,]+/', $r['authors'] );
4437 if ( ! empty( $post_authors ) ) {
4438 foreach ( $post_authors as $post_author ) {
4439 //Do we have an author id or an author login?
4440 if ( 0 == intval($post_author) ) {
4441 $post_author = get_user_by('login', $post_author);
4442 if ( empty( $post_author ) ) {
4445 if ( empty( $post_author->ID ) ) {
4448 $post_author = $post_author->ID;
4451 if ( '' == $author_query ) {
4452 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
4454 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
4457 if ( '' != $author_query ) {
4458 $author_query = " AND ($author_query)";
4464 $where = "$exclusions $inclusions ";
4465 if ( '' !== $meta_key || '' !== $meta_value ) {
4466 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
4468 // meta_key and meta_value might be slashed
4469 $meta_key = wp_unslash($meta_key);
4470 $meta_value = wp_unslash($meta_value);
4471 if ( '' !== $meta_key ) {
4472 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
4474 if ( '' !== $meta_value ) {
4475 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
4480 if ( is_array( $parent ) ) {
4481 $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
4482 if ( ! empty( $post_parent__in ) ) {
4483 $where .= " AND post_parent IN ($post_parent__in)";
4485 } elseif ( $parent >= 0 ) {
4486 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
4489 if ( 1 == count( $post_status ) ) {
4490 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $r['post_type'], reset( $post_status ) );
4492 $post_status = implode( "', '", $post_status );
4493 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $r['post_type'] );
4496 $orderby_array = array();
4497 $allowed_keys = array( 'author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
4498 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
4499 'ID', 'rand', 'comment_count' );
4501 foreach ( explode( ',', $r['sort_column'] ) as $orderby ) {
4502 $orderby = trim( $orderby );
4503 if ( ! in_array( $orderby, $allowed_keys ) ) {
4507 switch ( $orderby ) {
4511 $orderby = "$wpdb->posts.ID";
4514 $orderby = 'RAND()';
4516 case 'comment_count':
4517 $orderby = "$wpdb->posts.comment_count";
4520 if ( 0 === strpos( $orderby, 'post_' ) ) {
4521 $orderby = "$wpdb->posts." . $orderby;
4523 $orderby = "$wpdb->posts.post_" . $orderby;
4527 $orderby_array[] = $orderby;
4530 $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
4532 $sort_order = strtoupper( $r['sort_order'] );
4533 if ( '' !== $sort_order && ! in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) {
4534 $sort_order = 'ASC';
4537 $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
4538 $query .= $author_query;
4539 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
4541 if ( ! empty( $number ) ) {
4542 $query .= ' LIMIT ' . $offset . ',' . $number;
4545 $pages = $wpdb->get_results($query);
4547 if ( empty($pages) ) {
4548 /** This filter is documented in wp-includes/post.php */
4549 $pages = apply_filters( 'get_pages', array(), $r );
4553 // Sanitize before caching so it'll only get done once.
4554 $num_pages = count($pages);
4555 for ($i = 0; $i < $num_pages; $i++) {
4556 $pages[$i] = sanitize_post($pages[$i], 'raw');
4560 update_post_cache( $pages );
4562 if ( $child_of || $hierarchical ) {
4563 $pages = get_page_children($child_of, $pages);
4566 if ( ! empty( $r['exclude_tree'] ) ) {
4567 $exclude = wp_parse_id_list( $r['exclude_tree'] );
4568 foreach ( $exclude as $id ) {
4569 $children = get_page_children( $id, $pages );
4570 foreach ( $children as $child ) {
4571 $exclude[] = $child->ID;
4575 $num_pages = count( $pages );
4576 for ( $i = 0; $i < $num_pages; $i++ ) {
4577 if ( in_array( $pages[$i]->ID, $exclude ) ) {
4578 unset( $pages[$i] );
4583 $page_structure = array();
4584 foreach ( $pages as $page ) {
4585 $page_structure[] = $page->ID;
4588 wp_cache_set( $cache_key, $page_structure, 'posts' );
4590 // Convert to WP_Post instances
4591 $pages = array_map( 'get_post', $pages );
4594 * Filter the retrieved list of pages.
4598 * @param array $pages List of pages to retrieve.
4599 * @param array $r Array of get_pages() arguments.
4601 return apply_filters( 'get_pages', $pages, $r );
4605 // Attachment functions
4609 * Check if the attachment URI is local one and is really an attachment.
4613 * @param string $url URL to check
4614 * @return bool True on success, false on failure.
4616 function is_local_attachment($url) {
4617 if (strpos($url, home_url()) === false)
4619 if (strpos($url, home_url('/?attachment_id=')) !== false)
4621 if ( $id = url_to_postid($url) ) {
4622 $post = get_post($id);
4623 if ( 'attachment' == $post->post_type )
4630 * Insert an attachment.
4632 * If you set the 'ID' in the $args parameter, it will mean that you are
4633 * updating and attempt to update the attachment. You can also set the
4634 * attachment name or title by setting the key 'post_name' or 'post_title'.
4636 * You can set the dates for the attachment manually by setting the 'post_date'
4637 * and 'post_date_gmt' keys' values.
4639 * By default, the comments will use the default settings for whether the
4640 * comments are allowed. You can close them manually or keep them open by
4641 * setting the value for the 'comment_status' key.
4645 * @see wp_insert_post()
4647 * @param string|array $args Arguments for inserting an attachment.
4648 * @param string $file Optional. Filename.
4649 * @param int $parent Optional. Parent post ID.
4650 * @return int Attachment ID.
4652 function wp_insert_attachment( $args, $file = false, $parent = 0 ) {
4658 $data = wp_parse_args( $args, $defaults );
4660 if ( ! empty( $parent ) ) {
4661 $data['post_parent'] = $parent;
4664 $data['post_type'] = 'attachment';
4666 return wp_insert_post( $data );
4670 * Trash or delete an attachment.
4672 * When an attachment is permanently deleted, the file will also be removed.
4673 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4674 * with the attachment (except the main post).
4676 * The attachment is moved to the trash instead of permanently deleted unless trash
4677 * for media is disabled, item is already in the trash, or $force_delete is true.
4681 * @global wpdb $wpdb WordPress database abstraction object.
4683 * @param int $post_id Attachment ID.
4684 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
4686 * @return mixed False on failure. Post data on success.
4688 function wp_delete_attachment( $post_id, $force_delete = false ) {
4691 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4694 if ( 'attachment' != $post->post_type )
4697 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4698 return wp_trash_post( $post_id );
4700 delete_post_meta($post_id, '_wp_trash_meta_status');
4701 delete_post_meta($post_id, '_wp_trash_meta_time');
4703 $meta = wp_get_attachment_metadata( $post_id );
4704 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4705 $file = get_attached_file( $post_id );
4707 if ( is_multisite() )
4708 delete_transient( 'dirsize_cache' );
4711 * Fires before an attachment is deleted, at the start of wp_delete_attachment().
4715 * @param int $post_id Attachment ID.
4717 do_action( 'delete_attachment', $post_id );
4719 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4720 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4722 // Delete all for any posts.
4723 delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
4725 wp_defer_comment_counting( true );
4727 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4728 foreach ( $comment_ids as $comment_id ) {
4729 wp_delete_comment( $comment_id, true );
4732 wp_defer_comment_counting( false );
4734 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4735 foreach ( $post_meta_ids as $mid )
4736 delete_metadata_by_mid( 'post', $mid );
4738 /** This action is documented in wp-includes/post.php */
4739 do_action( 'delete_post', $post_id );
4740 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4744 /** This action is documented in wp-includes/post.php */
4745 do_action( 'deleted_post', $post_id );
4747 $uploadpath = wp_upload_dir();
4749 if ( ! empty($meta['thumb']) ) {
4750 // Don't delete the thumb if another attachment uses it.
4751 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)) ) {
4752 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4753 /** This filter is documented in wp-includes/functions.php */
4754 $thumbfile = apply_filters( 'wp_delete_file', $thumbfile );
4755 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4759 // Remove intermediate and backup images if there are any.
4760 if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
4761 foreach ( $meta['sizes'] as $size => $sizeinfo ) {
4762 $intermediate_file = str_replace( basename( $file ), $sizeinfo['file'], $file );
4763 /** This filter is documented in wp-includes/functions.php */
4764 $intermediate_file = apply_filters( 'wp_delete_file', $intermediate_file );
4765 @ unlink( path_join( $uploadpath['basedir'], $intermediate_file ) );
4769 if ( is_array($backup_sizes) ) {
4770 foreach ( $backup_sizes as $size ) {
4771 $del_file = path_join( dirname($meta['file']), $size['file'] );
4772 /** This filter is documented in wp-includes/functions.php */
4773 $del_file = apply_filters( 'wp_delete_file', $del_file );
4774 @ unlink( path_join($uploadpath['basedir'], $del_file) );
4778 wp_delete_file( $file );
4780 clean_post_cache( $post );
4786 * Retrieve attachment meta field for attachment ID.
4790 * @param int $post_id Attachment ID. Default 0.
4791 * @param bool $unfiltered Optional. If true, filters are not run. Default false.
4792 * @return mixed Attachment meta field. False on failure.
4794 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4795 $post_id = (int) $post_id;
4796 if ( !$post = get_post( $post_id ) )
4799 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4805 * Filter the attachment meta data.
4809 * @param array|bool $data Array of meta data for the given attachment, or false
4810 * if the object does not exist.
4811 * @param int $post_id Attachment ID.
4813 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4817 * Update metadata for an attachment.
4821 * @param int $post_id Attachment ID.
4822 * @param array $data Attachment data.
4823 * @return int|bool False if $post is invalid.
4825 function wp_update_attachment_metadata( $post_id, $data ) {
4826 $post_id = (int) $post_id;
4827 if ( !$post = get_post( $post_id ) )
4831 * Filter the updated attachment meta data.
4835 * @param array $data Array of updated attachment meta data.
4836 * @param int $post_id Attachment ID.
4838 if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4839 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4841 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4845 * Retrieve the URL for an attachment.
4849 * @global string $pagenow
4851 * @param int $post_id Optional. Attachment ID. Default 0.
4852 * @return string|false Attachment URL, otherwise false.
4854 function wp_get_attachment_url( $post_id = 0 ) {
4855 $post_id = (int) $post_id;
4856 if ( !$post = get_post( $post_id ) )
4859 if ( 'attachment' != $post->post_type )
4863 // Get attached file.
4864 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) {
4865 // Get upload directory.
4866 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
4867 // Check that the upload base exists in the file location.
4868 if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
4869 // Replace file location with url location.
4870 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
4871 } elseif ( false !== strpos($file, 'wp-content/uploads') ) {
4872 // Get the directory name relative to the basedir (back compat for pre-2.7 uploads)
4873 $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . basename( $file );
4875 // It's a newly-uploaded file, therefore $file is relative to the basedir.
4876 $url = $uploads['baseurl'] . "/$file";
4882 * If any of the above options failed, Fallback on the GUID as used pre-2.7,
4883 * not recommended to rely upon this.
4885 if ( empty($url) ) {
4886 $url = get_the_guid( $post->ID );
4889 // On SSL front-end, URLs should be HTTPS.
4890 if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) {
4891 $url = set_url_scheme( $url );
4895 * Filter the attachment URL.
4899 * @param string $url URL for the given attachment.
4900 * @param int $post_id Attachment ID.
4902 $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4904 if ( empty( $url ) )
4911 * Retrieve thumbnail for an attachment.
4915 * @param int $post_id Optional. Attachment ID. Default 0.
4916 * @return string|false False on failure. Thumbnail file path on success.
4918 function wp_get_attachment_thumb_file( $post_id = 0 ) {
4919 $post_id = (int) $post_id;
4920 if ( !$post = get_post( $post_id ) )
4922 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
4925 $file = get_attached_file( $post->ID );
4927 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) {
4929 * Filter the attachment thumbnail file path.
4933 * @param string $thumbfile File path to the attachment thumbnail.
4934 * @param int $post_id Attachment ID.
4936 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
4942 * Retrieve URL for an attachment thumbnail.
4946 * @param int $post_id Optional. Attachment ID. Default 0.
4947 * @return string|false False on failure. Thumbnail URL on success.
4949 function wp_get_attachment_thumb_url( $post_id = 0 ) {
4950 $post_id = (int) $post_id;
4951 if ( !$post = get_post( $post_id ) )
4953 if ( !$url = wp_get_attachment_url( $post->ID ) )
4956 $sized = image_downsize( $post_id, 'thumbnail' );
4960 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
4963 $url = str_replace(basename($url), basename($thumb), $url);
4966 * Filter the attachment thumbnail URL.
4970 * @param string $url URL for the attachment thumbnail.
4971 * @param int $post_id Attachment ID.
4973 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
4977 * Verifies an attachment is of a given type.
4981 * @param string $type Attachment type. Accepts 'image', 'audio', or 'video'.
4982 * @param int|WP_Post $post_id Optional. Attachment ID. Default 0.
4983 * @return bool True if one of the accepted types, false otherwise.
4985 function wp_attachment_is( $type, $post_id = 0 ) {
4986 if ( ! $post = get_post( $post_id ) ) {
4990 if ( ! $file = get_attached_file( $post->ID ) ) {
4994 if ( 0 === strpos( $post->post_mime_type, $type . '/' ) ) {
4998 $check = wp_check_filetype( $file );
4999 if ( empty( $check['ext'] ) ) {
5003 $ext = $check['ext'];
5005 if ( 'import' !== $post->post_mime_type ) {
5006 return $type === $ext;
5011 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
5012 return in_array( $ext, $image_exts );
5015 return in_array( $ext, wp_get_audio_extensions() );
5018 return in_array( $ext, wp_get_video_extensions() );
5021 return $type === $ext;
5026 * Checks if the attachment is an image.
5029 * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
5030 * allowed WP_Post object to be passed.
5032 * @param int|WP_Post $post Optional. Attachment ID. Default 0.
5033 * @return bool Whether the attachment is an image.
5035 function wp_attachment_is_image( $post = 0 ) {
5036 return wp_attachment_is( 'image', $post );
5040 * Retrieve the icon for a MIME type.
5044 * @param string|int $mime MIME type or attachment ID.
5045 * @return string|false Icon, false otherwise.
5047 function wp_mime_type_icon( $mime = 0 ) {
5048 if ( !is_numeric($mime) )
5049 $icon = wp_cache_get("mime_type_icon_$mime");
5052 if ( empty($icon) ) {
5053 $post_mimes = array();
5054 if ( is_numeric($mime) ) {
5055 $mime = (int) $mime;
5056 if ( $post = get_post( $mime ) ) {
5057 $post_id = (int) $post->ID;
5058 $file = get_attached_file( $post_id );
5059 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $file);
5060 if ( !empty($ext) ) {
5061 $post_mimes[] = $ext;
5062 if ( $ext_type = wp_ext2type( $ext ) )
5063 $post_mimes[] = $ext_type;
5065 $mime = $post->post_mime_type;
5070 $post_mimes[] = $mime;
5073 $icon_files = wp_cache_get('icon_files');
5075 if ( !is_array($icon_files) ) {
5077 * Filter the icon directory path.
5081 * @param string $path Icon directory absolute path.
5083 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
5086 * Filter the icon directory URI.
5090 * @param string $uri Icon directory URI.
5092 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
5095 * Filter the list of icon directory URIs.
5099 * @param array $uris List of icon directory URIs.
5101 $dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
5102 $icon_files = array();
5104 $keys = array_keys( $dirs );
5105 $dir = array_shift( $keys );
5106 $uri = array_shift($dirs);
5107 if ( $dh = opendir($dir) ) {
5108 while ( false !== $file = readdir($dh) ) {
5109 $file = basename($file);
5110 if ( substr($file, 0, 1) == '.' )
5112 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
5113 if ( is_dir("$dir/$file") )
5114 $dirs["$dir/$file"] = "$uri/$file";
5117 $icon_files["$dir/$file"] = "$uri/$file";
5122 wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
5126 // Icon basename - extension = MIME wildcard.
5127 foreach ( $icon_files as $file => $uri )
5128 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
5130 if ( ! empty($mime) ) {
5131 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
5132 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
5133 $post_mimes[] = str_replace('/', '_', $mime);
5136 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
5137 $matches['default'] = array('default');
5139 foreach ( $matches as $match => $wilds ) {
5140 foreach ( $wilds as $wild ) {
5141 if ( ! isset( $types[ $wild ] ) ) {
5145 $icon = $types[ $wild ];
5146 if ( ! is_numeric( $mime ) ) {
5147 wp_cache_add( "mime_type_icon_$mime", $icon );
5155 * Filter the mime type icon.
5159 * @param string $icon Path to the mime type icon.
5160 * @param string $mime Mime type.
5161 * @param int $post_id Attachment ID. Will equal 0 if the function passed
5164 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
5168 * Check for changed slugs for published post objects and save the old slug.
5170 * The function is used when a post object of any type is updated,
5171 * by comparing the current and previous post objects.
5173 * If the slug was changed and not already part of the old slugs then it will be
5174 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
5177 * The most logically usage of this function is redirecting changed post objects, so
5178 * that those that linked to an changed post will be redirected to the new post.
5182 * @param int $post_id Post ID.
5183 * @param WP_Post $post The Post Object
5184 * @param WP_Post $post_before The Previous Post Object
5186 function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
5187 // Don't bother if it hasn't changed.
5188 if ( $post->post_name == $post_before->post_name ) {
5192 // We're only concerned with published, non-hierarchical objects.
5193 if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
5197 $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
5199 // If we haven't added this old slug before, add it now.
5200 if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs ) ) {
5201 add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
5204 // If the new slug was used previously, delete it from the list.
5205 if ( in_array( $post->post_name, $old_slugs ) ) {
5206 delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
5211 * Retrieve the private post SQL based on capability.
5213 * This function provides a standardized way to appropriately select on the
5214 * post_status of a post type. The function will return a piece of SQL code
5215 * that can be added to a WHERE clause; this SQL is constructed to allow all
5216 * published posts, and all private posts to which the user has access.
5219 * @since 4.3.0 Added the ability to pass an array to `$post_type`.
5221 * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
5222 * @return string SQL code that can be added to a where clause.
5224 function get_private_posts_cap_sql( $post_type ) {
5225 return get_posts_by_author_sql( $post_type, false );
5229 * Retrieve the post SQL based on capability, author, and type.
5232 * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
5234 * @see get_private_posts_cap_sql()
5235 * @global wpdb $wpdb WordPress database abstraction object.
5237 * @param array|string $post_type Single post type or an array of post types.
5238 * @param bool $full Optional. Returns a full WHERE statement instead of just
5239 * an 'andalso' term. Default true.
5240 * @param int $post_author Optional. Query posts having a single author ID. Default null.
5241 * @param bool $public_only Optional. Only return public posts. Skips cap checks for
5242 * $current_user. Default false.
5243 * @return string SQL WHERE code that can be added to a query.
5245 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
5248 if ( is_array( $post_type ) ) {
5249 $post_types = $post_type;
5251 $post_types = array( $post_type );
5254 $post_type_clauses = array();
5255 foreach ( $post_types as $post_type ) {
5256 $post_type_obj = get_post_type_object( $post_type );
5257 if ( ! $post_type_obj ) {
5262 * Filter the capability to read private posts for a custom post type
5263 * when generating SQL for getting posts by author.
5266 * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
5268 * @param string $cap Capability.
5270 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
5271 $cap = current_user_can( $post_type_obj->cap->read_private_posts );
5274 // Only need to check the cap if $public_only is false.
5275 $post_status_sql = "post_status = 'publish'";
5276 if ( false === $public_only ) {
5278 // Does the user have the capability to view private posts? Guess so.
5279 $post_status_sql .= " OR post_status = 'private'";
5280 } elseif ( is_user_logged_in() ) {
5281 // Users can view their own private posts.
5282 $id = get_current_user_id();
5283 if ( null === $post_author || ! $full ) {
5284 $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
5285 } elseif ( $id == (int) $post_author ) {
5286 $post_status_sql .= " OR post_status = 'private'";
5291 $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
5294 if ( empty( $post_type_clauses ) ) {
5295 return $full ? 'WHERE 1 = 0' : '1 = 0';
5298 $sql = '( '. implode( ' OR ', $post_type_clauses ) . ' )';
5300 if ( null !== $post_author ) {
5301 $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
5305 $sql = 'WHERE ' . $sql;
5312 * Retrieve the date that the last post was published.
5314 * The server timezone is the default and is the difference between GMT and
5315 * server time. The 'blog' value is the date when the last post was posted. The
5316 * 'gmt' is when the last post was posted in GMT formatted date.
5319 * @since 4.4.0 The `$post_type` argument was added.
5321 * @param string $timezone Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
5322 * 'server' uses the server's internal timezone.
5323 * 'blog' uses the `post_modified` field, which proxies to the timezone set for the site.
5324 * 'gmt' uses the `post_modified_gmt` field.
5326 * @param string $post_type Optional. The post type to check. Default 'any'.
5327 * @return string The date of the last post.
5329 function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
5331 * Filter the date the last post was published.
5335 * @param string $date Date the last post was published.
5336 * @param string $timezone Location to use for getting the post published date.
5337 * See {@see get_lastpostdate()} for accepted `$timezone` values.
5339 return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date', $post_type ), $timezone );
5343 * Get the timestamp of the last time any post was modified.
5345 * The server timezone is the default and is the difference between GMT and
5346 * server time. The 'blog' value is just when the last post was modified. The
5347 * 'gmt' is when the last post was modified in GMT time.
5350 * @since 4.4.0 The `$post_type` argument was added.
5352 * @param string $timezone Optional. The timezone for the timestamp. See {@see get_lastpostdate()}
5353 * for information on accepted values.
5355 * @param string $post_type Optional. The post type to check. Default 'any'.
5356 * @return string The timestamp.
5358 function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
5360 * Pre-filter the return value of get_lastpostmodified() before the query is run.
5364 * @param string $lastpostmodified Date the last post was modified.
5365 * Returning anything other than false will short-circuit the function.
5366 * @param string $timezone Location to use for getting the post modified date.
5367 * See {@see get_lastpostdate()} for accepted `$timezone` values.
5368 * @param string $post_type The post type to check.
5370 $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
5371 if ( false !== $lastpostmodified ) {
5372 return $lastpostmodified;
5375 $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
5377 $lastpostdate = get_lastpostdate($timezone);
5378 if ( $lastpostdate > $lastpostmodified ) {
5379 $lastpostmodified = $lastpostdate;
5383 * Filter the date the last post was modified.
5387 * @param string $lastpostmodified Date the last post was modified.
5388 * @param string $timezone Location to use for getting the post modified date.
5389 * See {@see get_lastpostdate()} for accepted `$timezone` values.
5391 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
5395 * Get the timestamp of the last time any post was modified or published.
5398 * @since 4.4.0 The `$post_type` argument was added.
5401 * @global wpdb $wpdb WordPress database abstraction object.
5403 * @param string $timezone The timezone for the timestamp. See get_lastpostdate().
5404 * for information on accepted values.
5405 * @param string $field Post field to check. Accepts 'date' or 'modified'.
5406 * @param string $post_type Optional. The post type to check. Default 'any'.
5407 * @return string|false The timestamp.
5409 function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
5412 if ( ! in_array( $field, array( 'date', 'modified' ) ) ) {
5416 $timezone = strtolower( $timezone );
5418 $key = "lastpost{$field}:$timezone";
5419 if ( 'any' !== $post_type ) {
5420 $key .= ':' . sanitize_key( $post_type );
5423 $date = wp_cache_get( $key, 'timeinfo' );
5426 if ( 'any' === $post_type ) {
5427 $post_types = get_post_types( array( 'public' => true ) );
5428 array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
5429 $post_types = "'" . implode( "', '", $post_types ) . "'";
5431 $post_types = "'" . sanitize_key( $post_type ) . "'";
5434 switch ( $timezone ) {
5436 $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");
5439 $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");
5442 $add_seconds_server = date( 'Z' );
5443 $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");
5448 wp_cache_set( $key, $date, 'timeinfo' );
5456 * Updates posts in cache.
5460 * @param array $posts Array of post objects, passed by reference.
5462 function update_post_cache( &$posts ) {
5466 foreach ( $posts as $post )
5467 wp_cache_add( $post->ID, $post, 'posts' );
5471 * Will clean the post in the cache.
5473 * Cleaning means delete from the cache of the post. Will call to clean the term
5474 * object cache associated with the post ID.
5476 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
5477 * wp_suspend_cache_invalidation().
5481 * @global bool $_wp_suspend_cache_invalidation
5483 * @param int|WP_Post $post Post ID or post object to remove from the cache.
5485 function clean_post_cache( $post ) {
5486 global $_wp_suspend_cache_invalidation;
5488 if ( ! empty( $_wp_suspend_cache_invalidation ) )
5491 $post = get_post( $post );
5492 if ( empty( $post ) )
5495 wp_cache_delete( $post->ID, 'posts' );
5496 wp_cache_delete( $post->ID, 'post_meta' );
5498 clean_object_term_cache( $post->ID, $post->post_type );
5500 wp_cache_delete( 'wp_get_archives', 'general' );
5503 * Fires immediately after the given post's cache is cleaned.
5507 * @param int $post_id Post ID.
5508 * @param WP_Post $post Post object.
5510 do_action( 'clean_post_cache', $post->ID, $post );
5512 if ( 'page' == $post->post_type ) {
5513 wp_cache_delete( 'all_page_ids', 'posts' );
5516 * Fires immediately after the given page's cache is cleaned.
5520 * @param int $post_id Post ID.
5522 do_action( 'clean_page_cache', $post->ID );
5525 wp_cache_set( 'last_changed', microtime(), 'posts' );
5529 * Call major cache updating functions for list of Post objects.
5533 * @param array $posts Array of Post objects
5534 * @param string $post_type Optional. Post type. Default 'post'.
5535 * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
5536 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
5538 function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
5539 // No point in doing all this work if we didn't match any posts.
5543 update_post_cache($posts);
5545 $post_ids = array();
5546 foreach ( $posts as $post )
5547 $post_ids[] = $post->ID;
5552 if ( $update_term_cache ) {
5553 if ( is_array($post_type) ) {
5554 $ptypes = $post_type;
5555 } elseif ( 'any' == $post_type ) {
5557 // Just use the post_types in the supplied posts.
5558 foreach ( $posts as $post ) {
5559 $ptypes[] = $post->post_type;
5561 $ptypes = array_unique($ptypes);
5563 $ptypes = array($post_type);
5566 if ( ! empty($ptypes) )
5567 update_object_term_cache($post_ids, $ptypes);
5570 if ( $update_meta_cache )
5571 update_postmeta_cache($post_ids);
5575 * Updates metadata cache for list of post IDs.
5577 * Performs SQL query to retrieve the metadata for the post IDs and updates the
5578 * metadata cache for the posts. Therefore, the functions, which call this
5579 * function, do not need to perform SQL queries on their own.
5583 * @param array $post_ids List of post IDs.
5584 * @return array|false Returns false if there is nothing to update or an array
5587 function update_postmeta_cache( $post_ids ) {
5588 return update_meta_cache('post', $post_ids);
5592 * Will clean the attachment in the cache.
5594 * Cleaning means delete from the cache. Optionally will clean the term
5595 * object cache associated with the attachment ID.
5597 * This function will not run if $_wp_suspend_cache_invalidation is not empty.
5601 * @global bool $_wp_suspend_cache_invalidation
5603 * @param int $id The attachment ID in the cache to clean.
5604 * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
5606 function clean_attachment_cache( $id, $clean_terms = false ) {
5607 global $_wp_suspend_cache_invalidation;
5609 if ( !empty($_wp_suspend_cache_invalidation) )
5614 wp_cache_delete($id, 'posts');
5615 wp_cache_delete($id, 'post_meta');
5618 clean_object_term_cache($id, 'attachment');
5621 * Fires after the given attachment's cache is cleaned.
5625 * @param int $id Attachment ID.
5627 do_action( 'clean_attachment_cache', $id );
5635 * Hook for managing future post transitions to published.
5640 * @see wp_clear_scheduled_hook()
5641 * @global wpdb $wpdb WordPress database abstraction object.
5643 * @param string $new_status New post status.
5644 * @param string $old_status Previous post status.
5645 * @param WP_Post $post Post object.
5647 function _transition_post_status( $new_status, $old_status, $post ) {
5650 if ( $old_status != 'publish' && $new_status == 'publish' ) {
5651 // Reset GUID if transitioning to publish and it is empty.
5652 if ( '' == get_the_guid($post->ID) )
5653 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
5656 * Fires when a post's status is transitioned from private to published.
5659 * @deprecated 2.3.0 Use 'private_to_publish' instead.
5661 * @param int $post_id Post ID.
5663 do_action('private_to_published', $post->ID);
5666 // If published posts changed clear the lastpostmodified cache.
5667 if ( 'publish' == $new_status || 'publish' == $old_status) {
5668 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
5669 wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
5670 wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
5671 wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
5675 if ( $new_status !== $old_status ) {
5676 wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
5677 wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
5680 // Always clears the hook in case the post status bounced from future to draft.
5681 wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
5685 * Hook used to schedule publication for a post marked for the future.
5687 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
5692 * @param int $deprecated Not used. Can be set to null. Never implemented. Not marked
5693 * as deprecated with _deprecated_argument() as it conflicts with
5694 * wp_transition_post_status() and the default filter for
5695 * {@see _future_post_hook()}.
5696 * @param WP_Post $post Post object.
5698 function _future_post_hook( $deprecated, $post ) {
5699 wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
5700 wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
5704 * Hook to schedule pings and enclosures when a post is published.
5706 * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
5711 * @param int $post_id The ID in the database table of the post being published.
5713 function _publish_post_hook( $post_id ) {
5714 if ( defined( 'XMLRPC_REQUEST' ) ) {
5716 * Fires when _publish_post_hook() is called during an XML-RPC request.
5720 * @param int $post_id Post ID.
5722 do_action( 'xmlrpc_publish_post', $post_id );
5725 if ( defined('WP_IMPORTING') )
5728 if ( get_option('default_pingback_flag') )
5729 add_post_meta( $post_id, '_pingme', '1' );
5730 add_post_meta( $post_id, '_encloseme', '1' );
5732 wp_schedule_single_event(time(), 'do_pings');
5736 * Return the post's parent's post_ID
5740 * @param int $post_ID
5742 * @return int|false Post parent ID, otherwise false.
5744 function wp_get_post_parent_id( $post_ID ) {
5745 $post = get_post( $post_ID );
5746 if ( !$post || is_wp_error( $post ) )
5748 return (int) $post->post_parent;
5752 * Check the given subset of the post hierarchy for hierarchy loops.
5754 * Prevents loops from forming and breaks those that it finds. Attached
5755 * to the 'wp_insert_post_parent' filter.
5759 * @see wp_find_hierarchy_loop()
5761 * @param int $post_parent ID of the parent for the post we're checking.
5762 * @param int $post_ID ID of the post we're checking.
5763 * @return int The new post_parent for the post, 0 otherwise.
5765 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
5766 // Nothing fancy here - bail.
5767 if ( !$post_parent )
5770 // New post can't cause a loop.
5771 if ( empty( $post_ID ) )
5772 return $post_parent;
5774 // Can't be its own parent.
5775 if ( $post_parent == $post_ID )
5778 // Now look for larger loops.
5779 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
5780 return $post_parent; // No loop
5782 // Setting $post_parent to the given value causes a loop.
5783 if ( isset( $loop[$post_ID] ) )
5786 // There's a loop, but it doesn't contain $post_ID. Break the loop.
5787 foreach ( array_keys( $loop ) as $loop_member )
5788 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
5790 return $post_parent;
5794 * Set a post thumbnail.
5798 * @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
5799 * @param int $thumbnail_id Thumbnail to attach.
5800 * @return int|bool True on success, false on failure.
5802 function set_post_thumbnail( $post, $thumbnail_id ) {
5803 $post = get_post( $post );
5804 $thumbnail_id = absint( $thumbnail_id );
5805 if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
5806 if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
5807 return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
5809 return delete_post_meta( $post->ID, '_thumbnail_id' );
5815 * Remove a post thumbnail.
5819 * @param int|WP_Post $post Post ID or post object where thumbnail should be removed from.
5820 * @return bool True on success, false on failure.
5822 function delete_post_thumbnail( $post ) {
5823 $post = get_post( $post );
5825 return delete_post_meta( $post->ID, '_thumbnail_id' );
5830 * Delete auto-drafts for new posts that are > 7 days old.
5834 * @global wpdb $wpdb WordPress database abstraction object.
5836 function wp_delete_auto_drafts() {
5839 // Cleanup old auto-drafts more than 7 days old.
5840 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
5841 foreach ( (array) $old_posts as $delete ) {
5843 wp_delete_post( $delete, true );
5848 * Update the custom taxonomies' term counts when a post's status is changed.
5850 * For example, default posts term counts (for custom taxonomies) don't include
5851 * private / draft posts.
5856 * @param string $new_status New post status.
5857 * @param string $old_status Old post status.
5858 * @param WP_Post $post Post object.
5860 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
5861 // Update counts for the post's terms.
5862 foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
5863 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
5864 wp_update_term_count( $tt_ids, $taxonomy );
5869 * Adds any posts from the given ids to the cache that do not already exist in cache
5874 * @see update_post_caches()
5876 * @global wpdb $wpdb WordPress database abstraction object.
5878 * @param array $ids ID list.
5879 * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
5880 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
5882 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
5885 $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
5886 if ( !empty( $non_cached_ids ) ) {
5887 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
5889 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );