10 // Post Type Registration
14 * Creates the initial post types when 'init' action is fired.
20 function create_initial_post_types() {
21 register_post_type( 'post', array(
23 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
26 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
27 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
28 'capability_type' => 'post',
29 'map_meta_cap' => true,
31 'hierarchical' => false,
34 'delete_with_user' => true,
35 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
38 register_post_type( 'page', array(
40 'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
43 'publicly_queryable' => false,
44 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
45 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
46 'capability_type' => 'page',
47 'map_meta_cap' => true,
48 'menu_position' => 20,
49 'hierarchical' => true,
52 'delete_with_user' => true,
53 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
56 register_post_type( 'attachment', array(
58 'name' => _x('Media', 'post type general name'),
59 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
60 'add_new' => _x( 'Add New', 'add new media' ),
61 'edit_item' => __( 'Edit Media' ),
62 'view_item' => __( 'View Attachment Page' ),
66 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
67 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
68 'capability_type' => 'post',
69 'capabilities' => array(
70 'create_posts' => 'upload_files',
72 'map_meta_cap' => true,
73 'hierarchical' => false,
76 'show_in_nav_menus' => false,
77 'delete_with_user' => true,
78 'supports' => array( 'title', 'author', 'comments' ),
80 add_post_type_support( 'attachment:audio', 'thumbnail' );
81 add_post_type_support( 'attachment:video', 'thumbnail' );
83 register_post_type( 'revision', array(
85 'name' => __( 'Revisions' ),
86 'singular_name' => __( 'Revision' ),
89 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
90 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
91 'capability_type' => 'post',
92 'map_meta_cap' => true,
93 'hierarchical' => false,
96 'can_export' => false,
97 'delete_with_user' => true,
98 'supports' => array( 'author' ),
101 register_post_type( 'nav_menu_item', array(
103 'name' => __( 'Navigation Menu Items' ),
104 'singular_name' => __( 'Navigation Menu Item' ),
107 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
108 'hierarchical' => false,
110 'delete_with_user' => false,
111 'query_var' => false,
114 register_post_status( 'publish', array(
115 'label' => _x( 'Published', 'post status' ),
117 '_builtin' => true, /* internal use only. */
118 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
121 register_post_status( 'future', array(
122 'label' => _x( 'Scheduled', 'post status' ),
124 '_builtin' => true, /* internal use only. */
125 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
128 register_post_status( 'draft', array(
129 'label' => _x( 'Draft', 'post status' ),
131 '_builtin' => true, /* internal use only. */
132 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
135 register_post_status( 'pending', array(
136 'label' => _x( 'Pending', 'post status' ),
138 '_builtin' => true, /* internal use only. */
139 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
142 register_post_status( 'private', array(
143 'label' => _x( 'Private', 'post status' ),
145 '_builtin' => true, /* internal use only. */
146 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
149 register_post_status( 'trash', array(
150 'label' => _x( 'Trash', 'post status' ),
152 '_builtin' => true, /* internal use only. */
153 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
154 'show_in_admin_status_list' => true,
157 register_post_status( 'auto-draft', array(
158 'label' => 'auto-draft',
160 '_builtin' => true, /* internal use only. */
163 register_post_status( 'inherit', array(
164 'label' => 'inherit',
166 '_builtin' => true, /* internal use only. */
167 'exclude_from_search' => false,
172 * Retrieve attached file path based on attachment ID.
174 * By default the path will go through the 'get_attached_file' filter, but
175 * passing a true to the $unfiltered argument of get_attached_file() will
176 * return the file path unfiltered.
178 * The function works by getting the single post meta name, named
179 * '_wp_attached_file' and returning it. This is a convenience function to
180 * prevent looking up the meta name and provide a mechanism for sending the
181 * attached filename through a filter.
185 * @param int $attachment_id Attachment ID.
186 * @param bool $unfiltered Optional. Whether to apply filters. Default false.
187 * @return string|false The file path to where the attached file should be, false otherwise.
189 function get_attached_file( $attachment_id, $unfiltered = false ) {
190 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
192 // If the file is relative, prepend upload dir.
193 if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) && ( ( $uploads = wp_get_upload_dir() ) && false === $uploads['error'] ) ) {
194 $file = $uploads['basedir'] . "/$file";
202 * Filters the attached file based on the given ID.
206 * @param string $file Path to attached file.
207 * @param int $attachment_id Attachment ID.
209 return apply_filters( 'get_attached_file', $file, $attachment_id );
213 * Update attachment file path based on attachment ID.
215 * Used to update the file path of the attachment, which uses post meta name
216 * '_wp_attached_file' to store the path of the attachment.
220 * @param int $attachment_id Attachment ID.
221 * @param string $file File path for the attachment.
222 * @return bool True on success, false on failure.
224 function update_attached_file( $attachment_id, $file ) {
225 if ( !get_post( $attachment_id ) )
229 * Filters the path to the attached file to update.
233 * @param string $file Path to the attached file to update.
234 * @param int $attachment_id Attachment ID.
236 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
238 if ( $file = _wp_relative_upload_path( $file ) )
239 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
241 return delete_post_meta( $attachment_id, '_wp_attached_file' );
245 * Return relative path to an uploaded file.
247 * The path is relative to the current upload dir.
251 * @param string $path Full path to the file.
252 * @return string Relative path on success, unchanged path on failure.
254 function _wp_relative_upload_path( $path ) {
257 $uploads = wp_get_upload_dir();
258 if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
259 $new_path = str_replace( $uploads['basedir'], '', $new_path );
260 $new_path = ltrim( $new_path, '/' );
264 * Filters the relative path to an uploaded file.
268 * @param string $new_path Relative path to the file.
269 * @param string $path Full path to the file.
271 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
275 * Retrieve all children of the post parent ID.
277 * Normally, without any enhancements, the children would apply to pages. In the
278 * context of the inner workings of WordPress, pages, posts, and attachments
279 * share the same table, so therefore the functionality could apply to any one
280 * of them. It is then noted that while this function does not work on posts, it
281 * does not mean that it won't work on posts. It is recommended that you know
282 * what context you wish to retrieve the children of.
284 * Attachments may also be made the child of a post, so if that is an accurate
285 * statement (which needs to be verified), it would then be possible to get
286 * all of the attachments for a post. Attachments have since changed since
287 * version 2.5, so this is most likely inaccurate, but serves generally as an
288 * example of what is possible.
290 * The arguments listed as defaults are for this function and also of the
291 * get_posts() function. The arguments are combined with the get_children defaults
292 * and are then passed to the get_posts() function, which accepts additional arguments.
293 * You can replace the defaults in this function, listed below and the additional
294 * arguments listed in the get_posts() function.
296 * The 'post_parent' is the most important argument and important attention
297 * needs to be paid to the $args parameter. If you pass either an object or an
298 * integer (number), then just the 'post_parent' is grabbed and everything else
299 * is lost. If you don't specify any arguments, then it is assumed that you are
300 * in The Loop and the post parent will be grabbed for from the current post.
302 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
303 * is the amount of posts to retrieve that has a default of '-1', which is
304 * used to get all of the posts. Giving a number higher than 0 will only
305 * retrieve that amount of posts.
307 * The 'post_type' and 'post_status' arguments can be used to choose what
308 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
309 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
310 * argument will accept any post status within the write administration panels.
315 * @todo Check validity of description.
317 * @global WP_Post $post
319 * @param mixed $args Optional. User defined arguments for replacing the defaults. Default empty.
320 * @param string $output Optional. Constant for return type. Accepts OBJECT, ARRAY_A, ARRAY_N.
322 * @return array Array of children, where the type of each element is determined by $output parameter.
323 * Empty array on failure.
325 function get_children( $args = '', $output = OBJECT ) {
327 if ( empty( $args ) ) {
328 if ( isset( $GLOBALS['post'] ) ) {
329 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
333 } elseif ( is_object( $args ) ) {
334 $args = array('post_parent' => (int) $args->post_parent );
335 } elseif ( is_numeric( $args ) ) {
336 $args = array('post_parent' => (int) $args);
340 'numberposts' => -1, 'post_type' => 'any',
341 'post_status' => 'any', 'post_parent' => 0,
344 $r = wp_parse_args( $args, $defaults );
346 $children = get_posts( $r );
351 if ( ! empty( $r['fields'] ) )
354 update_post_cache($children);
356 foreach ( $children as $key => $child )
357 $kids[$child->ID] = $children[$key];
359 if ( $output == OBJECT ) {
361 } elseif ( $output == ARRAY_A ) {
363 foreach ( (array) $kids as $kid ) {
364 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
367 } elseif ( $output == ARRAY_N ) {
369 foreach ( (array) $kids as $kid ) {
370 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
379 * Get extended entry info (<!--more-->).
381 * There should not be any space after the second dash and before the word
382 * 'more'. There can be text or space(s) after the word 'more', but won't be
385 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
386 * the `<!--more-->`. The 'extended' key has the content after the
387 * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
391 * @param string $post Post content.
392 * @return array Post before ('main'), after ('extended'), and custom read more ('more_text').
394 function get_extended( $post ) {
395 //Match the new style more links.
396 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
397 list($main, $extended) = explode($matches[0], $post, 2);
398 $more_text = $matches[1];
405 // leading and trailing whitespace.
406 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
407 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
408 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
410 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
414 * Retrieves post data given a post ID or post object.
416 * See sanitize_post() for optional $filter values. Also, the parameter
417 * `$post`, must be given as a variable, since it is passed by reference.
421 * @global WP_Post $post
423 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
424 * @param string $output Optional, default is Object. Accepts OBJECT, ARRAY_A, or ARRAY_N.
426 * @param string $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
427 * or 'display'. Default 'raw'.
428 * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
429 * When $output is OBJECT, a `WP_Post` instance is returned.
431 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
432 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
433 $post = $GLOBALS['post'];
435 if ( $post instanceof WP_Post ) {
437 } elseif ( is_object( $post ) ) {
438 if ( empty( $post->filter ) ) {
439 $_post = sanitize_post( $post, 'raw' );
440 $_post = new WP_Post( $_post );
441 } elseif ( 'raw' == $post->filter ) {
442 $_post = new WP_Post( $post );
444 $_post = WP_Post::get_instance( $post->ID );
447 $_post = WP_Post::get_instance( $post );
453 $_post = $_post->filter( $filter );
455 if ( $output == ARRAY_A )
456 return $_post->to_array();
457 elseif ( $output == ARRAY_N )
458 return array_values( $_post->to_array() );
464 * Retrieve ancestors of a post.
468 * @param int|WP_Post $post Post ID or post object.
469 * @return array Ancestor IDs or empty array if none are found.
471 function get_post_ancestors( $post ) {
472 $post = get_post( $post );
474 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
477 $ancestors = array();
479 $id = $ancestors[] = $post->post_parent;
481 while ( $ancestor = get_post( $id ) ) {
482 // Loop detection: If the ancestor has been seen before, break.
483 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
486 $id = $ancestors[] = $ancestor->post_parent;
493 * Retrieve data from a post field based on Post ID.
495 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
496 * etc and based off of the post object property or key names.
498 * The context values are based off of the taxonomy filter functions and
499 * supported values are found within those functions.
502 * @since 4.5.0 The `$post` parameter was made optional.
504 * @see sanitize_post_field()
506 * @param string $field Post field name.
507 * @param int|WP_Post $post Optional. Post ID or post object. Defaults to current post.
508 * @param string $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
509 * or 'display'. Default 'display'.
510 * @return string The value of the post field on success, empty string on failure.
512 function get_post_field( $field, $post = null, $context = 'display' ) {
513 $post = get_post( $post );
518 if ( !isset($post->$field) )
521 return sanitize_post_field($field, $post->$field, $post->ID, $context);
525 * Retrieve the mime type of an attachment based on the ID.
527 * This function can be used with any post type, but it makes more sense with
532 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
533 * @return string|false The mime type on success, false on failure.
535 function get_post_mime_type( $ID = '' ) {
536 $post = get_post($ID);
538 if ( is_object($post) )
539 return $post->post_mime_type;
545 * Retrieve the post status based on the Post ID.
547 * If the post ID is of an attachment, then the parent post status will be given
552 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
553 * @return string|false Post status on success, false on failure.
555 function get_post_status( $ID = '' ) {
556 $post = get_post($ID);
558 if ( !is_object($post) )
561 if ( 'attachment' == $post->post_type ) {
562 if ( 'private' == $post->post_status )
565 // Unattached attachments are assumed to be published.
566 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
569 // Inherit status from the parent.
570 if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) {
571 $parent_post_status = get_post_status( $post->post_parent );
572 if ( 'trash' == $parent_post_status ) {
573 return get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
575 return $parent_post_status;
582 * Filters the post status.
586 * @param string $post_status The post status.
587 * @param WP_Post $post The post object.
589 return apply_filters( 'get_post_status', $post->post_status, $post );
593 * Retrieve all of the WordPress supported post statuses.
595 * Posts have a limited set of valid status values, this provides the
596 * post_status values and descriptions.
600 * @return array List of post statuses.
602 function get_post_statuses() {
604 'draft' => __( 'Draft' ),
605 'pending' => __( 'Pending Review' ),
606 'private' => __( 'Private' ),
607 'publish' => __( 'Published' )
614 * Retrieve all of the WordPress support page statuses.
616 * Pages have a limited set of valid status values, this provides the
617 * post_status values and descriptions.
621 * @return array List of page statuses.
623 function get_page_statuses() {
625 'draft' => __( 'Draft' ),
626 'private' => __( 'Private' ),
627 'publish' => __( 'Published' )
634 * Register a post status. Do not use before init.
636 * A simple function for creating or modifying a post status based on the
637 * parameters given. The function will accept an array (second optional
638 * parameter), along with a string for the post status name.
640 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
643 * @global array $wp_post_statuses Inserts new post status object into the list
645 * @param string $post_status Name of the post status.
646 * @param array|string $args {
647 * Optional. Array or string of post status arguments.
649 * @type bool|string $label A descriptive name for the post status marked
650 * for translation. Defaults to value of $post_status.
651 * @type bool|array $label_count Descriptive text to use for nooped plurals.
652 * Default array of $label, twice
653 * @type bool $exclude_from_search Whether to exclude posts with this post status
654 * from search results. Default is value of $internal.
655 * @type bool $_builtin Whether the status is built-in. Core-use only.
657 * @type bool $public Whether posts of this status should be shown
658 * in the front end of the site. Default false.
659 * @type bool $internal Whether the status is for internal use only.
661 * @type bool $protected Whether posts with this status should be protected.
663 * @type bool $private Whether posts with this status should be private.
665 * @type bool $publicly_queryable Whether posts with this status should be publicly-
666 * queryable. Default is value of $public.
667 * @type bool $show_in_admin_all_list Whether to include posts in the edit listing for
668 * their post type. Default is value of $internal.
669 * @type bool $show_in_admin_status_list Show in the list of statuses with post counts at
670 * the top of the edit listings,
671 * e.g. All (12) | Published (9) | My Custom Status (2)
672 * Default is value of $internal.
676 function register_post_status( $post_status, $args = array() ) {
677 global $wp_post_statuses;
679 if (!is_array($wp_post_statuses))
680 $wp_post_statuses = array();
682 // Args prefixed with an underscore are reserved for internal use.
685 'label_count' => false,
686 'exclude_from_search' => null,
692 'publicly_queryable' => null,
693 'show_in_admin_status_list' => null,
694 'show_in_admin_all_list' => null,
696 $args = wp_parse_args($args, $defaults);
697 $args = (object) $args;
699 $post_status = sanitize_key($post_status);
700 $args->name = $post_status;
702 // Set various defaults.
703 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
704 $args->internal = true;
706 if ( null === $args->public )
707 $args->public = false;
709 if ( null === $args->private )
710 $args->private = false;
712 if ( null === $args->protected )
713 $args->protected = false;
715 if ( null === $args->internal )
716 $args->internal = false;
718 if ( null === $args->publicly_queryable )
719 $args->publicly_queryable = $args->public;
721 if ( null === $args->exclude_from_search )
722 $args->exclude_from_search = $args->internal;
724 if ( null === $args->show_in_admin_all_list )
725 $args->show_in_admin_all_list = !$args->internal;
727 if ( null === $args->show_in_admin_status_list )
728 $args->show_in_admin_status_list = !$args->internal;
730 if ( false === $args->label )
731 $args->label = $post_status;
733 if ( false === $args->label_count )
734 $args->label_count = array( $args->label, $args->label );
736 $wp_post_statuses[$post_status] = $args;
742 * Retrieve a post status object by name.
746 * @global array $wp_post_statuses List of post statuses.
748 * @see register_post_status()
750 * @param string $post_status The name of a registered post status.
751 * @return object|null A post status object.
753 function get_post_status_object( $post_status ) {
754 global $wp_post_statuses;
756 if ( empty($wp_post_statuses[$post_status]) )
759 return $wp_post_statuses[$post_status];
763 * Get a list of post statuses.
767 * @global array $wp_post_statuses List of post statuses.
769 * @see register_post_status()
771 * @param array|string $args Optional. Array or string of post status arguments to compare against
772 * properties of the global `$wp_post_statuses objects`. Default empty array.
773 * @param string $output Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
774 * @param string $operator Optional. The logical operation to perform. 'or' means only one element
775 * from the array needs to match; 'and' means all elements must match.
777 * @return array A list of post status names or objects.
779 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
780 global $wp_post_statuses;
782 $field = ('names' == $output) ? 'name' : false;
784 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
788 * Whether the post type is hierarchical.
790 * A false return value might also mean that the post type does not exist.
794 * @see get_post_type_object()
796 * @param string $post_type Post type name
797 * @return bool Whether post type is hierarchical.
799 function is_post_type_hierarchical( $post_type ) {
800 if ( ! post_type_exists( $post_type ) )
803 $post_type = get_post_type_object( $post_type );
804 return $post_type->hierarchical;
808 * Check if a post type is registered.
812 * @see get_post_type_object()
814 * @param string $post_type Post type name.
815 * @return bool Whether post type is registered.
817 function post_type_exists( $post_type ) {
818 return (bool) get_post_type_object( $post_type );
822 * Retrieves the post type of the current post or of a given post.
826 * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
827 * @return string|false Post type on success, false on failure.
829 function get_post_type( $post = null ) {
830 if ( $post = get_post( $post ) )
831 return $post->post_type;
837 * Retrieves a post type object by name.
840 * @since 4.6.0 Object returned is now an instance of WP_Post_Type.
842 * @global array $wp_post_types List of post types.
844 * @see register_post_type()
846 * @param string $post_type The name of a registered post type.
847 * @return WP_Post_Type|null WP_Post_Type object if it exists, null otherwise.
849 function get_post_type_object( $post_type ) {
850 global $wp_post_types;
852 if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
856 return $wp_post_types[ $post_type ];
860 * Get a list of all registered post type objects.
864 * @global array $wp_post_types List of post types.
866 * @see register_post_type() for accepted arguments.
868 * @param array|string $args Optional. An array of key => value arguments to match against
869 * the post type objects. Default empty array.
870 * @param string $output Optional. The type of output to return. Accepts post type 'names'
871 * or 'objects'. Default 'names'.
872 * @param string $operator Optional. The logical operation to perform. 'or' means only one
873 * element from the array needs to match; 'and' means all elements
874 * must match; 'not' means no elements may match. Default 'and'.
875 * @return array A list of post type names or objects.
877 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
878 global $wp_post_types;
880 $field = ('names' == $output) ? 'name' : false;
882 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
886 * Registers a post type.
888 * Note: Post type registrations should not be hooked before the
889 * {@see 'init'} action. Also, any taxonomy connections should be
890 * registered via the `$taxonomies` argument to ensure consistency
891 * when hooks such as {@see 'parse_query'} or {@see 'pre_get_posts'}
894 * Post types can support any number of built-in core features such
895 * as meta boxes, custom fields, post thumbnails, post statuses,
896 * comments, and more. See the `$supports` argument for a complete
897 * list of supported features.
900 * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
901 * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing
902 * screen and post editing screen.
903 * @since 4.6.0 Post type object returned is now an instance of WP_Post_Type.
905 * @global array $wp_post_types List of post types.
907 * @param string $post_type Post type key. Must not exceed 20 characters and may
908 * only contain lowercase alphanumeric characters, dashes,
909 * and underscores. See sanitize_key().
910 * @param array|string $args {
911 * Array or string of arguments for registering a post type.
913 * @type string $label Name of the post type shown in the menu. Usually plural.
914 * Default is value of $labels['name'].
915 * @type array $labels An array of labels for this post type. If not set, post
916 * labels are inherited for non-hierarchical types and page
917 * labels for hierarchical ones. See get_post_type_labels() for a full
918 * list of supported labels.
919 * @type string $description A short descriptive summary of what the post type is.
921 * @type bool $public Whether a post type is intended for use publicly either via
922 * the admin interface or by front-end users. While the default
923 * settings of $exclude_from_search, $publicly_queryable, $show_ui,
924 * and $show_in_nav_menus are inherited from public, each does not
925 * rely on this relationship and controls a very specific intention.
927 * @type bool $hierarchical Whether the post type is hierarchical (e.g. page). Default false.
928 * @type bool $exclude_from_search Whether to exclude posts with this post type from front end search
929 * results. Default is the opposite value of $public.
930 * @type bool $publicly_queryable Whether queries can be performed on the front end for the post type
931 * as part of parse_request(). Endpoints would include:
932 * * ?post_type={post_type_key}
933 * * ?{post_type_key}={single_post_slug}
934 * * ?{post_type_query_var}={single_post_slug}
935 * If not set, the default is inherited from $public.
936 * @type bool $show_ui Whether to generate and allow a UI for managing this post type in the
937 * admin. Default is value of $public.
938 * @type bool $show_in_menu Where to show the post type in the admin menu. To work, $show_ui
939 * must be true. If true, the post type is shown in its own top level
940 * menu. If false, no menu is shown. If a string of an existing top
941 * level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
942 * type will be placed as a sub-menu of that.
943 * Default is value of $show_ui.
944 * @type bool $show_in_nav_menus Makes this post type available for selection in navigation menus.
945 * Default is value $public.
946 * @type bool $show_in_admin_bar Makes this post type available via the admin bar. Default is value
948 * @type int $menu_position The position in the menu order the post type should appear. To work,
949 * $show_in_menu must be true. Default null (at the bottom).
950 * @type string $menu_icon The url to the icon to be used for this menu. Pass a base64-encoded
951 * SVG using a data URI, which will be colored to match the color scheme
952 * -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
953 * of a Dashicons helper class to use a font icon, e.g.
954 * 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
955 * so an icon can be added via CSS. Defaults to use the posts icon.
956 * @type string $capability_type The string to use to build the read, edit, and delete capabilities.
957 * May be passed as an array to allow for alternative plurals when using
958 * this argument as a base to construct the capabilities, e.g.
959 * array('story', 'stories'). Default 'post'.
960 * @type array $capabilities Array of capabilities for this post type. $capability_type is used
961 * as a base to construct capabilities by default.
962 * See get_post_type_capabilities().
963 * @type bool $map_meta_cap Whether to use the internal default meta capability handling.
965 * @type array $supports Core feature(s) the post type supports. Serves as an alias for calling
966 * add_post_type_support() directly. Core features include 'title',
967 * 'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt',
968 * 'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'.
969 * Additionally, the 'revisions' feature dictates whether the post type
970 * will store revisions, and the 'comments' feature dictates whether the
971 * comments count will show on the edit screen. Defaults is an array
972 * containing 'title' and 'editor'.
973 * @type callable $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
974 * edit form. Do remove_meta_box() and add_meta_box() calls in the
975 * callback. Default null.
976 * @type array $taxonomies An array of taxonomy identifiers that will be registered for the
977 * post type. Taxonomies can be registered later with register_taxonomy()
978 * or register_taxonomy_for_object_type().
979 * Default empty array.
980 * @type bool|string $has_archive Whether there should be post type archives, or if a string, the
981 * archive slug to use. Will generate the proper rewrite rules if
982 * $rewrite is enabled. Default false.
983 * @type bool|array $rewrite {
984 * Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
985 * Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
986 * passed with any of these keys:
988 * @type string $slug Customize the permastruct slug. Defaults to $post_type key.
989 * @type bool $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
991 * @type bool $feeds Whether the feed permastruct should be built for this post type.
992 * Default is value of $has_archive.
993 * @type bool $pages Whether the permastruct should provide for pagination. Default true.
994 * @type const $ep_mask Endpoint mask to assign. If not specified and permalink_epmask is set,
995 * inherits from $permalink_epmask. If not specified and permalink_epmask
996 * is not set, defaults to EP_PERMALINK.
998 * @type string|bool $query_var Sets the query_var key for this post type. Defaults to $post_type
999 * key. If false, a post type cannot be loaded at
1000 * ?{query_var}={post_slug}. If specified as a string, the query
1001 * ?{query_var_string}={post_slug} will be valid.
1002 * @type bool $can_export Whether to allow this post type to be exported. Default true.
1003 * @type bool $delete_with_user Whether to delete posts of this type when deleting a user. If true,
1004 * posts of this type belonging to the user will be moved to trash
1005 * when then user is deleted. If false, posts of this type belonging
1006 * to the user will *not* be trashed or deleted. If not set (the default),
1007 * posts are trashed if post_type_supports('author'). Otherwise posts
1008 * are not trashed or deleted. Default null.
1009 * @type bool $_builtin FOR INTERNAL USE ONLY! True if this post type is a native or
1010 * "built-in" post_type. Default false.
1011 * @type string $_edit_link FOR INTERNAL USE ONLY! URL segment to use for edit link of
1012 * this post type. Default 'post.php?post=%d'.
1014 * @return WP_Post_Type|WP_Error The registered post type object, or an error object.
1016 function register_post_type( $post_type, $args = array() ) {
1017 global $wp_post_types;
1019 if ( ! is_array( $wp_post_types ) ) {
1020 $wp_post_types = array();
1023 // Sanitize post type name
1024 $post_type = sanitize_key( $post_type );
1026 if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1027 _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2.0' );
1028 return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1031 $post_type_object = new WP_Post_Type( $post_type, $args );
1032 $post_type_object->add_supports();
1033 $post_type_object->add_rewrite_rules();
1034 $post_type_object->register_meta_boxes();
1036 $wp_post_types[ $post_type ] = $post_type_object;
1038 $post_type_object->add_hooks();
1039 $post_type_object->register_taxonomies();
1042 * Fires after a post type is registered.
1045 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1047 * @param string $post_type Post type.
1048 * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1050 do_action( 'registered_post_type', $post_type, $post_type_object );
1052 return $post_type_object;
1056 * Unregisters a post type.
1058 * Can not be used to unregister built-in post types.
1062 * @global array $wp_post_types List of post types.
1064 * @param string $post_type Post type to unregister.
1065 * @return bool|WP_Error True on success, WP_Error on failure or if the post type doesn't exist.
1067 function unregister_post_type( $post_type ) {
1068 global $wp_post_types;
1070 if ( ! post_type_exists( $post_type ) ) {
1071 return new WP_Error( 'invalid_post_type', __( 'Invalid post type.' ) );
1074 $post_type_object = get_post_type_object( $post_type );
1076 // Do not allow unregistering internal post types.
1077 if ( $post_type_object->_builtin ) {
1078 return new WP_Error( 'invalid_post_type', __( 'Unregistering a built-in post type is not allowed' ) );
1081 $post_type_object->remove_supports();
1082 $post_type_object->remove_rewrite_rules();
1083 $post_type_object->unregister_meta_boxes();
1084 $post_type_object->remove_hooks();
1085 $post_type_object->unregister_taxonomies();
1087 unset( $wp_post_types[ $post_type ] );
1090 * Fires after a post type was unregistered.
1094 * @param string $post_type Post type key.
1096 do_action( 'unregistered_post_type', $post_type );
1102 * Build an object with all post type capabilities out of a post type object
1104 * Post type capabilities use the 'capability_type' argument as a base, if the
1105 * capability is not set in the 'capabilities' argument array or if the
1106 * 'capabilities' argument is not supplied.
1108 * The capability_type argument can optionally be registered as an array, with
1109 * the first value being singular and the second plural, e.g. array('story, 'stories')
1110 * Otherwise, an 's' will be added to the value for the plural form. After
1111 * registration, capability_type will always be a string of the singular value.
1113 * By default, seven keys are accepted as part of the capabilities array:
1115 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1116 * generally mapped to corresponding primitive capabilities depending on the
1117 * context, which would be the post being edited/read/deleted and the user or
1118 * role being checked. Thus these capabilities would generally not be granted
1119 * directly to users or roles.
1121 * - edit_posts - Controls whether objects of this post type can be edited.
1122 * - edit_others_posts - Controls whether objects of this type owned by other users
1123 * can be edited. If the post type does not support an author, then this will
1124 * behave like edit_posts.
1125 * - publish_posts - Controls publishing objects of this post type.
1126 * - read_private_posts - Controls whether private objects can be read.
1128 * These four primitive capabilities are checked in core in various locations.
1129 * There are also seven other primitive capabilities which are not referenced
1130 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1131 * meta capabilities and translates them into one or more primitive capabilities
1132 * that must then be checked against the user or role, depending on the context.
1134 * - read - Controls whether objects of this post type can be read.
1135 * - delete_posts - Controls whether objects of this post type can be deleted.
1136 * - delete_private_posts - Controls whether private objects can be deleted.
1137 * - delete_published_posts - Controls whether published objects can be deleted.
1138 * - delete_others_posts - Controls whether objects owned by other users can be
1139 * can be deleted. If the post type does not support an author, then this will
1140 * behave like delete_posts.
1141 * - edit_private_posts - Controls whether private objects can be edited.
1142 * - edit_published_posts - Controls whether published objects can be edited.
1144 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1145 * only assigned by default if the post type is registered with the 'map_meta_cap'
1146 * argument set to true (default is false).
1150 * @see register_post_type()
1151 * @see map_meta_cap()
1153 * @param object $args Post type registration arguments.
1154 * @return object object with all the capabilities as member variables.
1156 function get_post_type_capabilities( $args ) {
1157 if ( ! is_array( $args->capability_type ) )
1158 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1160 // Singular base for meta capabilities, plural base for primitive capabilities.
1161 list( $singular_base, $plural_base ) = $args->capability_type;
1163 $default_capabilities = array(
1164 // Meta capabilities
1165 'edit_post' => 'edit_' . $singular_base,
1166 'read_post' => 'read_' . $singular_base,
1167 'delete_post' => 'delete_' . $singular_base,
1168 // Primitive capabilities used outside of map_meta_cap():
1169 'edit_posts' => 'edit_' . $plural_base,
1170 'edit_others_posts' => 'edit_others_' . $plural_base,
1171 'publish_posts' => 'publish_' . $plural_base,
1172 'read_private_posts' => 'read_private_' . $plural_base,
1175 // Primitive capabilities used within map_meta_cap():
1176 if ( $args->map_meta_cap ) {
1177 $default_capabilities_for_mapping = array(
1179 'delete_posts' => 'delete_' . $plural_base,
1180 'delete_private_posts' => 'delete_private_' . $plural_base,
1181 'delete_published_posts' => 'delete_published_' . $plural_base,
1182 'delete_others_posts' => 'delete_others_' . $plural_base,
1183 'edit_private_posts' => 'edit_private_' . $plural_base,
1184 'edit_published_posts' => 'edit_published_' . $plural_base,
1186 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1189 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1191 // Post creation capability simply maps to edit_posts by default:
1192 if ( ! isset( $capabilities['create_posts'] ) )
1193 $capabilities['create_posts'] = $capabilities['edit_posts'];
1195 // Remember meta capabilities for future reference.
1196 if ( $args->map_meta_cap )
1197 _post_type_meta_capabilities( $capabilities );
1199 return (object) $capabilities;
1203 * Store or return a list of post type meta caps for map_meta_cap().
1208 * @global array $post_type_meta_caps Used to store meta capabilities.
1210 * @param array $capabilities Post type meta capabilities.
1212 function _post_type_meta_capabilities( $capabilities = null ) {
1213 global $post_type_meta_caps;
1215 foreach ( $capabilities as $core => $custom ) {
1216 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) ) {
1217 $post_type_meta_caps[ $custom ] = $core;
1223 * Builds an object with all post type labels out of a post type object.
1225 * Accepted keys of the label array in the post type object:
1227 * - `name` - General name for the post type, usually plural. The same and overridden
1228 * by `$post_type_object->label`. Default is 'Posts' / 'Pages'.
1229 * - `singular_name` - Name for one object of this post type. Default is 'Post' / 'Page'.
1230 * - `add_new` - Default is 'Add New' for both hierarchical and non-hierarchical types.
1231 * When internationalizing this string, please use a {@link https://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context}
1232 * matching your post type. Example: `_x( 'Add New', 'product', 'textdomain' );`.
1233 * - `add_new_item` - Label for adding a new singular item. Default is 'Add New Post' / 'Add New Page'.
1234 * - `edit_item` - Label for editing a singular item. Default is 'Edit Post' / 'Edit Page'.
1235 * - `new_item` - Label for the new item page title. Default is 'New Post' / 'New Page'.
1236 * - `view_item` - Label for viewing a singular item. Default is 'View Post' / 'View Page'.
1237 * - `search_items` - Label for searching plural items. Default is 'Search Posts' / 'Search Pages'.
1238 * - `not_found` - Label used when no items are found. Default is 'No posts found' / 'No pages found'.
1239 * - `not_found_in_trash` - Label used when no items are in the trash. Default is 'No posts found in Trash' /
1240 * 'No pages found in Trash'.
1241 * - `parent_item_colon` - Label used to prefix parents of hierarchical items. Not used on non-hierarchical
1242 * post types. Default is 'Parent Page:'.
1243 * - `all_items` - Label to signify all items in a submenu link. Default is 'All Posts' / 'All Pages'.
1244 * - `archives` - Label for archives in nav menus. Default is 'Post Archives' / 'Page Archives'.
1245 * - `insert_into_item` - Label for the media frame button. Default is 'Insert into post' / 'Insert into page'.
1246 * - `uploaded_to_this_item` - Label for the media frame filter. Default is 'Uploaded to this post' /
1247 * 'Uploaded to this page'.
1248 * - `featured_image` - Label for the Featured Image meta box title. Default is 'Featured Image'.
1249 * - `set_featured_image` - Label for setting the featured image. Default is 'Set featured image'.
1250 * - `remove_featured_image` - Label for removing the featured image. Default is 'Remove featured image'.
1251 * - `use_featured_image` - Label in the media frame for using a featured image. Default is 'Use as featured image'.
1252 * - `menu_name` - Label for the menu name. Default is the same as `name`.
1253 * - `filter_items_list` - Label for the table views hidden heading. Default is 'Filter posts list' /
1254 * 'Filter pages list'.
1255 * - `items_list_navigation` - Label for the table pagination hidden heading. Default is 'Posts list navigation' /
1256 * 'Pages list navigation'.
1257 * - `items_list` - Label for the table hidden heading. Default is 'Posts list' / 'Pages list'.
1259 * Above, the first default value is for non-hierarchical post types (like posts)
1260 * and the second one is for hierarchical post types (like pages).
1262 * Note: To set labels used in post type admin notices, see the {@see 'post_updated_messages'} filter.
1265 * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
1266 * and `use_featured_image` labels.
1267 * @since 4.4.0 Added the `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
1268 * `items_list_navigation`, and `items_list` labels.
1269 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1273 * @param object|WP_Post_Type $post_type_object Post type object.
1274 * @return object Object with all the labels as member variables.
1276 function get_post_type_labels( $post_type_object ) {
1277 $nohier_vs_hier_defaults = array(
1278 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1279 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1280 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1281 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1282 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1283 'new_item' => array( __('New Post'), __('New Page') ),
1284 'view_item' => array( __('View Post'), __('View Page') ),
1285 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1286 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1287 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1288 'parent_item_colon' => array( null, __('Parent Page:') ),
1289 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ),
1290 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ),
1291 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ),
1292 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ),
1293 'featured_image' => array( __( 'Featured Image' ), __( 'Featured Image' ) ),
1294 'set_featured_image' => array( __( 'Set featured image' ), __( 'Set featured image' ) ),
1295 'remove_featured_image' => array( __( 'Remove featured image' ), __( 'Remove featured image' ) ),
1296 'use_featured_image' => array( __( 'Use as featured image' ), __( 'Use as featured image' ) ),
1297 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ),
1298 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ),
1299 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ),
1301 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1303 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1305 $post_type = $post_type_object->name;
1307 $default_labels = clone $labels;
1310 * Filters the labels of a specific post type.
1312 * The dynamic portion of the hook name, `$post_type`, refers to
1313 * the post type slug.
1317 * @see get_post_type_labels() for the full list of labels.
1319 * @param object $labels Object with labels for the post type as member variables.
1321 $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
1323 // Ensure that the filtered labels contain all required default values.
1324 $labels = (object) array_merge( (array) $default_labels, (array) $labels );
1330 * Build an object with custom-something object (post type, taxonomy) labels
1331 * out of a custom-something object
1336 * @param object $object A custom-something object.
1337 * @param array $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
1338 * @return object Object containing labels for the given custom-something object.
1340 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1341 $object->labels = (array) $object->labels;
1343 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1344 $object->labels['name'] = $object->label;
1346 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1347 $object->labels['singular_name'] = $object->labels['name'];
1349 if ( ! isset( $object->labels['name_admin_bar'] ) )
1350 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1352 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1353 $object->labels['menu_name'] = $object->labels['name'];
1355 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1356 $object->labels['all_items'] = $object->labels['menu_name'];
1358 if ( !isset( $object->labels['archives'] ) && isset( $object->labels['all_items'] ) ) {
1359 $object->labels['archives'] = $object->labels['all_items'];
1362 $defaults = array();
1363 foreach ( $nohier_vs_hier_defaults as $key => $value ) {
1364 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1366 $labels = array_merge( $defaults, $object->labels );
1367 $object->labels = (object) $object->labels;
1369 return (object) $labels;
1373 * Add submenus for post types.
1378 function _add_post_type_submenus() {
1379 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1380 $ptype_obj = get_post_type_object( $ptype );
1382 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1384 add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
1389 * Register support of certain features for a post type.
1391 * All core features are directly associated with a functional area of the edit
1392 * screen, such as the editor or a meta box. Features include: 'title', 'editor',
1393 * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
1394 * 'thumbnail', 'custom-fields', and 'post-formats'.
1396 * Additionally, the 'revisions' feature dictates whether the post type will
1397 * store revisions, and the 'comments' feature dictates whether the comments
1398 * count will show on the edit screen.
1402 * @global array $_wp_post_type_features
1404 * @param string $post_type The post type for which to add the feature.
1405 * @param string|array $feature The feature being added, accepts an array of
1406 * feature strings or a single string.
1408 function add_post_type_support( $post_type, $feature ) {
1409 global $_wp_post_type_features;
1411 $features = (array) $feature;
1412 foreach ($features as $feature) {
1413 if ( func_num_args() == 2 )
1414 $_wp_post_type_features[$post_type][$feature] = true;
1416 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1421 * Remove support for a feature from a post type.
1425 * @global array $_wp_post_type_features
1427 * @param string $post_type The post type for which to remove the feature.
1428 * @param string $feature The feature being removed.
1430 function remove_post_type_support( $post_type, $feature ) {
1431 global $_wp_post_type_features;
1433 unset( $_wp_post_type_features[ $post_type ][ $feature ] );
1437 * Get all the post type features
1441 * @global array $_wp_post_type_features
1443 * @param string $post_type The post type.
1444 * @return array Post type supports list.
1446 function get_all_post_type_supports( $post_type ) {
1447 global $_wp_post_type_features;
1449 if ( isset( $_wp_post_type_features[$post_type] ) )
1450 return $_wp_post_type_features[$post_type];
1456 * Check a post type's support for a given feature.
1460 * @global array $_wp_post_type_features
1462 * @param string $post_type The post type being checked.
1463 * @param string $feature The feature being checked.
1464 * @return bool Whether the post type supports the given feature.
1466 function post_type_supports( $post_type, $feature ) {
1467 global $_wp_post_type_features;
1469 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1473 * Retrieves a list of post type names that support a specific feature.
1477 * @global array $_wp_post_type_features Post type features
1479 * @param array|string $feature Single feature or an array of features the post types should support.
1480 * @param string $operator Optional. The logical operation to perform. 'or' means
1481 * only one element from the array needs to match; 'and'
1482 * means all elements must match; 'not' means no elements may
1483 * match. Default 'and'.
1484 * @return array A list of post type names.
1486 function get_post_types_by_support( $feature, $operator = 'and' ) {
1487 global $_wp_post_type_features;
1489 $features = array_fill_keys( (array) $feature, true );
1491 return array_keys( wp_filter_object_list( $_wp_post_type_features, $features, $operator ) );
1495 * Update the post type for the post ID.
1497 * The page or post cache will be cleaned for the post ID.
1501 * @global wpdb $wpdb WordPress database abstraction object.
1503 * @param int $post_id Optional. Post ID to change post type. Default 0.
1504 * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
1505 * name a few. Default 'post'.
1506 * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
1508 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1511 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1512 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1514 clean_post_cache( $post_id );
1520 * Determines whether a post type is considered "viewable".
1522 * For built-in post types such as posts and pages, the 'public' value will be evaluated.
1523 * For all others, the 'publicly_queryable' value will be used.
1526 * @since 4.5.0 Added the ability to pass a post type name in addition to object.
1527 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1529 * @param string|WP_Post_Type $post_type Post type name or object.
1530 * @return bool Whether the post type should be considered viewable.
1532 function is_post_type_viewable( $post_type ) {
1533 if ( is_scalar( $post_type ) ) {
1534 $post_type = get_post_type_object( $post_type );
1535 if ( ! $post_type ) {
1540 return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
1544 * Retrieve list of latest posts or posts matching criteria.
1546 * The defaults are as follows:
1550 * @see WP_Query::parse_query()
1552 * @param array $args {
1553 * Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all
1554 * available arguments.
1556 * @type int $numberposts Total number of posts to retrieve. Is an alias of $posts_per_page
1557 * in WP_Query. Accepts -1 for all. Default 5.
1558 * @type int|string $category Category ID or comma-separated list of IDs (this or any children).
1559 * Is an alias of $cat in WP_Query. Default 0.
1560 * @type array $include An array of post IDs to retrieve, sticky posts will be included.
1561 * Is an alias of $post__in in WP_Query. Default empty array.
1562 * @type array $exclude An array of post IDs not to retrieve. Default empty array.
1563 * @type bool $suppress_filters Whether to suppress filters. Default true.
1565 * @return array List of posts.
1567 function get_posts( $args = null ) {
1570 'category' => 0, 'orderby' => 'date',
1571 'order' => 'DESC', 'include' => array(),
1572 'exclude' => array(), 'meta_key' => '',
1573 'meta_value' =>'', 'post_type' => 'post',
1574 'suppress_filters' => true
1577 $r = wp_parse_args( $args, $defaults );
1578 if ( empty( $r['post_status'] ) )
1579 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1580 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1581 $r['posts_per_page'] = $r['numberposts'];
1582 if ( ! empty($r['category']) )
1583 $r['cat'] = $r['category'];
1584 if ( ! empty($r['include']) ) {
1585 $incposts = wp_parse_id_list( $r['include'] );
1586 $r['posts_per_page'] = count($incposts); // only the number of posts included
1587 $r['post__in'] = $incposts;
1588 } elseif ( ! empty($r['exclude']) )
1589 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1591 $r['ignore_sticky_posts'] = true;
1592 $r['no_found_rows'] = true;
1594 $get_posts = new WP_Query;
1595 return $get_posts->query($r);
1600 // Post meta functions
1604 * Add meta data field to a post.
1606 * Post meta data is called "Custom Fields" on the Administration Screen.
1610 * @param int $post_id Post ID.
1611 * @param string $meta_key Metadata name.
1612 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1613 * @param bool $unique Optional. Whether the same key should not be added.
1615 * @return int|false Meta ID on success, false on failure.
1617 function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
1618 // Make sure meta is added to the post, not a revision.
1619 if ( $the_post = wp_is_post_revision($post_id) )
1620 $post_id = $the_post;
1622 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1626 * Remove metadata matching criteria from a post.
1628 * You can match based on the key, or key and value. Removing based on key and
1629 * value, will keep from removing duplicate metadata with the same key. It also
1630 * allows removing all metadata matching key, if needed.
1634 * @param int $post_id Post ID.
1635 * @param string $meta_key Metadata name.
1636 * @param mixed $meta_value Optional. Metadata value. Must be serializable if
1637 * non-scalar. Default empty.
1638 * @return bool True on success, false on failure.
1640 function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
1641 // Make sure meta is added to the post, not a revision.
1642 if ( $the_post = wp_is_post_revision($post_id) )
1643 $post_id = $the_post;
1645 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1649 * Retrieve post meta field for a post.
1653 * @param int $post_id Post ID.
1654 * @param string $key Optional. The meta key to retrieve. By default, returns
1655 * data for all keys. Default empty.
1656 * @param bool $single Optional. Whether to return a single value. Default false.
1657 * @return mixed Will be an array if $single is false. Will be value of meta data
1658 * field if $single is true.
1660 function get_post_meta( $post_id, $key = '', $single = false ) {
1661 return get_metadata('post', $post_id, $key, $single);
1665 * Update post meta field based on post ID.
1667 * Use the $prev_value parameter to differentiate between meta fields with the
1668 * same key and post ID.
1670 * If the meta field for the post does not exist, it will be added.
1674 * @param int $post_id Post ID.
1675 * @param string $meta_key Metadata key.
1676 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1677 * @param mixed $prev_value Optional. Previous value to check before removing.
1679 * @return int|bool Meta ID if the key didn't exist, true on successful update,
1682 function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
1683 // Make sure meta is added to the post, not a revision.
1684 if ( $the_post = wp_is_post_revision($post_id) )
1685 $post_id = $the_post;
1687 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1691 * Delete everything from post meta matching meta key.
1695 * @param string $post_meta_key Key to search for when deleting.
1696 * @return bool Whether the post meta key was deleted from the database.
1698 function delete_post_meta_by_key( $post_meta_key ) {
1699 return delete_metadata( 'post', null, $post_meta_key, '', true );
1703 * Retrieve post meta fields, based on post ID.
1705 * The post meta fields are retrieved from the cache where possible,
1706 * so the function is optimized to be called more than once.
1710 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1711 * @return array Post meta for the given post.
1713 function get_post_custom( $post_id = 0 ) {
1714 $post_id = absint( $post_id );
1716 $post_id = get_the_ID();
1718 return get_post_meta( $post_id );
1722 * Retrieve meta field names for a post.
1724 * If there are no meta fields, then nothing (null) will be returned.
1728 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1729 * @return array|void Array of the keys, if retrieved.
1731 function get_post_custom_keys( $post_id = 0 ) {
1732 $custom = get_post_custom( $post_id );
1734 if ( !is_array($custom) )
1737 if ( $keys = array_keys($custom) )
1742 * Retrieve values for a custom post field.
1744 * The parameters must not be considered optional. All of the post meta fields
1745 * will be retrieved and only the meta field key values returned.
1749 * @param string $key Optional. Meta field key. Default empty.
1750 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1751 * @return array|null Meta field values.
1753 function get_post_custom_values( $key = '', $post_id = 0 ) {
1757 $custom = get_post_custom($post_id);
1759 return isset($custom[$key]) ? $custom[$key] : null;
1763 * Check if post is sticky.
1765 * Sticky posts should remain at the top of The Loop. If the post ID is not
1766 * given, then The Loop ID for the current post will be used.
1770 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1771 * @return bool Whether post is sticky.
1773 function is_sticky( $post_id = 0 ) {
1774 $post_id = absint( $post_id );
1777 $post_id = get_the_ID();
1779 $stickies = get_option( 'sticky_posts' );
1781 if ( ! is_array( $stickies ) )
1784 if ( in_array( $post_id, $stickies ) )
1791 * Sanitize every post field.
1793 * If the context is 'raw', then the post object or array will get minimal
1794 * sanitization of the integer fields.
1798 * @see sanitize_post_field()
1800 * @param object|WP_Post|array $post The Post Object or Array
1801 * @param string $context Optional. How to sanitize post fields.
1802 * Accepts 'raw', 'edit', 'db', or 'display'.
1803 * Default 'display'.
1804 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the
1805 * same type as $post).
1807 function sanitize_post( $post, $context = 'display' ) {
1808 if ( is_object($post) ) {
1809 // Check if post already filtered for this context.
1810 if ( isset($post->filter) && $context == $post->filter )
1812 if ( !isset($post->ID) )
1814 foreach ( array_keys(get_object_vars($post)) as $field )
1815 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1816 $post->filter = $context;
1817 } elseif ( is_array( $post ) ) {
1818 // Check if post already filtered for this context.
1819 if ( isset($post['filter']) && $context == $post['filter'] )
1821 if ( !isset($post['ID']) )
1823 foreach ( array_keys($post) as $field )
1824 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1825 $post['filter'] = $context;
1831 * Sanitize post field based on context.
1833 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and
1834 * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
1835 * are treated like 'display' when calling filters.
1838 * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
1840 * @param string $field The Post Object field name.
1841 * @param mixed $value The Post Object value.
1842 * @param int $post_id Post ID.
1843 * @param string $context Optional. How to sanitize post fields. Looks for 'raw', 'edit',
1844 * 'db', 'display', 'attribute' and 'js'. Default 'display'.
1845 * @return mixed Sanitized value.
1847 function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
1848 $int_fields = array('ID', 'post_parent', 'menu_order');
1849 if ( in_array($field, $int_fields) )
1850 $value = (int) $value;
1852 // Fields which contain arrays of integers.
1853 $array_int_fields = array( 'ancestors' );
1854 if ( in_array($field, $array_int_fields) ) {
1855 $value = array_map( 'absint', $value);
1859 if ( 'raw' == $context )
1863 if ( false !== strpos($field, 'post_') ) {
1865 $field_no_prefix = str_replace('post_', '', $field);
1868 if ( 'edit' == $context ) {
1869 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1874 * Filters the value of a specific post field to edit.
1876 * The dynamic portion of the hook name, `$field`, refers to the post
1881 * @param mixed $value Value of the post field.
1882 * @param int $post_id Post ID.
1884 $value = apply_filters( "edit_{$field}", $value, $post_id );
1887 * Filters the value of a specific post field to edit.
1889 * The dynamic portion of the hook name, `$field_no_prefix`, refers to
1890 * the post field name.
1894 * @param mixed $value Value of the post field.
1895 * @param int $post_id Post ID.
1897 $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
1899 $value = apply_filters( "edit_post_{$field}", $value, $post_id );
1902 if ( in_array($field, $format_to_edit) ) {
1903 if ( 'post_content' == $field )
1904 $value = format_to_edit($value, user_can_richedit());
1906 $value = format_to_edit($value);
1908 $value = esc_attr($value);
1910 } elseif ( 'db' == $context ) {
1914 * Filters the value of a specific post field before saving.
1916 * The dynamic portion of the hook name, `$field`, refers to the post
1921 * @param mixed $value Value of the post field.
1923 $value = apply_filters( "pre_{$field}", $value );
1926 * Filters the value of a specific field before saving.
1928 * The dynamic portion of the hook name, `$field_no_prefix`, refers
1929 * to the post field name.
1933 * @param mixed $value Value of the post field.
1935 $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
1937 $value = apply_filters( "pre_post_{$field}", $value );
1940 * Filters the value of a specific post field before saving.
1942 * The dynamic portion of the hook name, `$field`, refers to the post
1947 * @param mixed $value Value of the post field.
1949 $value = apply_filters( "{$field}_pre", $value );
1953 // Use display filters by default.
1957 * Filters the value of a specific post field for display.
1959 * The dynamic portion of the hook name, `$field`, refers to the post
1964 * @param mixed $value Value of the prefixed post field.
1965 * @param int $post_id Post ID.
1966 * @param string $context Context for how to sanitize the field. Possible
1967 * values include 'raw', 'edit', 'db', 'display',
1968 * 'attribute' and 'js'.
1970 $value = apply_filters( $field, $value, $post_id, $context );
1972 $value = apply_filters( "post_{$field}", $value, $post_id, $context );
1975 if ( 'attribute' == $context ) {
1976 $value = esc_attr( $value );
1977 } elseif ( 'js' == $context ) {
1978 $value = esc_js( $value );
1986 * Make a post sticky.
1988 * Sticky posts should be displayed at the top of the front page.
1992 * @param int $post_id Post ID.
1994 function stick_post( $post_id ) {
1995 $stickies = get_option('sticky_posts');
1997 if ( !is_array($stickies) )
1998 $stickies = array($post_id);
2000 if ( ! in_array($post_id, $stickies) )
2001 $stickies[] = $post_id;
2003 $updated = update_option( 'sticky_posts', $stickies );
2007 * Fires once a post has been added to the sticky list.
2011 * @param int $post_id ID of the post that was stuck.
2013 do_action( 'post_stuck', $post_id );
2020 * Sticky posts should be displayed at the top of the front page.
2024 * @param int $post_id Post ID.
2026 function unstick_post( $post_id ) {
2027 $stickies = get_option('sticky_posts');
2029 if ( !is_array($stickies) )
2032 if ( ! in_array($post_id, $stickies) )
2035 $offset = array_search($post_id, $stickies);
2036 if ( false === $offset )
2039 array_splice($stickies, $offset, 1);
2041 $updated = update_option( 'sticky_posts', $stickies );
2045 * Fires once a post has been removed from the sticky list.
2049 * @param int $post_id ID of the post that was unstuck.
2051 do_action( 'post_unstuck', $post_id );
2056 * Return the cache key for wp_count_posts() based on the passed arguments.
2060 * @param string $type Optional. Post type to retrieve count Default 'post'.
2061 * @param string $perm Optional. 'readable' or empty. Default empty.
2062 * @return string The cache key.
2064 function _count_posts_cache_key( $type = 'post', $perm = '' ) {
2065 $cache_key = 'posts-' . $type;
2066 if ( 'readable' == $perm && is_user_logged_in() ) {
2067 $post_type_object = get_post_type_object( $type );
2068 if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2069 $cache_key .= '_' . $perm . '_' . get_current_user_id();
2076 * Count number of posts of a post type and if user has permissions to view.
2078 * This function provides an efficient method of finding the amount of post's
2079 * type a blog has. Another method is to count the amount of items in
2080 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2081 * when developing for 2.5+, use this function instead.
2083 * The $perm parameter checks for 'readable' value and if the user can read
2084 * private posts, it will display that for the user that is signed in.
2088 * @global wpdb $wpdb WordPress database abstraction object.
2090 * @param string $type Optional. Post type to retrieve count. Default 'post'.
2091 * @param string $perm Optional. 'readable' or empty. Default empty.
2092 * @return object Number of posts for each status.
2094 function wp_count_posts( $type = 'post', $perm = '' ) {
2097 if ( ! post_type_exists( $type ) )
2098 return new stdClass;
2100 $cache_key = _count_posts_cache_key( $type, $perm );
2102 $counts = wp_cache_get( $cache_key, 'counts' );
2103 if ( false !== $counts ) {
2104 /** This filter is documented in wp-includes/post.php */
2105 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2108 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2109 if ( 'readable' == $perm && is_user_logged_in() ) {
2110 $post_type_object = get_post_type_object($type);
2111 if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2112 $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
2113 get_current_user_id()
2117 $query .= ' GROUP BY post_status';
2119 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2120 $counts = array_fill_keys( get_post_stati(), 0 );
2122 foreach ( $results as $row ) {
2123 $counts[ $row['post_status'] ] = $row['num_posts'];
2126 $counts = (object) $counts;
2127 wp_cache_set( $cache_key, $counts, 'counts' );
2130 * Modify returned post counts by status for the current post type.
2134 * @param object $counts An object containing the current post_type's post
2136 * @param string $type Post type.
2137 * @param string $perm The permission to determine if the posts are 'readable'
2138 * by the current user.
2140 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2144 * Count number of attachments for the mime type(s).
2146 * If you set the optional mime_type parameter, then an array will still be
2147 * returned, but will only have the item you are looking for. It does not give
2148 * you the number of attachments that are children of a post. You can get that
2149 * by counting the number of children that post has.
2153 * @global wpdb $wpdb WordPress database abstraction object.
2155 * @param string|array $mime_type Optional. Array or comma-separated list of
2156 * MIME patterns. Default empty.
2157 * @return object An object containing the attachment counts by mime type.
2159 function wp_count_attachments( $mime_type = '' ) {
2162 $and = wp_post_mime_type_where( $mime_type );
2163 $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
2166 foreach ( (array) $count as $row ) {
2167 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2169 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2172 * Modify returned attachment counts by mime type.
2176 * @param object $counts An object containing the attachment counts by
2178 * @param string $mime_type The mime type pattern used to filter the attachments
2181 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2185 * Get default post mime types.
2189 * @return array List of post mime types.
2191 function get_post_mime_types() {
2192 $post_mime_types = array( // array( adj, noun )
2193 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2194 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2195 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2199 * Filters the default list of post mime types.
2203 * @param array $post_mime_types Default list of post mime types.
2205 return apply_filters( 'post_mime_types', $post_mime_types );
2209 * Check a MIME-Type against a list.
2211 * If the wildcard_mime_types parameter is a string, it must be comma separated
2212 * list. If the real_mime_types is a string, it is also comma separated to
2217 * @param string|array $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
2218 * or flash (same as *flash*).
2219 * @param string|array $real_mime_types Real post mime type values.
2220 * @return array array(wildcard=>array(real types)).
2222 function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
2224 if ( is_string( $wildcard_mime_types ) ) {
2225 $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
2227 if ( is_string( $real_mime_types ) ) {
2228 $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
2231 $patternses = array();
2232 $wild = '[-._a-z0-9]*';
2234 foreach ( (array) $wildcard_mime_types as $type ) {
2235 $mimes = array_map( 'trim', explode( ',', $type ) );
2236 foreach ( $mimes as $mime ) {
2237 $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
2238 $patternses[][$type] = "^$regex$";
2239 if ( false === strpos( $mime, '/' ) ) {
2240 $patternses[][$type] = "^$regex/";
2241 $patternses[][$type] = $regex;
2245 asort( $patternses );
2247 foreach ( $patternses as $patterns ) {
2248 foreach ( $patterns as $type => $pattern ) {
2249 foreach ( (array) $real_mime_types as $real ) {
2250 if ( preg_match( "#$pattern#", $real ) && ( empty( $matches[$type] ) || false === array_search( $real, $matches[$type] ) ) ) {
2251 $matches[$type][] = $real;
2260 * Convert MIME types into SQL.
2264 * @param string|array $post_mime_types List of mime types or comma separated string
2266 * @param string $table_alias Optional. Specify a table alias, if needed.
2268 * @return string The SQL AND clause for mime searching.
2270 function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
2272 $wildcards = array('', '%', '%/%');
2273 if ( is_string($post_mime_types) )
2274 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2278 foreach ( (array) $post_mime_types as $mime_type ) {
2279 $mime_type = preg_replace('/\s/', '', $mime_type);
2280 $slashpos = strpos($mime_type, '/');
2281 if ( false !== $slashpos ) {
2282 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2283 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2284 if ( empty($mime_subgroup) )
2285 $mime_subgroup = '*';
2287 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2288 $mime_pattern = "$mime_group/$mime_subgroup";
2290 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2291 if ( false === strpos($mime_pattern, '*') )
2292 $mime_pattern .= '/*';
2295 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2297 if ( in_array( $mime_type, $wildcards ) )
2300 if ( false !== strpos($mime_pattern, '%') )
2301 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2303 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2305 if ( !empty($wheres) )
2306 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2311 * Trash or delete a post or page.
2313 * When the post and page is permanently deleted, everything that is tied to
2314 * it is deleted also. This includes comments, post meta fields, and terms
2315 * associated with the post.
2317 * The post or page is moved to trash instead of permanently deleted unless
2318 * trash is disabled, item is already in the trash, or $force_delete is true.
2322 * @global wpdb $wpdb WordPress database abstraction object.
2323 * @see wp_delete_attachment()
2324 * @see wp_trash_post()
2326 * @param int $postid Optional. Post ID. Default 0.
2327 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
2329 * @return array|false|WP_Post False on failure.
2331 function wp_delete_post( $postid = 0, $force_delete = false ) {
2334 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2337 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2338 return wp_trash_post( $postid );
2340 if ( $post->post_type == 'attachment' )
2341 return wp_delete_attachment( $postid, $force_delete );
2344 * Filters whether a post deletion should take place.
2348 * @param bool $delete Whether to go forward with deletion.
2349 * @param WP_Post $post Post object.
2350 * @param bool $force_delete Whether to bypass the trash.
2352 $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
2353 if ( null !== $check ) {
2358 * Fires before a post is deleted, at the start of wp_delete_post().
2362 * @see wp_delete_post()
2364 * @param int $postid Post ID.
2366 do_action( 'before_delete_post', $postid );
2368 delete_post_meta($postid,'_wp_trash_meta_status');
2369 delete_post_meta($postid,'_wp_trash_meta_time');
2371 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2373 $parent_data = array( 'post_parent' => $post->post_parent );
2374 $parent_where = array( 'post_parent' => $postid );
2376 if ( is_post_type_hierarchical( $post->post_type ) ) {
2377 // Point children of this page to its parent, also clean the cache of affected children.
2378 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2379 $children = $wpdb->get_results( $children_query );
2381 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2385 // Do raw query. wp_get_post_revisions() is filtered.
2386 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2387 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2388 foreach ( $revision_ids as $revision_id )
2389 wp_delete_post_revision( $revision_id );
2391 // Point all attachments to this post up one level.
2392 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2394 wp_defer_comment_counting( true );
2396 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2397 foreach ( $comment_ids as $comment_id ) {
2398 wp_delete_comment( $comment_id, true );
2401 wp_defer_comment_counting( false );
2403 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2404 foreach ( $post_meta_ids as $mid )
2405 delete_metadata_by_mid( 'post', $mid );
2408 * Fires immediately before a post is deleted from the database.
2412 * @param int $postid Post ID.
2414 do_action( 'delete_post', $postid );
2415 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2421 * Fires immediately after a post is deleted from the database.
2425 * @param int $postid Post ID.
2427 do_action( 'deleted_post', $postid );
2429 clean_post_cache( $post );
2431 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2432 foreach ( $children as $child )
2433 clean_post_cache( $child );
2436 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2439 * Fires after a post is deleted, at the conclusion of wp_delete_post().
2443 * @see wp_delete_post()
2445 * @param int $postid Post ID.
2447 do_action( 'after_delete_post', $postid );
2453 * Reset the page_on_front, show_on_front, and page_for_post settings when
2454 * a linked page is deleted or trashed.
2456 * Also ensures the post is no longer sticky.
2461 * @param int $post_id Post ID.
2463 function _reset_front_page_settings_for_post( $post_id ) {
2464 $post = get_post( $post_id );
2465 if ( 'page' == $post->post_type ) {
2467 * If the page is defined in option page_on_front or post_for_posts,
2468 * adjust the corresponding options.
2470 if ( get_option( 'page_on_front' ) == $post->ID ) {
2471 update_option( 'show_on_front', 'posts' );
2472 update_option( 'page_on_front', 0 );
2474 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2475 delete_option( 'page_for_posts', 0 );
2478 unstick_post( $post->ID );
2482 * Move a post or page to the Trash
2484 * If trash is disabled, the post or page is permanently deleted.
2488 * @see wp_delete_post()
2490 * @param int $post_id Optional. Post ID. Default is ID of the global $post
2491 * if EMPTY_TRASH_DAYS equals true.
2492 * @return false|array|WP_Post|null Post data array, otherwise false.
2494 function wp_trash_post( $post_id = 0 ) {
2495 if ( !EMPTY_TRASH_DAYS )
2496 return wp_delete_post($post_id, true);
2498 if ( !$post = get_post($post_id, ARRAY_A) )
2501 if ( $post['post_status'] == 'trash' )
2505 * Fires before a post is sent to the trash.
2509 * @param int $post_id Post ID.
2511 do_action( 'wp_trash_post', $post_id );
2513 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2514 add_post_meta($post_id,'_wp_trash_meta_time', time());
2516 $post['post_status'] = 'trash';
2517 wp_insert_post( wp_slash( $post ) );
2519 wp_trash_post_comments($post_id);
2522 * Fires after a post is sent to the trash.
2526 * @param int $post_id Post ID.
2528 do_action( 'trashed_post', $post_id );
2534 * Restore a post or page from the Trash.
2538 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2539 * @return WP_Post|false WP_Post object. False on failure.
2541 function wp_untrash_post( $post_id = 0 ) {
2542 if ( !$post = get_post($post_id, ARRAY_A) )
2545 if ( $post['post_status'] != 'trash' )
2549 * Fires before a post is restored from the trash.
2553 * @param int $post_id Post ID.
2555 do_action( 'untrash_post', $post_id );
2557 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2559 $post['post_status'] = $post_status;
2561 delete_post_meta($post_id, '_wp_trash_meta_status');
2562 delete_post_meta($post_id, '_wp_trash_meta_time');
2564 wp_insert_post( wp_slash( $post ) );
2566 wp_untrash_post_comments($post_id);
2569 * Fires after a post is restored from the trash.
2573 * @param int $post_id Post ID.
2575 do_action( 'untrashed_post', $post_id );
2581 * Moves comments for a post to the trash.
2585 * @global wpdb $wpdb WordPress database abstraction object.
2587 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2588 * @return mixed|void False on failure.
2590 function wp_trash_post_comments( $post = null ) {
2593 $post = get_post($post);
2597 $post_id = $post->ID;
2600 * Fires before comments are sent to the trash.
2604 * @param int $post_id Post ID.
2606 do_action( 'trash_post_comments', $post_id );
2608 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2609 if ( empty($comments) )
2612 // Cache current status for each comment.
2613 $statuses = array();
2614 foreach ( $comments as $comment )
2615 $statuses[$comment->comment_ID] = $comment->comment_approved;
2616 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2618 // Set status for all comments to post-trashed.
2619 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2621 clean_comment_cache( array_keys($statuses) );
2624 * Fires after comments are sent to the trash.
2628 * @param int $post_id Post ID.
2629 * @param array $statuses Array of comment statuses.
2631 do_action( 'trashed_post_comments', $post_id, $statuses );
2637 * Restore comments for a post from the trash.
2641 * @global wpdb $wpdb WordPress database abstraction object.
2643 * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2646 function wp_untrash_post_comments( $post = null ) {
2649 $post = get_post($post);
2653 $post_id = $post->ID;
2655 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2657 if ( empty($statuses) )
2661 * Fires before comments are restored for a post from the trash.
2665 * @param int $post_id Post ID.
2667 do_action( 'untrash_post_comments', $post_id );
2669 // Restore each comment to its original status.
2670 $group_by_status = array();
2671 foreach ( $statuses as $comment_id => $comment_status )
2672 $group_by_status[$comment_status][] = $comment_id;
2674 foreach ( $group_by_status as $status => $comments ) {
2675 // Sanity check. This shouldn't happen.
2676 if ( 'post-trashed' == $status ) {
2679 $comments_in = implode( ', ', array_map( 'intval', $comments ) );
2680 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
2683 clean_comment_cache( array_keys($statuses) );
2685 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2688 * Fires after comments are restored for a post from the trash.
2692 * @param int $post_id Post ID.
2694 do_action( 'untrashed_post_comments', $post_id );
2698 * Retrieve the list of categories for a post.
2700 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2701 * away from the complexity of the taxonomy layer.
2705 * @see wp_get_object_terms()
2707 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2708 * global $post. Default 0.
2709 * @param array $args Optional. Category arguments. See wp_get_object_terms(). Default empty.
2710 * @return array List of categories. If the `$fields` argument passed via `$args` is 'all' or
2711 * 'all_with_object_id', an array of WP_Term objects will be returned. If `$fields`
2712 * is 'ids', an array of category ids. If `$fields` is 'names', an array of category names.
2714 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2715 $post_id = (int) $post_id;
2717 $defaults = array('fields' => 'ids');
2718 $args = wp_parse_args( $args, $defaults );
2720 $cats = wp_get_object_terms($post_id, 'category', $args);
2725 * Retrieve the tags for a post.
2727 * There is only one default for this function, called 'fields' and by default
2728 * is set to 'all'. There are other defaults that can be overridden in
2729 * wp_get_object_terms().
2733 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2734 * global $post. Default 0.
2735 * @param array $args Optional. Overwrite the defaults
2736 * @return array List of post tags.
2738 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2739 return wp_get_post_terms( $post_id, 'post_tag', $args);
2743 * Retrieve the terms for a post.
2745 * There is only one default for this function, called 'fields' and by default
2746 * is set to 'all'. There are other defaults that can be overridden in
2747 * wp_get_object_terms().
2751 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2752 * global $post. Default 0.
2753 * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
2754 * @param array $args Optional. wp_get_object_terms() arguments. Default empty array.
2755 * @return array|WP_Error List of post terms or empty array if no terms were found. WP_Error object
2756 * if `$taxonomy` doesn't exist.
2758 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2759 $post_id = (int) $post_id;
2761 $defaults = array('fields' => 'all');
2762 $args = wp_parse_args( $args, $defaults );
2764 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2770 * Retrieve a number of recent posts.
2776 * @param array $args Optional. Arguments to retrieve posts. Default empty array.
2777 * @param string $output Optional. Type of output. Accepts ARRAY_A or ''. Default ARRAY_A.
2778 * @return array|false Associative array if $output equals ARRAY_A, array or false if no results.
2780 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2782 if ( is_numeric( $args ) ) {
2783 _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2784 $args = array( 'numberposts' => absint( $args ) );
2787 // Set default arguments.
2789 'numberposts' => 10, 'offset' => 0,
2790 'category' => 0, 'orderby' => 'post_date',
2791 'order' => 'DESC', 'include' => '',
2792 'exclude' => '', 'meta_key' => '',
2793 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2794 'suppress_filters' => true
2797 $r = wp_parse_args( $args, $defaults );
2799 $results = get_posts( $r );
2801 // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
2802 if ( ARRAY_A == $output ){
2803 foreach ( $results as $key => $result ) {
2804 $results[$key] = get_object_vars( $result );
2806 return $results ? $results : array();
2809 return $results ? $results : false;
2814 * Insert or update a post.
2816 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2818 * You can set the post date manually, by setting the values for 'post_date'
2819 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2820 * setting the value for 'comment_status' key.
2823 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
2824 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
2826 * @see sanitize_post()
2827 * @global wpdb $wpdb WordPress database abstraction object.
2829 * @param array $postarr {
2830 * An array of elements that make up a post to update or insert.
2832 * @type int $ID The post ID. If equal to something other than 0,
2833 * the post with that ID will be updated. Default 0.
2834 * @type int $post_author The ID of the user who added the post. Default is
2835 * the current user ID.
2836 * @type string $post_date The date of the post. Default is the current time.
2837 * @type string $post_date_gmt The date of the post in the GMT timezone. Default is
2838 * the value of `$post_date`.
2839 * @type mixed $post_content The post content. Default empty.
2840 * @type string $post_content_filtered The filtered post content. Default empty.
2841 * @type string $post_title The post title. Default empty.
2842 * @type string $post_excerpt The post excerpt. Default empty.
2843 * @type string $post_status The post status. Default 'draft'.
2844 * @type string $post_type The post type. Default 'post'.
2845 * @type string $comment_status Whether the post can accept comments. Accepts 'open' or 'closed'.
2846 * Default is the value of 'default_comment_status' option.
2847 * @type string $ping_status Whether the post can accept pings. Accepts 'open' or 'closed'.
2848 * Default is the value of 'default_ping_status' option.
2849 * @type string $post_password The password to access the post. Default empty.
2850 * @type string $post_name The post name. Default is the sanitized post title
2851 * when creating a new post.
2852 * @type string $to_ping Space or carriage return-separated list of URLs to ping.
2854 * @type string $pinged Space or carriage return-separated list of URLs that have
2855 * been pinged. Default empty.
2856 * @type string $post_modified The date when the post was last modified. Default is
2858 * @type string $post_modified_gmt The date when the post was last modified in the GMT
2859 * timezone. Default is the current time.
2860 * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
2861 * @type int $menu_order The order the post should be displayed in. Default 0.
2862 * @type string $post_mime_type The mime type of the post. Default empty.
2863 * @type string $guid Global Unique ID for referencing the post. Default empty.
2864 * @type array $post_category Array of category names, slugs, or IDs.
2865 * Defaults to value of the 'default_category' option.
2866 * @type array $tax_input Array of taxonomy terms keyed by their taxonomy name. Default empty.
2867 * @type array $meta_input Array of post meta values keyed by their post meta key. Default empty.
2869 * @param bool $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
2870 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2872 function wp_insert_post( $postarr, $wp_error = false ) {
2875 $user_id = get_current_user_id();
2878 'post_author' => $user_id,
2879 'post_content' => '',
2880 'post_content_filtered' => '',
2882 'post_excerpt' => '',
2883 'post_status' => 'draft',
2884 'post_type' => 'post',
2885 'comment_status' => '',
2886 'ping_status' => '',
2887 'post_password' => '',
2897 $postarr = wp_parse_args($postarr, $defaults);
2899 unset( $postarr[ 'filter' ] );
2901 $postarr = sanitize_post($postarr, 'db');
2903 // Are we updating or creating?
2906 $guid = $postarr['guid'];
2908 if ( ! empty( $postarr['ID'] ) ) {
2911 // Get the post ID and GUID.
2912 $post_ID = $postarr['ID'];
2913 $post_before = get_post( $post_ID );
2914 if ( is_null( $post_before ) ) {
2916 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2921 $guid = get_post_field( 'guid', $post_ID );
2922 $previous_status = get_post_field('post_status', $post_ID );
2924 $previous_status = 'new';
2927 $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
2929 $post_title = $postarr['post_title'];
2930 $post_content = $postarr['post_content'];
2931 $post_excerpt = $postarr['post_excerpt'];
2932 if ( isset( $postarr['post_name'] ) ) {
2933 $post_name = $postarr['post_name'];
2934 } elseif ( $update ) {
2935 // For an update, don't modify the post_name if it wasn't supplied as an argument.
2936 $post_name = $post_before->post_name;
2939 $maybe_empty = 'attachment' !== $post_type
2940 && ! $post_content && ! $post_title && ! $post_excerpt
2941 && post_type_supports( $post_type, 'editor' )
2942 && post_type_supports( $post_type, 'title' )
2943 && post_type_supports( $post_type, 'excerpt' );
2946 * Filters whether the post should be considered "empty".
2948 * The post is considered "empty" if both:
2949 * 1. The post type supports the title, editor, and excerpt fields
2950 * 2. The title, editor, and excerpt fields are all empty
2952 * Returning a truthy value to the filter will effectively short-circuit
2953 * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
2954 * will be returned instead.
2958 * @param bool $maybe_empty Whether the post should be considered "empty".
2959 * @param array $postarr Array of post data.
2961 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2963 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2969 $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
2970 if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash' ) ) ) {
2971 $post_status = 'inherit';
2974 if ( ! empty( $postarr['post_category'] ) ) {
2975 // Filter out empty terms.
2976 $post_category = array_filter( $postarr['post_category'] );
2979 // Make sure we set a valid category.
2980 if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
2981 // 'post' requires at least one category.
2982 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
2983 $post_category = array( get_option('default_category') );
2985 $post_category = array();
2989 // Don't allow contributors to set the post slug for pending review posts.
2990 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
2995 * Create a valid post name. Drafts and pending posts are allowed to have
2996 * an empty post name.
2998 if ( empty($post_name) ) {
2999 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3000 $post_name = sanitize_title($post_title);
3005 // On updates, we need to check to see if it's using the old, fixed sanitization context.
3006 $check_name = sanitize_title( $post_name, '', 'old-save' );
3007 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
3008 $post_name = $check_name;
3009 } else { // new post, or slug has changed.
3010 $post_name = sanitize_title($post_name);
3015 * If the post date is empty (due to having been new or a draft) and status
3016 * is not 'draft' or 'pending', set date to now.
3018 if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
3019 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3020 $post_date = current_time( 'mysql' );
3022 $post_date = get_date_from_gmt( $postarr['post_date_gmt'] );
3025 $post_date = $postarr['post_date'];
3028 // Validate the date.
3029 $mm = substr( $post_date, 5, 2 );
3030 $jj = substr( $post_date, 8, 2 );
3031 $aa = substr( $post_date, 0, 4 );
3032 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
3033 if ( ! $valid_date ) {
3035 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
3041 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3042 if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3043 $post_date_gmt = get_gmt_from_date( $post_date );
3045 $post_date_gmt = '0000-00-00 00:00:00';
3048 $post_date_gmt = $postarr['post_date_gmt'];
3051 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
3052 $post_modified = current_time( 'mysql' );
3053 $post_modified_gmt = current_time( 'mysql', 1 );
3055 $post_modified = $post_date;
3056 $post_modified_gmt = $post_date_gmt;
3059 if ( 'attachment' !== $post_type ) {
3060 if ( 'publish' == $post_status ) {
3061 $now = gmdate('Y-m-d H:i:59');
3062 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
3063 $post_status = 'future';
3065 } elseif ( 'future' == $post_status ) {
3066 $now = gmdate('Y-m-d H:i:59');
3067 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) {
3068 $post_status = 'publish';
3074 if ( empty( $postarr['comment_status'] ) ) {
3076 $comment_status = 'closed';
3078 $comment_status = get_default_comment_status( $post_type );
3081 $comment_status = $postarr['comment_status'];
3084 // These variables are needed by compact() later.
3085 $post_content_filtered = $postarr['post_content_filtered'];
3086 $post_author = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
3087 $ping_status = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
3088 $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
3089 $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
3090 $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
3093 * The 'wp_insert_post_parent' filter expects all variables to be present.
3094 * Previously, these variables would have already been extracted
3096 if ( isset( $postarr['menu_order'] ) ) {
3097 $menu_order = (int) $postarr['menu_order'];
3102 $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
3103 if ( 'private' == $post_status ) {
3104 $post_password = '';
3107 if ( isset( $postarr['post_parent'] ) ) {
3108 $post_parent = (int) $postarr['post_parent'];
3114 * Filters the post parent -- used to check for and prevent hierarchy loops.
3118 * @param int $post_parent Post parent ID.
3119 * @param int $post_ID Post ID.
3120 * @param array $new_postarr Array of parsed post data.
3121 * @param array $postarr Array of sanitized, but otherwise unmodified post data.
3123 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
3126 * If the post is being untrashed and it has a desired slug stored in post meta,
3129 if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
3130 $desired_post_slug = get_post_meta( $post_ID, '_wp_desired_post_slug', true );
3131 if ( $desired_post_slug ) {
3132 delete_post_meta( $post_ID, '_wp_desired_post_slug' );
3133 $post_name = $desired_post_slug;
3137 // If a trashed post has the desired slug, change it and let this post have it.
3138 if ( 'trash' !== $post_status && $post_name ) {
3139 wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID );
3142 // When trashing an existing post, change its slug to allow non-trashed posts to use it.
3143 if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
3144 $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_ID );
3147 $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
3150 $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
3152 // Expected_slashed (everything!).
3153 $data = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' );
3155 $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
3157 foreach ( $emoji_fields as $emoji_field ) {
3158 if ( isset( $data[ $emoji_field ] ) ) {
3159 $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
3160 if ( 'utf8' === $charset ) {
3161 $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
3166 if ( 'attachment' === $post_type ) {
3168 * Filters attachment post data before it is updated in or added to the database.
3172 * @param array $data An array of sanitized attachment post data.
3173 * @param array $postarr An array of unsanitized attachment post data.
3175 $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
3178 * Filters slashed post data just before it is inserted into the database.
3182 * @param array $data An array of slashed post data.
3183 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3185 $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
3187 $data = wp_unslash( $data );
3188 $where = array( 'ID' => $post_ID );
3192 * Fires immediately before an existing post is updated in the database.
3196 * @param int $post_ID Post ID.
3197 * @param array $data Array of unslashed post data.
3199 do_action( 'pre_post_update', $post_ID, $data );
3200 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
3202 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
3208 // If there is a suggested ID, use it if not already present.
3209 if ( ! empty( $import_id ) ) {
3210 $import_id = (int) $import_id;
3211 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3212 $data['ID'] = $import_id;
3215 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
3217 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
3222 $post_ID = (int) $wpdb->insert_id;
3224 // Use the newly generated $post_ID.
3225 $where = array( 'ID' => $post_ID );
3228 if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
3229 $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_ID ), $post_ID, $data['post_status'], $post_type, $post_parent );
3230 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
3231 clean_post_cache( $post_ID );
3234 if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
3235 wp_set_post_categories( $post_ID, $post_category );
3238 if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
3239 wp_set_post_tags( $post_ID, $postarr['tags_input'] );
3242 // New-style support for all custom taxonomies.
3243 if ( ! empty( $postarr['tax_input'] ) ) {
3244 foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
3245 $taxonomy_obj = get_taxonomy($taxonomy);
3246 if ( ! $taxonomy_obj ) {
3247 /* translators: %s: taxonomy name */
3248 _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
3252 // array = hierarchical, string = non-hierarchical.
3253 if ( is_array( $tags ) ) {
3254 $tags = array_filter($tags);
3256 if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
3257 wp_set_post_terms( $post_ID, $tags, $taxonomy );
3262 if ( ! empty( $postarr['meta_input'] ) ) {
3263 foreach ( $postarr['meta_input'] as $field => $value ) {
3264 update_post_meta( $post_ID, $field, $value );
3268 $current_guid = get_post_field( 'guid', $post_ID );
3271 if ( ! $update && '' == $current_guid ) {
3272 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
3275 if ( 'attachment' === $postarr['post_type'] ) {
3276 if ( ! empty( $postarr['file'] ) ) {
3277 update_attached_file( $post_ID, $postarr['file'] );
3280 if ( ! empty( $postarr['context'] ) ) {
3281 add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
3285 // Set or remove featured image.
3286 if ( isset( $postarr['_thumbnail_id'] ) ) {
3287 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
3288 if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
3289 if ( wp_attachment_is( 'audio', $post_ID ) ) {
3290 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3291 } elseif ( wp_attachment_is( 'video', $post_ID ) ) {
3292 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3296 if ( $thumbnail_support ) {
3297 $thumbnail_id = intval( $postarr['_thumbnail_id'] );
3298 if ( -1 === $thumbnail_id ) {
3299 delete_post_thumbnail( $post_ID );
3301 set_post_thumbnail( $post_ID, $thumbnail_id );
3306 clean_post_cache( $post_ID );
3308 $post = get_post( $post_ID );
3310 if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
3311 $post->page_template = $postarr['page_template'];
3312 $page_templates = wp_get_theme()->get_page_templates( $post );
3313 if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
3315 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
3317 update_post_meta( $post_ID, '_wp_page_template', 'default' );
3319 update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
3323 if ( 'attachment' !== $postarr['post_type'] ) {
3324 wp_transition_post_status( $data['post_status'], $previous_status, $post );
3328 * Fires once an existing attachment has been updated.
3332 * @param int $post_ID Attachment ID.
3334 do_action( 'edit_attachment', $post_ID );
3335 $post_after = get_post( $post_ID );
3338 * Fires once an existing attachment has been updated.
3342 * @param int $post_ID Post ID.
3343 * @param WP_Post $post_after Post object following the update.
3344 * @param WP_Post $post_before Post object before the update.
3346 do_action( 'attachment_updated', $post_ID, $post_after, $post_before );
3350 * Fires once an attachment has been added.
3354 * @param int $post_ID Attachment ID.
3356 do_action( 'add_attachment', $post_ID );
3364 * Fires once an existing post has been updated.
3368 * @param int $post_ID Post ID.
3369 * @param WP_Post $post Post object.
3371 do_action( 'edit_post', $post_ID, $post );
3372 $post_after = get_post($post_ID);
3375 * Fires once an existing post has been updated.
3379 * @param int $post_ID Post ID.
3380 * @param WP_Post $post_after Post object following the update.
3381 * @param WP_Post $post_before Post object before the update.
3383 do_action( 'post_updated', $post_ID, $post_after, $post_before);
3387 * Fires once a post has been saved.
3389 * The dynamic portion of the hook name, `$post->post_type`, refers to
3390 * the post type slug.
3394 * @param int $post_ID Post ID.
3395 * @param WP_Post $post Post object.
3396 * @param bool $update Whether this is an existing post being updated or not.
3398 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
3401 * Fires once a post has been saved.
3405 * @param int $post_ID Post ID.
3406 * @param WP_Post $post Post object.
3407 * @param bool $update Whether this is an existing post being updated or not.
3409 do_action( 'save_post', $post_ID, $post, $update );
3412 * Fires once a post has been saved.
3416 * @param int $post_ID Post ID.
3417 * @param WP_Post $post Post object.
3418 * @param bool $update Whether this is an existing post being updated or not.
3420 do_action( 'wp_insert_post', $post_ID, $post, $update );
3426 * Update a post with new post data.
3428 * The date does not have to be set for drafts. You can set the date and it will
3429 * not be overridden.
3433 * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
3434 * objects are not. Default array.
3435 * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
3436 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
3438 function wp_update_post( $postarr = array(), $wp_error = false ) {
3439 if ( is_object($postarr) ) {
3440 // Non-escaped post was passed.
3441 $postarr = get_object_vars($postarr);
3442 $postarr = wp_slash($postarr);
3445 // First, get all of the original fields.
3446 $post = get_post($postarr['ID'], ARRAY_A);
3448 if ( is_null( $post ) ) {
3450 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3454 // Escape data pulled from DB.
3455 $post = wp_slash($post);
3457 // Passed post category list overwrites existing category list if not empty.
3458 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3459 && 0 != count($postarr['post_category']) )
3460 $post_cats = $postarr['post_category'];
3462 $post_cats = $post['post_category'];
3464 // Drafts shouldn't be assigned a date unless explicitly done so by the user.
3465 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3466 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3469 $clear_date = false;
3471 // Merge old and new fields with new fields overwriting old ones.
3472 $postarr = array_merge($post, $postarr);
3473 $postarr['post_category'] = $post_cats;
3474 if ( $clear_date ) {
3475 $postarr['post_date'] = current_time('mysql');
3476 $postarr['post_date_gmt'] = '';
3479 if ($postarr['post_type'] == 'attachment')
3480 return wp_insert_attachment($postarr);
3482 return wp_insert_post( $postarr, $wp_error );
3486 * Publish a post by transitioning the post status.
3490 * @global wpdb $wpdb WordPress database abstraction object.
3492 * @param int|WP_Post $post Post ID or post object.
3494 function wp_publish_post( $post ) {
3497 if ( ! $post = get_post( $post ) )
3500 if ( 'publish' == $post->post_status )
3503 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3505 clean_post_cache( $post->ID );
3507 $old_status = $post->post_status;
3508 $post->post_status = 'publish';
3509 wp_transition_post_status( 'publish', $old_status, $post );
3511 /** This action is documented in wp-includes/post.php */
3512 do_action( 'edit_post', $post->ID, $post );
3514 /** This action is documented in wp-includes/post.php */
3515 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3517 /** This action is documented in wp-includes/post.php */
3518 do_action( 'save_post', $post->ID, $post, true );
3520 /** This action is documented in wp-includes/post.php */
3521 do_action( 'wp_insert_post', $post->ID, $post, true );
3525 * Publish future post and make sure post ID has future post status.
3527 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3528 * from publishing drafts, etc.
3532 * @param int|WP_Post $post_id Post ID or post object.
3534 function check_and_publish_future_post( $post_id ) {
3535 $post = get_post($post_id);
3540 if ( 'future' != $post->post_status )
3543 $time = strtotime( $post->post_date_gmt . ' GMT' );
3545 // Uh oh, someone jumped the gun!
3546 if ( $time > time() ) {
3547 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3548 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3552 // wp_publish_post() returns no meaningful value.
3553 wp_publish_post( $post_id );
3557 * Computes a unique slug for the post, when given the desired slug and some post details.
3561 * @global wpdb $wpdb WordPress database abstraction object.
3562 * @global WP_Rewrite $wp_rewrite
3564 * @param string $slug The desired slug (post_name).
3565 * @param int $post_ID Post ID.
3566 * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
3567 * @param string $post_type Post type.
3568 * @param int $post_parent Post parent ID.
3569 * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3571 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3572 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3575 global $wpdb, $wp_rewrite;
3577 $original_slug = $slug;
3579 $feeds = $wp_rewrite->feeds;
3580 if ( ! is_array( $feeds ) )
3583 if ( 'attachment' == $post_type ) {
3584 // Attachment slugs must be unique across all types.
3585 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3586 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3589 * Filters whether the post slug would make a bad attachment slug.
3593 * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
3594 * @param string $slug The post slug.
3596 if ( $post_name_check || in_array( $slug, $feeds ) || 'embed' === $slug || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3599 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3600 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3602 } while ( $post_name_check );
3603 $slug = $alt_post_name;
3605 } elseif ( is_post_type_hierarchical( $post_type ) ) {
3606 if ( 'nav_menu_item' == $post_type )
3610 * Page slugs must be unique within their own trees. Pages are in a separate
3611 * namespace than posts so page slugs are allowed to overlap post slugs.
3613 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1";
3614 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
3617 * Filters whether the post slug would make a bad hierarchical post slug.
3621 * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
3622 * @param string $slug The post slug.
3623 * @param string $post_type Post type.
3624 * @param int $post_parent Post parent ID.
3626 if ( $post_name_check || in_array( $slug, $feeds ) || 'embed' === $slug || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
3629 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3630 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
3632 } while ( $post_name_check );
3633 $slug = $alt_post_name;
3636 // Post slugs must be unique across all posts.
3637 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3638 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3640 // Prevent new post slugs that could result in URLs that conflict with date archives.
3641 $post = get_post( $post_ID );
3642 $conflicts_with_date_archive = false;
3643 if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) && $slug_num = intval( $slug ) ) {
3644 $permastructs = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
3645 $postname_index = array_search( '%postname%', $permastructs );
3648 * Potential date clashes are as follows: