3 * Post functions and post utility function.
11 // Post Type Registration
15 * Creates the initial post types when 'init' action is fired.
19 function create_initial_post_types() {
20 register_post_type( 'post', array(
22 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
25 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
26 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
27 'capability_type' => 'post',
28 'map_meta_cap' => true,
29 'hierarchical' => false,
32 'delete_with_user' => true,
33 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
36 register_post_type( 'page', array(
38 'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
41 'publicly_queryable' => false,
42 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
43 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
44 'capability_type' => 'page',
45 'map_meta_cap' => true,
46 'hierarchical' => true,
49 'delete_with_user' => true,
50 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
53 register_post_type( 'attachment', array(
55 'name' => _x('Media', 'post type general name'),
56 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
57 'add_new' => _x( 'Add New', 'add new media' ),
58 'edit_item' => __( 'Edit Media' ),
59 'view_item' => __( 'View Attachment Page' ),
63 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
64 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
65 'capability_type' => 'post',
66 'capabilities' => array(
67 'create_posts' => 'upload_files',
69 'map_meta_cap' => true,
70 'hierarchical' => false,
73 'show_in_nav_menus' => false,
74 'delete_with_user' => true,
75 'supports' => array( 'title', 'author', 'comments' ),
77 add_post_type_support( 'attachment:audio', 'thumbnail' );
78 add_post_type_support( 'attachment:video', 'thumbnail' );
80 register_post_type( 'revision', array(
82 'name' => __( 'Revisions' ),
83 'singular_name' => __( 'Revision' ),
86 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
87 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
88 'capability_type' => 'post',
89 'map_meta_cap' => true,
90 'hierarchical' => false,
93 'can_export' => false,
94 'delete_with_user' => true,
95 'supports' => array( 'author' ),
98 register_post_type( 'nav_menu_item', array(
100 'name' => __( 'Navigation Menu Items' ),
101 'singular_name' => __( 'Navigation Menu Item' ),
104 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
105 'hierarchical' => false,
107 'delete_with_user' => false,
108 'query_var' => false,
111 register_post_status( 'publish', array(
112 'label' => _x( 'Published', 'post' ),
114 '_builtin' => true, /* internal use only. */
115 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
118 register_post_status( 'future', array(
119 'label' => _x( 'Scheduled', 'post' ),
121 '_builtin' => true, /* internal use only. */
122 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
125 register_post_status( 'draft', array(
126 'label' => _x( 'Draft', 'post' ),
128 '_builtin' => true, /* internal use only. */
129 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
132 register_post_status( 'pending', array(
133 'label' => _x( 'Pending', 'post' ),
135 '_builtin' => true, /* internal use only. */
136 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
139 register_post_status( 'private', array(
140 'label' => _x( 'Private', 'post' ),
142 '_builtin' => true, /* internal use only. */
143 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
146 register_post_status( 'trash', array(
147 'label' => _x( 'Trash', 'post' ),
149 '_builtin' => true, /* internal use only. */
150 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
151 'show_in_admin_status_list' => true,
154 register_post_status( 'auto-draft', array(
155 'label' => 'auto-draft',
157 '_builtin' => true, /* internal use only. */
160 register_post_status( 'inherit', array(
161 'label' => 'inherit',
163 '_builtin' => true, /* internal use only. */
164 'exclude_from_search' => false,
167 add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
170 * Retrieve attached file path based on attachment ID.
172 * By default the path will go through the 'get_attached_file' filter, but
173 * passing a true to the $unfiltered argument of get_attached_file() will
174 * return the file path unfiltered.
176 * The function works by getting the single post meta name, named
177 * '_wp_attached_file' and returning it. This is a convenience function to
178 * prevent looking up the meta name and provide a mechanism for sending the
179 * attached filename through a filter.
183 * @param int $attachment_id Attachment ID.
184 * @param bool $unfiltered Optional. Whether to apply filters. Default false.
185 * @return string|bool The file path to where the attached file should be, false otherwise.
187 function get_attached_file( $attachment_id, $unfiltered = false ) {
188 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
189 // If the file is relative, prepend upload dir.
190 if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
191 $file = $uploads['basedir'] . "/$file";
196 * Filter the attached file based on the given ID.
200 * @param string $file Path to attached file.
201 * @param int $attachment_id Attachment ID.
203 return apply_filters( 'get_attached_file', $file, $attachment_id );
207 * Update attachment file path based on attachment ID.
209 * Used to update the file path of the attachment, which uses post meta name
210 * '_wp_attached_file' to store the path of the attachment.
214 * @param int $attachment_id Attachment ID.
215 * @param string $file File path for the attachment.
216 * @return bool True on success, false on failure.
218 function update_attached_file( $attachment_id, $file ) {
219 if ( !get_post( $attachment_id ) )
223 * Filter the path to the attached file to update.
227 * @param string $file Path to the attached file to update.
228 * @param int $attachment_id Attachment ID.
230 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
232 if ( $file = _wp_relative_upload_path( $file ) )
233 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
235 return delete_post_meta( $attachment_id, '_wp_attached_file' );
239 * Return relative path to an uploaded file.
241 * The path is relative to the current upload dir.
245 * @param string $path Full path to the file.
246 * @return string Relative path on success, unchanged path on failure.
248 function _wp_relative_upload_path( $path ) {
251 $uploads = wp_upload_dir();
252 if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
253 $new_path = str_replace( $uploads['basedir'], '', $new_path );
254 $new_path = ltrim( $new_path, '/' );
258 * Filter the relative path to an uploaded file.
262 * @param string $new_path Relative path to the file.
263 * @param string $path Full path to the file.
265 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
269 * Retrieve all children of the post parent ID.
271 * Normally, without any enhancements, the children would apply to pages. In the
272 * context of the inner workings of WordPress, pages, posts, and attachments
273 * share the same table, so therefore the functionality could apply to any one
274 * of them. It is then noted that while this function does not work on posts, it
275 * does not mean that it won't work on posts. It is recommended that you know
276 * what context you wish to retrieve the children of.
278 * Attachments may also be made the child of a post, so if that is an accurate
279 * statement (which needs to be verified), it would then be possible to get
280 * all of the attachments for a post. Attachments have since changed since
281 * version 2.5, so this is most likely unaccurate, but serves generally as an
282 * example of what is possible.
284 * The arguments listed as defaults are for this function and also of the
285 * {@link get_posts()} function. The arguments are combined with the
286 * get_children defaults and are then passed to the {@link get_posts()}
287 * function, which accepts additional arguments. You can replace the defaults in
288 * this function, listed below and the additional arguments listed in the
289 * {@link get_posts()} function.
291 * The 'post_parent' is the most important argument and important attention
292 * needs to be paid to the $args parameter. If you pass either an object or an
293 * integer (number), then just the 'post_parent' is grabbed and everything else
294 * is lost. If you don't specify any arguments, then it is assumed that you are
295 * in The Loop and the post parent will be grabbed for from the current post.
297 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
298 * is the amount of posts to retrieve that has a default of '-1', which is
299 * used to get all of the posts. Giving a number higher than 0 will only
300 * retrieve that amount of posts.
302 * The 'post_type' and 'post_status' arguments can be used to choose what
303 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
304 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
305 * argument will accept any post status within the write administration panels.
307 * @internal Claims made in the long description might be inaccurate.
312 * @param mixed $args Optional. User defined arguments for replacing the defaults. Default empty.
313 * @param string $output Optional. Constant for return type. Accepts OBJECT, ARRAY_A, ARRAY_N.
315 * @return array Array of children, where the type of each element is determined by $output parameter.
316 * Empty array on failure.
318 function get_children( $args = '', $output = OBJECT ) {
320 if ( empty( $args ) ) {
321 if ( isset( $GLOBALS['post'] ) ) {
322 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
326 } elseif ( is_object( $args ) ) {
327 $args = array('post_parent' => (int) $args->post_parent );
328 } elseif ( is_numeric( $args ) ) {
329 $args = array('post_parent' => (int) $args);
333 'numberposts' => -1, 'post_type' => 'any',
334 'post_status' => 'any', 'post_parent' => 0,
337 $r = wp_parse_args( $args, $defaults );
339 $children = get_posts( $r );
344 if ( ! empty( $r['fields'] ) )
347 update_post_cache($children);
349 foreach ( $children as $key => $child )
350 $kids[$child->ID] = $children[$key];
352 if ( $output == OBJECT ) {
354 } elseif ( $output == ARRAY_A ) {
355 foreach ( (array) $kids as $kid )
356 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
358 } elseif ( $output == ARRAY_N ) {
359 foreach ( (array) $kids as $kid )
360 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
368 * Get extended entry info (<!--more-->).
370 * There should not be any space after the second dash and before the word
371 * 'more'. There can be text or space(s) after the word 'more', but won't be
374 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
375 * the <code><!--more--></code>. The 'extended' key has the content after the
376 * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text.
380 * @param string $post Post content.
381 * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text').
383 function get_extended( $post ) {
384 //Match the new style more links.
385 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
386 list($main, $extended) = explode($matches[0], $post, 2);
387 $more_text = $matches[1];
394 // leading and trailing whitespace.
395 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
396 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
397 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
399 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
403 * Retrieves post data given a post ID or post object.
405 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
406 * $post, must be given as a variable, since it is passed by reference.
410 * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
411 * @param string $output Optional, default is Object. Accepts OBJECT, ARRAY_A, or ARRAY_N.
413 * @param string $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
414 * or 'display'. Default 'raw'.
415 * @return WP_Post|null WP_Post on success or null on failure.
417 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
418 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
419 $post = $GLOBALS['post'];
421 if ( is_a( $post, 'WP_Post' ) ) {
423 } elseif ( is_object( $post ) ) {
424 if ( empty( $post->filter ) ) {
425 $_post = sanitize_post( $post, 'raw' );
426 $_post = new WP_Post( $_post );
427 } elseif ( 'raw' == $post->filter ) {
428 $_post = new WP_Post( $post );
430 $_post = WP_Post::get_instance( $post->ID );
433 $_post = WP_Post::get_instance( $post );
439 $_post = $_post->filter( $filter );
441 if ( $output == ARRAY_A )
442 return $_post->to_array();
443 elseif ( $output == ARRAY_N )
444 return array_values( $_post->to_array() );
450 * WordPress Post class.
455 final class WP_Post {
467 * A numeric string, for compatibility reasons.
471 public $post_author = 0;
474 * The post's local publication time.
478 public $post_date = '0000-00-00 00:00:00';
481 * The post's GMT publication time.
485 public $post_date_gmt = '0000-00-00 00:00:00';
488 * The post's content.
492 public $post_content = '';
499 public $post_title = '';
502 * The post's excerpt.
506 public $post_excerpt = '';
513 public $post_status = 'publish';
516 * Whether comments are allowed.
520 public $comment_status = 'open';
523 * Whether pings are allowed.
527 public $ping_status = 'open';
530 * The post's password in plain text.
534 public $post_password = '';
541 public $post_name = '';
544 * URLs queued to be pinged.
548 public $to_ping = '';
551 * URLs that have been pinged.
558 * The post's local modified time.
562 public $post_modified = '0000-00-00 00:00:00';
565 * The post's GMT modified time.
569 public $post_modified_gmt = '0000-00-00 00:00:00';
572 * A utility DB field for post content.
577 public $post_content_filtered = '';
580 * ID of a post's parent post.
584 public $post_parent = 0;
587 * The unique identifier for a post, not necessarily a URL, used as the feed GUID.
594 * A field used for ordering posts.
598 public $menu_order = 0;
601 * The post's type, like post or page.
605 public $post_type = 'post';
608 * An attachment's mime type.
612 public $post_mime_type = '';
615 * Cached comment count.
617 * A numeric string, for compatibility reasons.
621 public $comment_count = 0;
624 * Stores the post object's sanitization level.
626 * Does not correspond to a DB field.
633 * Retrieve WP_Post instance.
638 * @param int $post_id Post ID.
639 * @return WP_Post|bool Post object, false otherwise.
641 public static function get_instance( $post_id ) {
644 $post_id = (int) $post_id;
648 $_post = wp_cache_get( $post_id, 'posts' );
651 $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
656 $_post = sanitize_post( $_post, 'raw' );
657 wp_cache_add( $_post->ID, $_post, 'posts' );
658 } elseif ( empty( $_post->filter ) ) {
659 $_post = sanitize_post( $_post, 'raw' );
662 return new WP_Post( $_post );
668 * @param WP_Post $post Post object.
670 public function __construct( $post ) {
671 foreach ( get_object_vars( $post ) as $key => $value )
672 $this->$key = $value;
678 * @param string $key Property to check if set.
681 public function __isset( $key ) {
682 if ( 'ancestors' == $key )
685 if ( 'page_template' == $key )
686 return ( 'page' == $this->post_type );
688 if ( 'post_category' == $key )
691 if ( 'tags_input' == $key )
694 return metadata_exists( 'post', $this->ID, $key );
700 * @param string $key Key to get.
701 * @return array|mixed
703 public function __get( $key ) {
704 if ( 'page_template' == $key && $this->__isset( $key ) ) {
705 return get_post_meta( $this->ID, '_wp_page_template', true );
708 if ( 'post_category' == $key ) {
709 if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
710 $terms = get_the_terms( $this, 'category' );
712 if ( empty( $terms ) )
715 return wp_list_pluck( $terms, 'term_id' );
718 if ( 'tags_input' == $key ) {
719 if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
720 $terms = get_the_terms( $this, 'post_tag' );
722 if ( empty( $terms ) )
725 return wp_list_pluck( $terms, 'name' );
728 // Rest of the values need filtering.
729 if ( 'ancestors' == $key )
730 $value = get_post_ancestors( $this );
732 $value = get_post_meta( $this->ID, $key, true );
735 $value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
743 * @param string $filter Filter.
744 * @return $this|array|bool|object|WP_Post
746 public function filter( $filter ) {
747 if ( $this->filter == $filter )
750 if ( $filter == 'raw' )
751 return self::get_instance( $this->ID );
753 return sanitize_post( $this, $filter );
757 * Convert object to array.
759 * @return array Object as array.
761 public function to_array() {
762 $post = get_object_vars( $this );
764 foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
765 if ( $this->__isset( $key ) )
766 $post[ $key ] = $this->__get( $key );
774 * Retrieve ancestors of a post.
778 * @param int|WP_Post $post Post ID or post object.
779 * @return array Ancestor IDs or empty array if none are found.
781 function get_post_ancestors( $post ) {
782 $post = get_post( $post );
784 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
787 $ancestors = array();
789 $id = $ancestors[] = $post->post_parent;
791 while ( $ancestor = get_post( $id ) ) {
792 // Loop detection: If the ancestor has been seen before, break.
793 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
796 $id = $ancestors[] = $ancestor->post_parent;
803 * Retrieve data from a post field based on Post ID.
805 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
806 * etc and based off of the post object property or key names.
808 * The context values are based off of the taxonomy filter functions and
809 * supported values are found within those functions.
813 * @see sanitize_post_field()
815 * @param string $field Post field name.
816 * @param int|WP_Post $post Post ID or post object.
817 * @param string $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
818 * or 'display'. Default 'display'.
819 * @return string The value of the post field on success, empty string on failure.
821 function get_post_field( $field, $post, $context = 'display' ) {
822 $post = get_post( $post );
827 if ( !isset($post->$field) )
830 return sanitize_post_field($field, $post->$field, $post->ID, $context);
834 * Retrieve the mime type of an attachment based on the ID.
836 * This function can be used with any post type, but it makes more sense with
841 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
842 * @return string|bool The mime type on success, false on failure.
844 function get_post_mime_type( $ID = '' ) {
845 $post = get_post($ID);
847 if ( is_object($post) )
848 return $post->post_mime_type;
854 * Retrieve the post status based on the Post ID.
856 * If the post ID is of an attachment, then the parent post status will be given
861 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
862 * @return string|bool Post status on success, false on failure.
864 function get_post_status( $ID = '' ) {
865 $post = get_post($ID);
867 if ( !is_object($post) )
870 if ( 'attachment' == $post->post_type ) {
871 if ( 'private' == $post->post_status )
874 // Unattached attachments are assumed to be published.
875 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
878 // Inherit status from the parent.
879 if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) {
880 $parent_post_status = get_post_status( $post->post_parent );
881 if ( 'trash' == $parent_post_status ) {
882 return get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
884 return $parent_post_status;
890 return $post->post_status;
894 * Retrieve all of the WordPress supported post statuses.
896 * Posts have a limited set of valid status values, this provides the
897 * post_status values and descriptions.
901 * @return array List of post statuses.
903 function get_post_statuses() {
905 'draft' => __( 'Draft' ),
906 'pending' => __( 'Pending Review' ),
907 'private' => __( 'Private' ),
908 'publish' => __( 'Published' )
915 * Retrieve all of the WordPress support page statuses.
917 * Pages have a limited set of valid status values, this provides the
918 * post_status values and descriptions.
922 * @return array List of page statuses.
924 function get_page_statuses() {
926 'draft' => __( 'Draft' ),
927 'private' => __( 'Private' ),
928 'publish' => __( 'Published' )
935 * Register a post status. Do not use before init.
937 * A simple function for creating or modifying a post status based on the
938 * parameters given. The function will accept an array (second optional
939 * parameter), along with a string for the post status name.
941 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
944 * @uses $wp_post_statuses Inserts new post status object into the list
946 * @param string $post_status Name of the post status.
947 * @param array|string $args {
948 * Optional. Array or string of post status arguments.
950 * @type bool|string $label A descriptive name for the post status marked
951 * for translation. Defaults to value of $post_status.
952 * @type bool|array $label_count Descriptive text to use for nooped plurals.
953 * Default array of $label, twice
954 * @type bool $exclude_from_search Whether to exclude posts with this post status
955 * from search results. Default is value of $internal.
956 * @type bool $_builtin Whether the status is built-in. Core-use only.
958 * @type bool $public Whether posts of this status should be shown
959 * in the front end of the site. Default true.
960 * @type bool $internal Whether the status is for internal use only.
962 * @type bool $protected Whether posts with this status should be protected.
964 * @type bool $private Whether posts with this status should be private.
966 * @type bool $publicly_queryable Whether posts with this status should be publicly-
967 * queryable. Default is value of $public.
968 * @type bool $show_in_admin_all_list Whether to include posts in the edit listing for
969 * their post type. Default is value of $internal.
970 * @type bool $show_in_admin_status_list Show in the list of statuses with post counts at
971 * the top of the edit listings,
972 * e.g. All (12) | Published (9) | My Custom Status (2)
973 * Default is value of $internal.
976 function register_post_status( $post_status, $args = array() ) {
977 global $wp_post_statuses;
979 if (!is_array($wp_post_statuses))
980 $wp_post_statuses = array();
982 // Args prefixed with an underscore are reserved for internal use.
985 'label_count' => false,
986 'exclude_from_search' => null,
992 'publicly_queryable' => null,
993 'show_in_admin_status_list' => null,
994 'show_in_admin_all_list' => null,
996 $args = wp_parse_args($args, $defaults);
997 $args = (object) $args;
999 $post_status = sanitize_key($post_status);
1000 $args->name = $post_status;
1002 // Set various defaults.
1003 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
1004 $args->internal = true;
1006 if ( null === $args->public )
1007 $args->public = false;
1009 if ( null === $args->private )
1010 $args->private = false;
1012 if ( null === $args->protected )
1013 $args->protected = false;
1015 if ( null === $args->internal )
1016 $args->internal = false;
1018 if ( null === $args->publicly_queryable )
1019 $args->publicly_queryable = $args->public;
1021 if ( null === $args->exclude_from_search )
1022 $args->exclude_from_search = $args->internal;
1024 if ( null === $args->show_in_admin_all_list )
1025 $args->show_in_admin_all_list = !$args->internal;
1027 if ( null === $args->show_in_admin_status_list )
1028 $args->show_in_admin_status_list = !$args->internal;
1030 if ( false === $args->label )
1031 $args->label = $post_status;
1033 if ( false === $args->label_count )
1034 $args->label_count = array( $args->label, $args->label );
1036 $wp_post_statuses[$post_status] = $args;
1042 * Retrieve a post status object by name.
1046 * @global array $wp_post_statuses List of post statuses.
1048 * @see register_post_status()
1050 * @param string $post_status The name of a registered post status.
1051 * @return object A post status object.
1053 function get_post_status_object( $post_status ) {
1054 global $wp_post_statuses;
1056 if ( empty($wp_post_statuses[$post_status]) )
1059 return $wp_post_statuses[$post_status];
1063 * Get a list of all registered post status objects.
1067 * @global array $wp_post_statuses List of post statuses.
1069 * @see register_post_status()
1071 * @param array|string $args Optional. Array or string of post status arguments. Default array.
1072 * @param string $output Optional. The type of output to return. Accepts post status 'names'
1073 * or 'objects'. Default 'names'.
1074 * @param string $operator Optional. The logical operation to perform. 'or' means only one element
1075 * from the array needs to match; 'and' means all elements must match.
1077 * @return array A list of post status names or objects.
1079 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
1080 global $wp_post_statuses;
1082 $field = ('names' == $output) ? 'name' : false;
1084 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
1088 * Whether the post type is hierarchical.
1090 * A false return value might also mean that the post type does not exist.
1094 * @see get_post_type_object()
1096 * @param string $post_type Post type name
1097 * @return bool Whether post type is hierarchical.
1099 function is_post_type_hierarchical( $post_type ) {
1100 if ( ! post_type_exists( $post_type ) )
1103 $post_type = get_post_type_object( $post_type );
1104 return $post_type->hierarchical;
1108 * Check if a post type is registered.
1112 * @see get_post_type_object()
1114 * @param string $post_type Post type name.
1115 * @return bool Whether post type is registered.
1117 function post_type_exists( $post_type ) {
1118 return (bool) get_post_type_object( $post_type );
1122 * Retrieve the post type of the current post or of a given post.
1126 * @param int|WP_Post $post Optional. Post ID or post object. Default is global $post.
1127 * @return string|bool Post type on success, false on failure.
1129 function get_post_type( $post = null ) {
1130 if ( $post = get_post( $post ) )
1131 return $post->post_type;
1137 * Retrieve a post type object by name.
1141 * @global array $wp_post_types List of post types.
1143 * @see register_post_type()
1145 * @param string $post_type The name of a registered post type.
1146 * @return object A post type object.
1148 function get_post_type_object( $post_type ) {
1149 global $wp_post_types;
1151 if ( empty($wp_post_types[$post_type]) )
1154 return $wp_post_types[$post_type];
1158 * Get a list of all registered post type objects.
1162 * @global array $wp_post_types List of post types.
1164 * @see register_post_type()
1166 * @param array|string $args Optional. An array of key => value arguments to match against
1167 * the post type objects. Default empty array.
1168 * @param string $output Optional. The type of output to return. Accepts post type 'names'
1169 * or 'objects'. Default 'names'.
1170 * @param string $operator Optaionl. The logical operation to perform. 'or' means only one
1171 * element from the array needs to match; 'and' means all elements
1172 * must match. Default 'and'.
1173 * @return array A list of post type names or objects.
1175 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
1176 global $wp_post_types;
1178 $field = ('names' == $output) ? 'name' : false;
1180 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
1184 * Register a post type. Do not use before init.
1186 * A function for creating or modifying a post type based on the
1187 * parameters given. The function will accept an array (second optional
1188 * parameter), along with a string for the post type name.
1192 * @global array $wp_post_types List of post types.
1193 * @global WP_Rewrite $wp_rewrite Used for default feeds.
1194 * @global WP $wp Used to add query vars.
1196 * @param string $post_type Post type key, must not exceed 20 characters.
1197 * @param array|string $args {
1198 * Array or string of arguments for registering a post type.
1200 * @type string $label Name of the post type shown in the menu. Usually plural.
1201 * Default is value of $labels['name'].
1202 * @type array $labels An array of labels for this post type. If not set, post
1203 * labels are inherited for non-hierarchical types and page
1204 * labels for hierarchical ones. {@see get_post_type_labels()}.
1205 * @type string $description A short descriptive summary of what the post type is.
1207 * @type bool $public Whether a post type is intended for use publicly either via
1208 * the admin interface or by front-end users. While the default
1209 * settings of $exclude_from_search, $publicly_queryable, $show_ui,
1210 * and $show_in_nav_menus are inherited from public, each does not
1211 * rely on this relationship and controls a very specific intention.
1213 * @type bool $hierarchical Whether the post type is hierarchical (e.g. page). Default false.
1214 * @type bool $exclude_from_search Whether to exclude posts with this post type from front end search
1215 * results. Default is the opposite value of $public.
1216 * @type bool $publicly_queryable Whether queries can be performed on the front end for the post type
1217 * as part of {@see parse_request()}. Endpoints would include:
1218 * * ?post_type={post_type_key}
1219 * * ?{post_type_key}={single_post_slug}
1220 * * ?{post_type_query_var}={single_post_slug}
1221 * If not set, the default is inherited from $public.
1222 * @type bool $show_ui Whether to generate a default UI for managing this post type in the
1223 * admin. Default is value of $public.
1224 * @type bool $show_in_menu Where to show the post type in the admin menu. To work, $show_ui
1225 * must be true. If true, the post type is shown in its own top level
1226 * menu. If false, no menu is shown. If a string of an existing top
1227 * level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
1228 * type will be placed as a sub-menu of that.
1229 * Default is value of $show_ui.
1230 * @type bool $show_in_nav_menus Makes this post type available for selection in navigation menus.
1231 * Default is value $public.
1232 * @type bool $show_in_admin_bar Makes this post type available via the admin bar. Default is value
1234 * @type int $menu_position The position in the menu order the post type should appear. To work,
1235 * $show_in_menu must be true. Default null (at the bottom).
1236 * @type string $menu_icon The url to the icon to be used for this menu. Pass a base64-encoded
1237 * SVG using a data URI, which will be colored to match the color scheme
1238 * -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
1239 * of a Dashicons helper class to use a font icon, e.g.
1240 * 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
1241 * so an icon can be added via CSS. Defaults to use the posts icon.
1242 * @type string $capability_type The string to use to build the read, edit, and delete capabilities.
1243 * May be passed as an array to allow for alternative plurals when using
1244 * this argument as a base to construct the capabilities, e.g.
1245 * array('story', 'stories'). Default 'post'.
1246 * @type array $capabilities Array of capabilities for this post type. $capability_type is used
1247 * as a base to construct capabilities by default.
1248 * {@see get_post_type_capabilities()}.
1249 * @type bool $map_meta_cap Whether to use the internal default meta capability handling.
1251 * @type array $supports An alias for calling {@see add_post_type_support()} directly.
1252 * Defaults to array containing 'title' & 'editor'.
1253 * @type callback $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
1254 * edit form. Do remove_meta_box() and add_meta_box() calls in the
1255 * callback. Default null.
1256 * @type array $taxonomies An array of taxonomy identifiers that will be registered for the
1257 * post type. Taxonomies can be registered later with
1258 * {@see register_taxonomy()} or {@see register_taxonomy_for_object_type()}.
1259 * Default empty array.
1260 * @type bool|string $has_archive Whether there should be post type archives, or if a string, the
1261 * archive slug to use. Will generate the proper rewrite rules if
1262 * $rewrite is enabled. Default false.
1263 * @type bool|array $rewrite {
1264 * Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
1265 * Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
1266 * passed with any of these keys:
1268 * @type string $slug Customize the permastruct slug. Defaults to $post_type key.
1269 * @type bool $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
1271 * @type bool $feeds Whether the feed permastruct should be built for this post type.
1272 * Default is value of $has_archive.
1273 * @type bool $pages Whether the permastruct should provide for pagination. Default true.
1274 * @type const $ep_mask Endpoint mask to assign. If not specified and permalink_epmask is set,
1275 * inherits from $permalink_epmask. If not specified and permalink_epmask
1276 * is not set, defaults to EP_PERMALINK.
1278 * @type string|bool $query_var Sets the query_var key for this post type. Defaults to $post_type
1279 * key. If false, a post type cannot be loaded at
1280 * ?{query_var}={post_slug}. If specified as a string, the query
1281 * ?{query_var_string}={post_slug} will be valid.
1282 * @type bool $can_export Whether to allow this post type to be exported. Default true.
1283 * @type bool $delete_with_user Whether to delete posts of this type when deleting a user. If true,
1284 * posts of this type belonging to the user will be moved to trash
1285 * when then user is deleted. If false, posts of this type belonging
1286 * to the user will *not* be trashed or deleted. If not set (the default),
1287 * posts are trashed if post_type_supports('author'). Otherwise posts
1288 * are not trashed or deleted. Default null.
1289 * @type bool $_builtin FOR INTERNAL USE ONLY! True if this post type is a native or
1290 * "built-in" post_type. Default false.
1291 * @type string $_edit_link FOR INTERNAL USE ONLY! URL segment to use for edit link of
1292 * this post type. Default 'post.php?post=%d'.
1294 * @return object|WP_Error The registered post type object, or an error object.
1296 function register_post_type( $post_type, $args = array() ) {
1297 global $wp_post_types, $wp_rewrite, $wp;
1299 if ( ! is_array( $wp_post_types ) )
1300 $wp_post_types = array();
1302 // Args prefixed with an underscore are reserved for internal use.
1304 'labels' => array(),
1305 'description' => '',
1307 'hierarchical' => false,
1308 'exclude_from_search' => null,
1309 'publicly_queryable' => null,
1311 'show_in_menu' => null,
1312 'show_in_nav_menus' => null,
1313 'show_in_admin_bar' => null,
1314 'menu_position' => null,
1315 'menu_icon' => null,
1316 'capability_type' => 'post',
1317 'capabilities' => array(),
1318 'map_meta_cap' => null,
1319 'supports' => array(),
1320 'register_meta_box_cb' => null,
1321 'taxonomies' => array(),
1322 'has_archive' => false,
1324 'query_var' => true,
1325 'can_export' => true,
1326 'delete_with_user' => null,
1327 '_builtin' => false,
1328 '_edit_link' => 'post.php?post=%d',
1330 $args = wp_parse_args( $args, $defaults );
1331 $args = (object) $args;
1333 $post_type = sanitize_key( $post_type );
1334 $args->name = $post_type;
1336 if ( strlen( $post_type ) > 20 ) {
1337 _doing_it_wrong( __FUNCTION__, __( 'Post types cannot exceed 20 characters in length' ), '4.0' );
1338 return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
1341 // If not set, default to the setting for public.
1342 if ( null === $args->publicly_queryable )
1343 $args->publicly_queryable = $args->public;
1345 // If not set, default to the setting for public.
1346 if ( null === $args->show_ui )
1347 $args->show_ui = $args->public;
1349 // If not set, default to the setting for show_ui.
1350 if ( null === $args->show_in_menu || ! $args->show_ui )
1351 $args->show_in_menu = $args->show_ui;
1353 // If not set, default to the whether the full UI is shown.
1354 if ( null === $args->show_in_admin_bar )
1355 $args->show_in_admin_bar = true === $args->show_in_menu;
1357 // If not set, default to the setting for public.
1358 if ( null === $args->show_in_nav_menus )
1359 $args->show_in_nav_menus = $args->public;
1361 // If not set, default to true if not public, false if public.
1362 if ( null === $args->exclude_from_search )
1363 $args->exclude_from_search = !$args->public;
1365 // Back compat with quirky handling in version 3.0. #14122.
1366 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1367 $args->map_meta_cap = true;
1369 // If not set, default to false.
1370 if ( null === $args->map_meta_cap )
1371 $args->map_meta_cap = false;
1373 $args->cap = get_post_type_capabilities( $args );
1374 unset( $args->capabilities );
1376 if ( is_array( $args->capability_type ) )
1377 $args->capability_type = $args->capability_type[0];
1379 if ( ! empty( $args->supports ) ) {
1380 add_post_type_support( $post_type, $args->supports );
1381 unset( $args->supports );
1382 } elseif ( false !== $args->supports ) {
1383 // Add default features
1384 add_post_type_support( $post_type, array( 'title', 'editor' ) );
1387 if ( false !== $args->query_var && ! empty( $wp ) ) {
1388 if ( true === $args->query_var )
1389 $args->query_var = $post_type;
1391 $args->query_var = sanitize_title_with_dashes( $args->query_var );
1392 $wp->add_query_var( $args->query_var );
1395 if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
1396 if ( ! is_array( $args->rewrite ) )
1397 $args->rewrite = array();
1398 if ( empty( $args->rewrite['slug'] ) )
1399 $args->rewrite['slug'] = $post_type;
1400 if ( ! isset( $args->rewrite['with_front'] ) )
1401 $args->rewrite['with_front'] = true;
1402 if ( ! isset( $args->rewrite['pages'] ) )
1403 $args->rewrite['pages'] = true;
1404 if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1405 $args->rewrite['feeds'] = (bool) $args->has_archive;
1406 if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1407 if ( isset( $args->permalink_epmask ) )
1408 $args->rewrite['ep_mask'] = $args->permalink_epmask;
1410 $args->rewrite['ep_mask'] = EP_PERMALINK;
1413 if ( $args->hierarchical )
1414 add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
1416 add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
1418 if ( $args->has_archive ) {
1419 $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1420 if ( $args->rewrite['with_front'] )
1421 $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1423 $archive_slug = $wp_rewrite->root . $archive_slug;
1425 add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1426 if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1427 $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1428 add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1429 add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1431 if ( $args->rewrite['pages'] )
1432 add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1435 $permastruct_args = $args->rewrite;
1436 $permastruct_args['feed'] = $permastruct_args['feeds'];
1437 add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
1440 // Register the post type meta box if a custom callback was specified.
1441 if ( $args->register_meta_box_cb )
1442 add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
1444 $args->labels = get_post_type_labels( $args );
1445 $args->label = $args->labels->name;
1447 $wp_post_types[ $post_type ] = $args;
1449 add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1451 foreach ( $args->taxonomies as $taxonomy ) {
1452 register_taxonomy_for_object_type( $taxonomy, $post_type );
1456 * Fires after a post type is registered.
1460 * @param string $post_type Post type.
1461 * @param object $args Arguments used to register the post type.
1463 do_action( 'registered_post_type', $post_type, $args );
1469 * Build an object with all post type capabilities out of a post type object
1471 * Post type capabilities use the 'capability_type' argument as a base, if the
1472 * capability is not set in the 'capabilities' argument array or if the
1473 * 'capabilities' argument is not supplied.
1475 * The capability_type argument can optionally be registered as an array, with
1476 * the first value being singular and the second plural, e.g. array('story, 'stories')
1477 * Otherwise, an 's' will be added to the value for the plural form. After
1478 * registration, capability_type will always be a string of the singular value.
1480 * By default, seven keys are accepted as part of the capabilities array:
1482 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1483 * generally mapped to corresponding primitive capabilities depending on the
1484 * context, which would be the post being edited/read/deleted and the user or
1485 * role being checked. Thus these capabilities would generally not be granted
1486 * directly to users or roles.
1488 * - edit_posts - Controls whether objects of this post type can be edited.
1489 * - edit_others_posts - Controls whether objects of this type owned by other users
1490 * can be edited. If the post type does not support an author, then this will
1491 * behave like edit_posts.
1492 * - publish_posts - Controls publishing objects of this post type.
1493 * - read_private_posts - Controls whether private objects can be read.
1495 * These four primitive capabilities are checked in core in various locations.
1496 * There are also seven other primitive capabilities which are not referenced
1497 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1498 * meta capabilities and translates them into one or more primitive capabilities
1499 * that must then be checked against the user or role, depending on the context.
1501 * - read - Controls whether objects of this post type can be read.
1502 * - delete_posts - Controls whether objects of this post type can be deleted.
1503 * - delete_private_posts - Controls whether private objects can be deleted.
1504 * - delete_published_posts - Controls whether published objects can be deleted.
1505 * - delete_others_posts - Controls whether objects owned by other users can be
1506 * can be deleted. If the post type does not support an author, then this will
1507 * behave like delete_posts.
1508 * - edit_private_posts - Controls whether private objects can be edited.
1509 * - edit_published_posts - Controls whether published objects can be edited.
1511 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1512 * only assigned by default if the post type is registered with the 'map_meta_cap'
1513 * argument set to true (default is false).
1517 * @see register_post_type()
1518 * @see map_meta_cap()
1520 * @param object $args Post type registration arguments.
1521 * @return object object with all the capabilities as member variables.
1523 function get_post_type_capabilities( $args ) {
1524 if ( ! is_array( $args->capability_type ) )
1525 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1527 // Singular base for meta capabilities, plural base for primitive capabilities.
1528 list( $singular_base, $plural_base ) = $args->capability_type;
1530 $default_capabilities = array(
1531 // Meta capabilities
1532 'edit_post' => 'edit_' . $singular_base,
1533 'read_post' => 'read_' . $singular_base,
1534 'delete_post' => 'delete_' . $singular_base,
1535 // Primitive capabilities used outside of map_meta_cap():
1536 'edit_posts' => 'edit_' . $plural_base,
1537 'edit_others_posts' => 'edit_others_' . $plural_base,
1538 'publish_posts' => 'publish_' . $plural_base,
1539 'read_private_posts' => 'read_private_' . $plural_base,
1542 // Primitive capabilities used within map_meta_cap():
1543 if ( $args->map_meta_cap ) {
1544 $default_capabilities_for_mapping = array(
1546 'delete_posts' => 'delete_' . $plural_base,
1547 'delete_private_posts' => 'delete_private_' . $plural_base,
1548 'delete_published_posts' => 'delete_published_' . $plural_base,
1549 'delete_others_posts' => 'delete_others_' . $plural_base,
1550 'edit_private_posts' => 'edit_private_' . $plural_base,
1551 'edit_published_posts' => 'edit_published_' . $plural_base,
1553 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1556 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1558 // Post creation capability simply maps to edit_posts by default:
1559 if ( ! isset( $capabilities['create_posts'] ) )
1560 $capabilities['create_posts'] = $capabilities['edit_posts'];
1562 // Remember meta capabilities for future reference.
1563 if ( $args->map_meta_cap )
1564 _post_type_meta_capabilities( $capabilities );
1566 return (object) $capabilities;
1570 * Store or return a list of post type meta caps for map_meta_cap().
1575 * @param null|array $capabilities Post type meta capabilities.
1577 function _post_type_meta_capabilities( $capabilities = null ) {
1578 static $meta_caps = array();
1579 if ( null === $capabilities )
1581 foreach ( $capabilities as $core => $custom ) {
1582 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1583 $meta_caps[ $custom ] = $core;
1588 * Build an object with all post type labels out of a post type object
1590 * Accepted keys of the label array in the post type object:
1592 * - name - general name for the post type, usually plural. The same and overridden
1593 * by $post_type_object->label. Default is Posts/Pages
1594 * - singular_name - name for one object of this post type. Default is Post/Page
1595 * - add_new - Default is Add New for both hierarchical and non-hierarchical types.
1596 * When internationalizing this string, please use a gettext context
1597 * {@see http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context}
1598 * matching your post type. Example: <code>_x('Add New', 'product');</code>.
1599 * - add_new_item - Default is Add New Post/Add New Page.
1600 * - edit_item - Default is Edit Post/Edit Page.
1601 * - new_item - Default is New Post/New Page.
1602 * - view_item - Default is View Post/View Page.
1603 * - search_items - Default is Search Posts/Search Pages.
1604 * - not_found - Default is No posts found/No pages found.
1605 * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash.
1606 * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical
1607 * ones the default is 'Parent Page:'.
1608 * - all_items - String for the submenu. Default is All Posts/All Pages.
1609 * - menu_name - Default is the same as <code>name</code>.
1611 * Above, the first default value is for non-hierarchical post types (like posts)
1612 * and the second one is for hierarchical post types (like pages).
1617 * @param object $post_type_object Post type object.
1618 * @return object object with all the labels as member variables.
1620 function get_post_type_labels( $post_type_object ) {
1621 $nohier_vs_hier_defaults = array(
1622 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1623 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1624 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1625 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1626 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1627 'new_item' => array( __('New Post'), __('New Page') ),
1628 'view_item' => array( __('View Post'), __('View Page') ),
1629 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1630 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1631 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1632 'parent_item_colon' => array( null, __('Parent Page:') ),
1633 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
1635 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1637 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1639 $post_type = $post_type_object->name;
1642 * Filter the labels of a specific post type.
1644 * The dynamic portion of the hook name, $post_type, refers to
1645 * the post type slug.
1649 * @see get_post_type_labels() for the full list of labels.
1651 * @param array $labels Array of labels for the given post type.
1653 return apply_filters( "post_type_labels_{$post_type}", $labels );
1657 * Build an object with custom-something object (post type, taxonomy) labels
1658 * out of a custom-something object
1663 * @param object $object A custom-something object.
1664 * @param array $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
1666 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1667 $object->labels = (array) $object->labels;
1669 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1670 $object->labels['name'] = $object->label;
1672 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1673 $object->labels['singular_name'] = $object->labels['name'];
1675 if ( ! isset( $object->labels['name_admin_bar'] ) )
1676 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1678 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1679 $object->labels['menu_name'] = $object->labels['name'];
1681 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1682 $object->labels['all_items'] = $object->labels['menu_name'];
1684 foreach ( $nohier_vs_hier_defaults as $key => $value )
1685 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1687 $labels = array_merge( $defaults, $object->labels );
1688 return (object)$labels;
1692 * Add submenus for post types.
1697 function _add_post_type_submenus() {
1698 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1699 $ptype_obj = get_post_type_object( $ptype );
1701 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1703 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" );
1706 add_action( 'admin_menu', '_add_post_type_submenus' );
1709 * Register support of certain features for a post type.
1711 * All core features are directly associated with a functional area of the edit
1712 * screen, such as the editor or a meta box. Features include: 'title', 'editor',
1713 * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
1714 * 'thumbnail', 'custom-fields', and 'post-formats'.
1716 * Additionally, the 'revisions' feature dictates whether the post type will
1717 * store revisions, and the 'comments' feature dictates whether the comments
1718 * count will show on the edit screen.
1722 * @param string $post_type The post type for which to add the feature.
1723 * @param string|array $feature The feature being added, accepts an array of
1724 * feature strings or a single string.
1726 function add_post_type_support( $post_type, $feature ) {
1727 global $_wp_post_type_features;
1729 $features = (array) $feature;
1730 foreach ($features as $feature) {
1731 if ( func_num_args() == 2 )
1732 $_wp_post_type_features[$post_type][$feature] = true;
1734 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1739 * Remove support for a feature from a post type.
1743 * @param string $post_type The post type for which to remove the feature.
1744 * @param string $feature The feature being removed.
1746 function remove_post_type_support( $post_type, $feature ) {
1747 global $_wp_post_type_features;
1749 if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
1750 unset( $_wp_post_type_features[$post_type][$feature] );
1754 * Get all the post type features
1758 * @param string $post_type The post type.
1759 * @return array Post type supports list.
1761 function get_all_post_type_supports( $post_type ) {
1762 global $_wp_post_type_features;
1764 if ( isset( $_wp_post_type_features[$post_type] ) )
1765 return $_wp_post_type_features[$post_type];
1771 * Check a post type's support for a given feature.
1775 * @param string $post_type The post type being checked.
1776 * @param string $feature the feature being checked.
1777 * @return bool Whether the post type supports the given feature.
1779 function post_type_supports( $post_type, $feature ) {
1780 global $_wp_post_type_features;
1782 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1786 * Update the post type for the post ID.
1788 * The page or post cache will be cleaned for the post ID.
1792 * @global wpdb $wpdb WordPress database access abstraction object.
1794 * @param int $post_id Optional. Post ID to change post type. Default 0.
1795 * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
1796 * name a few. Default 'post'.
1797 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
1799 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1802 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1803 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1805 clean_post_cache( $post_id );
1811 * Retrieve list of latest posts or posts matching criteria.
1813 * The defaults are as follows:
1817 * @see WP_Query::parse_query()
1819 * @param array $args {
1820 * Optional. Arguments to retrieve posts. {@see WP_Query::parse_query()} for more
1821 * available arguments.
1823 * @type int $numberposts Total number of posts to retrieve. Is an alias of $posts_per_page
1824 * in WP_Query. Accepts 1+ and -1 for all. Default 5.
1825 * @type int $offset The number of posts to offset before retrieval. Default 0.
1826 * @type int|string $category Category ID or comma-separated list of IDs (this or any children).
1827 * Is an alias of $cat in WP_Query. Default 0.
1828 * @type string $orderby Which field to order posts by. Accepts post fields. Default 'date'.
1829 * @type array $include An array of post IDs to retrieve, sticky posts will be included.
1830 * Is an alias of $post__in in WP_Query. Default empty array.
1831 * @type array $exclude An array of post IDs not to retrieve. Default empty array.
1832 * @type string $meta_key Custom field key. Default empty.
1833 * @type mixed $meta_value Custom field value. Default empty string.
1834 * @type string $post_type Post type. Default 'post'.
1835 * @type bool $suppress_filters Whether to suppress filters. Default true.
1837 * @return array List of posts.
1839 function get_posts( $args = null ) {
1841 'numberposts' => 5, 'offset' => 0,
1842 'category' => 0, 'orderby' => 'date',
1843 'order' => 'DESC', 'include' => array(),
1844 'exclude' => array(), 'meta_key' => '',
1845 'meta_value' =>'', 'post_type' => 'post',
1846 'suppress_filters' => true
1849 $r = wp_parse_args( $args, $defaults );
1850 if ( empty( $r['post_status'] ) )
1851 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1852 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1853 $r['posts_per_page'] = $r['numberposts'];
1854 if ( ! empty($r['category']) )
1855 $r['cat'] = $r['category'];
1856 if ( ! empty($r['include']) ) {
1857 $incposts = wp_parse_id_list( $r['include'] );
1858 $r['posts_per_page'] = count($incposts); // only the number of posts included
1859 $r['post__in'] = $incposts;
1860 } elseif ( ! empty($r['exclude']) )
1861 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1863 $r['ignore_sticky_posts'] = true;
1864 $r['no_found_rows'] = true;
1866 $get_posts = new WP_Query;
1867 return $get_posts->query($r);
1872 // Post meta functions
1876 * Add meta data field to a post.
1878 * Post meta data is called "Custom Fields" on the Administration Screen.
1882 * @param int $post_id Post ID.
1883 * @param string $meta_key Metadata name.
1884 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1885 * @param bool $unique Optional. Whether the same key should not be added.
1887 * @return int|bool Meta ID on success, false on failure.
1889 function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
1890 // Make sure meta is added to the post, not a revision.
1891 if ( $the_post = wp_is_post_revision($post_id) )
1892 $post_id = $the_post;
1894 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1898 * Remove metadata matching criteria from a post.
1900 * You can match based on the key, or key and value. Removing based on key and
1901 * value, will keep from removing duplicate metadata with the same key. It also
1902 * allows removing all metadata matching key, if needed.
1906 * @param int $post_id Post ID.
1907 * @param string $meta_key Metadata name.
1908 * @param mixed $meta_value Optional. Metadata value. Must be serializable if
1909 * non-scalar. Default empty.
1910 * @return bool True on success, false on failure.
1912 function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
1913 // Make sure meta is added to the post, not a revision.
1914 if ( $the_post = wp_is_post_revision($post_id) )
1915 $post_id = $the_post;
1917 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1921 * Retrieve post meta field for a post.
1925 * @param int $post_id Post ID.
1926 * @param string $key Optional. The meta key to retrieve. By default, returns
1927 * data for all keys. Default empty.
1928 * @param bool $single Optional. Whether to return a single value. Default false.
1929 * @return mixed Will be an array if $single is false. Will be value of meta data
1930 * field if $single is true.
1932 function get_post_meta( $post_id, $key = '', $single = false ) {
1933 return get_metadata('post', $post_id, $key, $single);
1937 * Update post meta field based on post ID.
1939 * Use the $prev_value parameter to differentiate between meta fields with the
1940 * same key and post ID.
1942 * If the meta field for the post does not exist, it will be added.
1946 * @param int $post_id Post ID.
1947 * @param string $meta_key Metadata key.
1948 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1949 * @param mixed $prev_value Optional. Previous value to check before removing.
1951 * @return int|bool Meta ID if the key didn't exist, true on successful update,
1954 function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
1955 // Make sure meta is added to the post, not a revision.
1956 if ( $the_post = wp_is_post_revision($post_id) )
1957 $post_id = $the_post;
1959 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1963 * Delete everything from post meta matching meta key.
1967 * @param string $post_meta_key Key to search for when deleting.
1968 * @return bool Whether the post meta key was deleted from the database.
1970 function delete_post_meta_by_key( $post_meta_key ) {
1971 return delete_metadata( 'post', null, $post_meta_key, '', true );
1975 * Retrieve post meta fields, based on post ID.
1977 * The post meta fields are retrieved from the cache where possible,
1978 * so the function is optimized to be called more than once.
1982 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1983 * @return array Post meta for the given post.
1985 function get_post_custom( $post_id = 0 ) {
1986 $post_id = absint( $post_id );
1988 $post_id = get_the_ID();
1990 return get_post_meta( $post_id );
1994 * Retrieve meta field names for a post.
1996 * If there are no meta fields, then nothing (null) will be returned.
2000 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2001 * @return array|null Either array of the keys, or null if keys could not be
2004 function get_post_custom_keys( $post_id = 0 ) {
2005 $custom = get_post_custom( $post_id );
2007 if ( !is_array($custom) )
2010 if ( $keys = array_keys($custom) )
2015 * Retrieve values for a custom post field.
2017 * The parameters must not be considered optional. All of the post meta fields
2018 * will be retrieved and only the meta field key values returned.
2022 * @param string $key Optional. Meta field key. Default empty.
2023 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2024 * @return array Meta field values.
2026 function get_post_custom_values( $key = '', $post_id = 0 ) {
2030 $custom = get_post_custom($post_id);
2032 return isset($custom[$key]) ? $custom[$key] : null;
2036 * Check if post is sticky.
2038 * Sticky posts should remain at the top of The Loop. If the post ID is not
2039 * given, then The Loop ID for the current post will be used.
2043 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2044 * @return bool Whether post is sticky.
2046 function is_sticky( $post_id = 0 ) {
2047 $post_id = absint( $post_id );
2050 $post_id = get_the_ID();
2052 $stickies = get_option( 'sticky_posts' );
2054 if ( ! is_array( $stickies ) )
2057 if ( in_array( $post_id, $stickies ) )
2064 * Sanitize every post field.
2066 * If the context is 'raw', then the post object or array will get minimal
2067 * sanitization of the integer fields.
2071 * @see sanitize_post_field()
2073 * @param object|WP_Post|array $post The Post Object or Array
2074 * @param string $context Optional. How to sanitize post fields.
2075 * Accepts 'raw', 'edit', 'db', or 'display'.
2076 * Default 'display'.
2077 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the
2078 * same type as $post).
2080 function sanitize_post( $post, $context = 'display' ) {
2081 if ( is_object($post) ) {
2082 // Check if post already filtered for this context.
2083 if ( isset($post->filter) && $context == $post->filter )
2085 if ( !isset($post->ID) )
2087 foreach ( array_keys(get_object_vars($post)) as $field )
2088 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
2089 $post->filter = $context;
2091 // Check if post already filtered for this context.
2092 if ( isset($post['filter']) && $context == $post['filter'] )
2094 if ( !isset($post['ID']) )
2096 foreach ( array_keys($post) as $field )
2097 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
2098 $post['filter'] = $context;
2104 * Sanitize post field based on context.
2106 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and
2107 * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
2108 * are treated like 'display' when calling filters.
2112 * @param string $field The Post Object field name.
2113 * @param mixed $value The Post Object value.
2114 * @param int $post_id Post ID.
2115 * @param string $context How to sanitize post fields. Looks for 'raw', 'edit',
2116 * 'db', 'display', 'attribute' and 'js'.
2117 * @return mixed Sanitized value.
2119 function sanitize_post_field($field, $value, $post_id, $context) {
2120 $int_fields = array('ID', 'post_parent', 'menu_order');
2121 if ( in_array($field, $int_fields) )
2122 $value = (int) $value;
2124 // Fields which contain arrays of integers.
2125 $array_int_fields = array( 'ancestors' );
2126 if ( in_array($field, $array_int_fields) ) {
2127 $value = array_map( 'absint', $value);
2131 if ( 'raw' == $context )
2135 if ( false !== strpos($field, 'post_') ) {
2137 $field_no_prefix = str_replace('post_', '', $field);
2140 if ( 'edit' == $context ) {
2141 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
2146 * Filter the value of a specific post field to edit.
2148 * The dynamic portion of the hook name, $field, refers to the post
2153 * @param mixed $value Value of the post field.
2154 * @param int $post_id Post ID.
2156 $value = apply_filters( "edit_{$field}", $value, $post_id );
2159 * Filter the value of a specific post field to edit.
2161 * The dynamic portion of the hook name, $field_no_prefix, refers to
2162 * the post field name.
2166 * @param mixed $value Value of the post field.
2167 * @param int $post_id Post ID.
2169 $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
2171 $value = apply_filters( "edit_post_{$field}", $value, $post_id );
2174 if ( in_array($field, $format_to_edit) ) {
2175 if ( 'post_content' == $field )
2176 $value = format_to_edit($value, user_can_richedit());
2178 $value = format_to_edit($value);
2180 $value = esc_attr($value);
2182 } else if ( 'db' == $context ) {
2186 * Filter the value of a specific post field before saving.
2188 * The dynamic portion of the hook name, $field, refers to the post
2193 * @param mixed $value Value of the post field.
2195 $value = apply_filters( "pre_{$field}", $value );
2198 * Filter the value of a specific field before saving.
2200 * The dynamic portion of the hook name, $field_no_prefix, refers
2201 * to the post field name.
2205 * @param mixed $value Value of the post field.
2207 $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
2209 $value = apply_filters( "pre_post_{$field}", $value );
2212 * Filter the value of a specific post field before saving.
2214 * The dynamic portion of the hook name, $field, refers to the post
2219 * @param mixed $value Value of the post field.
2221 $value = apply_filters( "{$field}_pre", $value );
2225 // Use display filters by default.
2229 * Filter the value of a specific post field for display.
2231 * The dynamic portion of the hook name, $field, refers to the post
2236 * @param mixed $value Value of the prefixed post field.
2237 * @param int $post_id Post ID.
2238 * @param string $context Context for how to sanitize the field. Possible
2239 * values include 'raw', 'edit', 'db', 'display',
2240 * 'attribute' and 'js'.
2242 $value = apply_filters( $field, $value, $post_id, $context );
2244 $value = apply_filters( "post_{$field}", $value, $post_id, $context );
2248 if ( 'attribute' == $context )
2249 $value = esc_attr($value);
2250 else if ( 'js' == $context )
2251 $value = esc_js($value);
2257 * Make a post sticky.
2259 * Sticky posts should be displayed at the top of the front page.
2263 * @param int $post_id Post ID.
2265 function stick_post( $post_id ) {
2266 $stickies = get_option('sticky_posts');
2268 if ( !is_array($stickies) )
2269 $stickies = array($post_id);
2271 if ( ! in_array($post_id, $stickies) )
2272 $stickies[] = $post_id;
2274 update_option('sticky_posts', $stickies);
2280 * Sticky posts should be displayed at the top of the front page.
2284 * @param int $post_id Post ID.
2286 function unstick_post( $post_id ) {
2287 $stickies = get_option('sticky_posts');
2289 if ( !is_array($stickies) )
2292 if ( ! in_array($post_id, $stickies) )
2295 $offset = array_search($post_id, $stickies);
2296 if ( false === $offset )
2299 array_splice($stickies, $offset, 1);
2301 update_option('sticky_posts', $stickies);
2305 * Return the cache key for wp_count_posts() based on the passed arguments.
2309 * @param string $type Optional. Post type to retrieve count Default 'post'.
2310 * @param string $perm Optional. 'readable' or empty. Default empty.
2311 * @return string The cache key.
2313 function _count_posts_cache_key( $type = 'post', $perm = '' ) {
2314 $cache_key = 'posts-' . $type;
2315 if ( 'readable' == $perm && is_user_logged_in() ) {
2316 $post_type_object = get_post_type_object( $type );
2317 if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2318 $cache_key .= '_' . $perm . '_' . get_current_user_id();
2325 * Count number of posts of a post type and if user has permissions to view.
2327 * This function provides an efficient method of finding the amount of post's
2328 * type a blog has. Another method is to count the amount of items in
2329 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2330 * when developing for 2.5+, use this function instead.
2332 * The $perm parameter checks for 'readable' value and if the user can read
2333 * private posts, it will display that for the user that is signed in.
2337 * @param string $type Optional. Post type to retrieve count. Default 'post'.
2338 * @param string $perm Optional. 'readable' or empty. Default empty.
2339 * @return object Number of posts for each status.
2341 function wp_count_posts( $type = 'post', $perm = '' ) {
2344 if ( ! post_type_exists( $type ) )
2345 return new stdClass;
2347 $cache_key = _count_posts_cache_key( $type, $perm );
2349 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2350 if ( 'readable' == $perm && is_user_logged_in() ) {
2351 $post_type_object = get_post_type_object($type);
2352 if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2353 $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
2354 get_current_user_id()
2358 $query .= ' GROUP BY post_status';
2360 $counts = wp_cache_get( $cache_key, 'counts' );
2361 if ( false === $counts ) {
2362 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2363 $counts = array_fill_keys( get_post_stati(), 0 );
2365 foreach ( $results as $row )
2366 $counts[ $row['post_status'] ] = $row['num_posts'];
2368 $counts = (object) $counts;
2369 wp_cache_set( $cache_key, $counts, 'counts' );
2373 * Modify returned post counts by status for the current post type.
2377 * @param object $counts An object containing the current post_type's post
2379 * @param string $type Post type.
2380 * @param string $perm The permission to determine if the posts are 'readable'
2381 * by the current user.
2383 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2387 * Count number of attachments for the mime type(s).
2389 * If you set the optional mime_type parameter, then an array will still be
2390 * returned, but will only have the item you are looking for. It does not give
2391 * you the number of attachments that are children of a post. You can get that
2392 * by counting the number of children that post has.
2396 * @param string|array $mime_type Optional. Array or comma-separated list of
2397 * MIME patterns. Default empty.
2398 * @return object An object containing the attachment counts by mime type.
2400 function wp_count_attachments( $mime_type = '' ) {
2403 $and = wp_post_mime_type_where( $mime_type );
2404 $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 );
2407 foreach( (array) $count as $row ) {
2408 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2410 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2413 * Modify returned attachment counts by mime type.
2417 * @param object $counts An object containing the attachment counts by
2419 * @param string $mime_type The mime type pattern used to filter the attachments
2422 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2426 * Get default post mime types.
2430 * @return array List of post mime types.
2432 function get_post_mime_types() {
2433 $post_mime_types = array( // array( adj, noun )
2434 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2435 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2436 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2440 * Filter the default list of post mime types.
2444 * @param array $post_mime_types Default list of post mime types.
2446 return apply_filters( 'post_mime_types', $post_mime_types );
2450 * Check a MIME-Type against a list.
2452 * If the wildcard_mime_types parameter is a string, it must be comma separated
2453 * list. If the real_mime_types is a string, it is also comma separated to
2458 * @param string|array $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
2459 * or flash (same as *flash*).
2460 * @param string|array $real_mime_types Real post mime type values.
2461 * @return array array(wildcard=>array(real types)).
2463 function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
2465 if ( is_string( $wildcard_mime_types ) ) {
2466 $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
2468 if ( is_string( $real_mime_types ) ) {
2469 $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
2472 $patternses = array();
2473 $wild = '[-._a-z0-9]*';
2475 foreach ( (array) $wildcard_mime_types as $type ) {
2476 $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $type ) ) );
2477 $patternses[1][$type] = "^$regex$";
2478 if ( false === strpos($type, '/') ) {
2479 $patternses[2][$type] = "^$regex/";
2480 $patternses[3][$type] = $regex;
2483 asort( $patternses );
2485 foreach ( $patternses as $patterns ) {
2486 foreach ( $patterns as $type => $pattern ) {
2487 foreach ( (array) $real_mime_types as $real ) {
2488 if ( preg_match( "#$pattern#", $real ) && ( empty( $matches[$type] ) || false === array_search( $real, $matches[$type] ) ) ) {
2489 $matches[$type][] = $real;
2498 * Convert MIME types into SQL.
2502 * @param string|array $post_mime_types List of mime types or comma separated string
2504 * @param string $table_alias Optional. Specify a table alias, if needed.
2506 * @return string The SQL AND clause for mime searching.
2508 function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
2510 $wildcards = array('', '%', '%/%');
2511 if ( is_string($post_mime_types) )
2512 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2513 foreach ( (array) $post_mime_types as $mime_type ) {
2514 $mime_type = preg_replace('/\s/', '', $mime_type);
2515 $slashpos = strpos($mime_type, '/');
2516 if ( false !== $slashpos ) {
2517 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2518 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2519 if ( empty($mime_subgroup) )
2520 $mime_subgroup = '*';
2522 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2523 $mime_pattern = "$mime_group/$mime_subgroup";
2525 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2526 if ( false === strpos($mime_pattern, '*') )
2527 $mime_pattern .= '/*';
2530 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2532 if ( in_array( $mime_type, $wildcards ) )
2535 if ( false !== strpos($mime_pattern, '%') )
2536 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2538 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2540 if ( !empty($wheres) )
2541 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2546 * Trash or delete a post or page.
2548 * When the post and page is permanently deleted, everything that is tied to
2549 * it is deleted also. This includes comments, post meta fields, and terms
2550 * associated with the post.
2552 * The post or page is moved to trash instead of permanently deleted unless
2553 * trash is disabled, item is already in the trash, or $force_delete is true.
2557 * @global wpdb $wpdb WordPress database access abstraction object.
2558 * @see wp_delete_attachment()
2559 * @see wp_trash_post()
2561 * @param int $postid Optional. Post ID. Default 0.
2562 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
2564 * @return array|bool|WP_Post False on failure.
2566 function wp_delete_post( $postid = 0, $force_delete = false ) {
2569 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2572 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2573 return wp_trash_post($postid);
2575 if ( $post->post_type == 'attachment' )
2576 return wp_delete_attachment( $postid, $force_delete );
2579 * Fires before a post is deleted, at the start of wp_delete_post().
2583 * @see wp_delete_post()
2585 * @param int $postid Post ID.
2587 do_action( 'before_delete_post', $postid );
2589 delete_post_meta($postid,'_wp_trash_meta_status');
2590 delete_post_meta($postid,'_wp_trash_meta_time');
2592 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2594 $parent_data = array( 'post_parent' => $post->post_parent );
2595 $parent_where = array( 'post_parent' => $postid );
2597 if ( is_post_type_hierarchical( $post->post_type ) ) {
2598 // Point children of this page to its parent, also clean the cache of affected children.
2599 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2600 $children = $wpdb->get_results( $children_query );
2602 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2605 // Do raw query. wp_get_post_revisions() is filtered.
2606 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2607 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2608 foreach ( $revision_ids as $revision_id )
2609 wp_delete_post_revision( $revision_id );
2611 // Point all attachments to this post up one level.
2612 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2614 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2615 foreach ( $comment_ids as $comment_id )
2616 wp_delete_comment( $comment_id, true );
2618 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2619 foreach ( $post_meta_ids as $mid )
2620 delete_metadata_by_mid( 'post', $mid );
2623 * Fires immediately before a post is deleted from the database.
2627 * @param int $postid Post ID.
2629 do_action( 'delete_post', $postid );
2630 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2636 * Fires immediately after a post is deleted from the database.
2640 * @param int $postid Post ID.
2642 do_action( 'deleted_post', $postid );
2644 clean_post_cache( $post );
2646 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2647 foreach ( $children as $child )
2648 clean_post_cache( $child );
2651 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2654 * Fires after a post is deleted, at the conclusion of wp_delete_post().
2658 * @see wp_delete_post()
2660 * @param int $postid Post ID.
2662 do_action( 'after_delete_post', $postid );
2668 * Reset the page_on_front, show_on_front, and page_for_post settings when
2669 * a linked page is deleted or trashed.
2671 * Also ensures the post is no longer sticky.
2676 * @param int $post_id Post ID.
2678 function _reset_front_page_settings_for_post( $post_id ) {
2679 $post = get_post( $post_id );
2680 if ( 'page' == $post->post_type ) {
2682 * If the page is defined in option page_on_front or post_for_posts,
2683 * adjust the corresponding options.
2685 if ( get_option( 'page_on_front' ) == $post->ID ) {
2686 update_option( 'show_on_front', 'posts' );
2687 update_option( 'page_on_front', 0 );
2689 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2690 delete_option( 'page_for_posts', 0 );
2693 unstick_post( $post->ID );
2695 add_action( 'before_delete_post', '_reset_front_page_settings_for_post' );
2696 add_action( 'wp_trash_post', '_reset_front_page_settings_for_post' );
2699 * Move a post or page to the Trash
2701 * If trash is disabled, the post or page is permanently deleted.
2705 * @see wp_delete_post()
2707 * @param int $post_id Optional. Post ID. Default is ID of the global $post
2708 * if EMPTY_TRASH_DAYS equals true.
2709 * @return bool|array Post data array, otherwise false.
2711 function wp_trash_post( $post_id = 0 ) {
2712 if ( !EMPTY_TRASH_DAYS )
2713 return wp_delete_post($post_id, true);
2715 if ( !$post = get_post($post_id, ARRAY_A) )
2718 if ( $post['post_status'] == 'trash' )
2722 * Fires before a post is sent to the trash.
2726 * @param int $post_id Post ID.
2728 do_action( 'wp_trash_post', $post_id );
2730 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2731 add_post_meta($post_id,'_wp_trash_meta_time', time());
2733 $post['post_status'] = 'trash';
2734 wp_insert_post($post);
2736 wp_trash_post_comments($post_id);
2739 * Fires after a post is sent to the trash.
2743 * @param int $post_id Post ID.
2745 do_action( 'trashed_post', $post_id );
2751 * Restore a post or page from the Trash.
2755 * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2756 * @return WP_Post|bool WP_Post object. False on failure.
2758 function wp_untrash_post( $post_id = 0 ) {
2759 if ( !$post = get_post($post_id, ARRAY_A) )
2762 if ( $post['post_status'] != 'trash' )
2766 * Fires before a post is restored from the trash.
2770 * @param int $post_id Post ID.
2772 do_action( 'untrash_post', $post_id );
2774 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2776 $post['post_status'] = $post_status;
2778 delete_post_meta($post_id, '_wp_trash_meta_status');
2779 delete_post_meta($post_id, '_wp_trash_meta_time');
2781 wp_insert_post($post);
2783 wp_untrash_post_comments($post_id);
2786 * Fires after a post is restored from the trash.
2790 * @param int $post_id Post ID.
2792 do_action( 'untrashed_post', $post_id );
2798 * Moves comments for a post to the trash.
2802 * @global wpdb $wpdb WordPress database access abstraction object.
2804 * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
2805 * @return mixed False on failure.
2807 function wp_trash_post_comments( $post = null ) {
2810 $post = get_post($post);
2814 $post_id = $post->ID;
2817 * Fires before comments are sent to the trash.
2821 * @param int $post_id Post ID.
2823 do_action( 'trash_post_comments', $post_id );
2825 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2826 if ( empty($comments) )
2829 // Cache current status for each comment.
2830 $statuses = array();
2831 foreach ( $comments as $comment )
2832 $statuses[$comment->comment_ID] = $comment->comment_approved;
2833 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2835 // Set status for all comments to post-trashed.
2836 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2838 clean_comment_cache( array_keys($statuses) );
2841 * Fires after comments are sent to the trash.
2845 * @param int $post_id Post ID.
2846 * @param array $statuses Array of comment statuses.
2848 do_action( 'trashed_post_comments', $post_id, $statuses );
2854 * Restore comments for a post from the trash.
2858 * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
2859 * @return mixed False on failure.
2861 function wp_untrash_post_comments( $post = null ) {
2864 $post = get_post($post);
2868 $post_id = $post->ID;
2870 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2872 if ( empty($statuses) )
2876 * Fires before comments are restored for a post from the trash.
2880 * @param int $post_id Post ID.
2882 do_action( 'untrash_post_comments', $post_id );
2884 // Restore each comment to its original status.
2885 $group_by_status = array();
2886 foreach ( $statuses as $comment_id => $comment_status )
2887 $group_by_status[$comment_status][] = $comment_id;
2889 foreach ( $group_by_status as $status => $comments ) {
2890 // Sanity check. This shouldn't happen.
2891 if ( 'post-trashed' == $status )
2893 $comments_in = implode( "', '", $comments );
2894 $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
2897 clean_comment_cache( array_keys($statuses) );
2899 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2902 * Fires after comments are restored for a post from the trash.
2906 * @param int $post_id Post ID.
2908 do_action( 'untrashed_post_comments', $post_id );
2912 * Retrieve the list of categories for a post.
2914 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2915 * away from the complexity of the taxonomy layer.
2919 * @see wp_get_object_terms()
2921 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2922 * global $post. Default 0.
2923 * @param array $args Optional. Category arguments. Default empty.
2924 * @return array List of categories.
2926 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2927 $post_id = (int) $post_id;
2929 $defaults = array('fields' => 'ids');
2930 $args = wp_parse_args( $args, $defaults );
2932 $cats = wp_get_object_terms($post_id, 'category', $args);
2937 * Retrieve the tags for a post.
2939 * There is only one default for this function, called 'fields' and by default
2940 * is set to 'all'. There are other defaults that can be overridden in
2941 * {@link wp_get_object_terms()}.
2945 * @uses wp_get_object_terms()
2947 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2948 * global $post. Defualt 0.
2949 * @param array $args Optional. Overwrite the defaults
2950 * @return array List of post tags.
2952 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2953 return wp_get_post_terms( $post_id, 'post_tag', $args);
2957 * Retrieve the terms for a post.
2959 * There is only one default for this function, called 'fields' and by default
2960 * is set to 'all'. There are other defaults that can be overridden in
2961 * {@link wp_get_object_terms()}.
2965 * @uses wp_get_object_terms()
2967 * @param int $post_id Optional. The Post ID. Does not default to the ID of the
2968 * global $post. Default 0.
2969 * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
2970 * @param array $args Optional. {@link wp_get_object_terms()} arguments. Default empty array.
2971 * @return array List of post tags.
2973 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2974 $post_id = (int) $post_id;
2976 $defaults = array('fields' => 'all');
2977 $args = wp_parse_args( $args, $defaults );
2979 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2985 * Retrieve a number of recent posts.
2991 * @param string $deprecated Not used.
2992 * @param array $args Optional. Arguments to retrieve posts. Default empty array.
2993 * @param string $output Optional. Type of output. Accepts ARRAY_A or ''. Default ARRAY_A.
2994 * @return array|bool Associative array if $output equals ARRAY_A, array or false if no results.
2996 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2998 if ( is_numeric( $args ) ) {
2999 _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
3000 $args = array( 'numberposts' => absint( $args ) );
3003 // Set default arguments.
3005 'numberposts' => 10, 'offset' => 0,
3006 'category' => 0, 'orderby' => 'post_date',
3007 'order' => 'DESC', 'include' => '',
3008 'exclude' => '', 'meta_key' => '',
3009 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
3010 'suppress_filters' => true
3013 $r = wp_parse_args( $args, $defaults );
3015 $results = get_posts( $r );
3017 // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
3018 if ( ARRAY_A == $output ){
3019 foreach( $results as $key => $result ) {
3020 $results[$key] = get_object_vars( $result );
3022 return $results ? $results : array();
3025 return $results ? $results : false;
3030 * Insert or update a post.
3032 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
3034 * You can set the post date manually, by setting the values for 'post_date'
3035 * and 'post_date_gmt' keys. You can close the comments or open the comments by
3036 * setting the value for 'comment_status' key.
3040 * @see sanitize_post()
3041 * @global wpdb $wpdb WordPress database abstraction object.
3043 * @param array $postarr {
3044 * An array of elements that make up a post to update or insert.
3046 * @type int $ID The post ID. If equal to something other than 0,
3047 * the post with that ID will be updated. Default 0.
3048 * @type string $post_status The post status. Default 'draft'.
3049 * @type string $post_type The post type. Default 'post'.
3050 * @type int $post_author The ID of the user who added the post. Default is
3051 * the current user ID.
3052 * @type bool $ping_status Whether the post can accept pings. Default is the
3053 * value of 'default_ping_status' option.
3054 * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
3055 * @type int $menu_order The order it is displayed. Default 0.
3056 * @type string $to_ping Space or carriage return-separated list of URLs to ping.
3057 * Default empty string.
3058 * @type string $pinged Space or carriage return-separated list of URLs that have
3059 * been pinged. Default empty string.
3060 * @type string $post_password The password to access the post. Default empty string.
3061 * @type string $guid' Global Unique ID for referencing the post.
3062 * @type string $post_content_filtered The filtered post content. Default empty string.
3063 * @type string $post_excerpt The post excerpt. Default empty string.
3065 * @param bool $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
3066 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
3068 function wp_insert_post( $postarr, $wp_error = false ) {
3071 $user_id = get_current_user_id();
3073 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id,
3074 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
3075 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
3076 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
3077 'post_content' => '', 'post_title' => '', 'context' => '');
3079 $postarr = wp_parse_args($postarr, $defaults);
3081 unset( $postarr[ 'filter' ] );
3083 $postarr = sanitize_post($postarr, 'db');
3085 // Are we updating or creating?
3088 $guid = $postarr['guid'];
3090 if ( ! empty( $postarr['ID'] ) ) {
3093 // Get the post ID and GUID.
3094 $post_ID = $postarr['ID'];
3095 $post_before = get_post( $post_ID );
3096 if ( is_null( $post_before ) ) {
3098 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3103 $guid = get_post_field( 'guid', $post_ID );
3104 $previous_status = get_post_field('post_status', $post_ID );
3106 $previous_status = 'new';
3109 $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
3111 $post_title = $postarr['post_title'];
3112 $post_content = $postarr['post_content'];
3113 $post_excerpt = $postarr['post_excerpt'];
3114 if ( isset( $postarr['post_name'] ) ) {
3115 $post_name = $postarr['post_name'];
3118 $maybe_empty = 'attachment' !== $post_type
3119 && ! $post_content && ! $post_title && ! $post_excerpt
3120 && post_type_supports( $post_type, 'editor' )
3121 && post_type_supports( $post_type, 'title' )
3122 && post_type_supports( $post_type, 'excerpt' );
3125 * Filter whether the post should be considered "empty".
3127 * The post is considered "empty" if both:
3128 * 1. The post type supports the title, editor, and excerpt fields
3129 * 2. The title, editor, and excerpt fields are all empty
3131 * Returning a truthy value to the filter will effectively short-circuit
3132 * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
3133 * will be returned instead.
3137 * @param bool $maybe_empty Whether the post should be considered "empty".
3138 * @param array $postarr Array of post data.
3140 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
3142 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
3148 $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
3149 if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash' ) ) ) {
3150 $post_status = 'inherit';
3153 if ( ! empty( $postarr['post_category'] ) ) {
3154 // Filter out empty terms.
3155 $post_category = array_filter( $postarr['post_category'] );
3158 // Make sure we set a valid category.
3159 if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
3160 // 'post' requires at least one category.
3161 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3162 $post_category = array( get_option('default_category') );
3164 $post_category = array();
3168 // Don't allow contributors to set the post slug for pending review posts.
3169 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
3174 * Create a valid post name. Drafts and pending posts are allowed to have
3175 * an empty post name.
3177 if ( empty($post_name) ) {
3178 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3179 $post_name = sanitize_title($post_title);
3184 // On updates, we need to check to see if it's using the old, fixed sanitization context.
3185 $check_name = sanitize_title( $post_name, '', 'old-save' );
3186 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
3187 $post_name = $check_name;
3188 } else { // new post, or slug has changed.
3189 $post_name = sanitize_title($post_name);
3194 * If the post date is empty (due to having been new or a draft) and status
3195 * is not 'draft' or 'pending', set date to now.
3197 if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
3198 $post_date = current_time( 'mysql' );
3200 $post_date = $postarr['post_date'];
3203 // Validate the date.
3204 $mm = substr( $post_date, 5, 2 );
3205 $jj = substr( $post_date, 8, 2 );
3206 $aa = substr( $post_date, 0, 4 );
3207 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
3208 if ( ! $valid_date ) {
3210 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
3216 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3217 if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3218 $post_date_gmt = get_gmt_from_date( $post_date );
3220 $post_date_gmt = '0000-00-00 00:00:00';
3223 $post_date_gmt = $postarr['post_date_gmt'];
3226 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
3227 $post_modified = current_time( 'mysql' );
3228 $post_modified_gmt = current_time( 'mysql', 1 );
3230 $post_modified = $post_date;
3231 $post_modified_gmt = $post_date_gmt;
3234 if ( 'attachment' !== $post_type ) {
3235 if ( 'publish' == $post_status ) {
3236 $now = gmdate('Y-m-d H:i:59');
3237 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
3238 $post_status = 'future';
3240 } elseif( 'future' == $post_status ) {
3241 $now = gmdate('Y-m-d H:i:59');
3242 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) {
3243 $post_status = 'publish';
3248 if ( empty( $postarr['comment_status'] ) ) {
3250 $comment_status = 'closed';
3252 $comment_status = get_option('default_comment_status');
3255 $comment_status = $postarr['comment_status'];
3258 // These variables are needed by compact() later.
3259 $post_content_filtered = $postarr['post_content_filtered'];
3260 $post_author = empty( $postarr['post_author'] ) ? $user_id : $postarr['post_author'];
3261 $ping_status = empty( $postarr['ping_status'] ) ? get_option( 'default_ping_status' ) : $postarr['ping_status'];
3262 $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
3263 $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
3264 $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
3267 * The 'wp_insert_post_parent' filter expects all variables to be present.
3268 * Previously, these variables would have already been extracted
3270 if ( isset( $postarr['menu_order'] ) ) {
3271 $menu_order = (int) $postarr['menu_order'];
3276 $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
3277 if ( 'private' == $post_status ) {
3278 $post_password = '';
3281 if ( isset( $postarr['post_parent'] ) ) {
3282 $post_parent = (int) $postarr['post_parent'];
3288 * Filter the post parent -- used to check for and prevent hierarchy loops.
3292 * @param int $post_parent Post parent ID.
3293 * @param int $post_ID Post ID.
3294 * @param array $new_postarr Array of parsed post data.
3295 * @param array $postarr Array of sanitized, but otherwise unmodified post data.
3297 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
3299 $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
3302 $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
3304 // Expected_slashed (everything!).
3305 $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' );
3307 if ( 'attachment' === $post_type ) {
3309 * Filter attachment post data before it is updated in or added to the database.
3313 * @param array $data An array of sanitized attachment post data.
3314 * @param array $postarr An array of unsanitized attachment post data.
3316 $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
3319 * Filter slashed post data just before it is inserted into the database.
3323 * @param array $data An array of slashed post data.
3324 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3326 $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
3328 $data = wp_unslash( $data );
3329 $where = array( 'ID' => $post_ID );
3333 * Fires immediately before an existing post is updated in the database.
3337 * @param int $post_ID Post ID.
3338 * @param array $data Array of unslashed post data.
3340 do_action( 'pre_post_update', $post_ID, $data );
3341 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
3343 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
3349 // If there is a suggested ID, use it if not already present.
3350 if ( ! empty( $import_id ) ) {
3351 $import_id = (int) $import_id;
3352 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3353 $data['ID'] = $import_id;
3356 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
3358 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
3363 $post_ID = (int) $wpdb->insert_id;
3365 // Use the newly generated $post_ID.
3366 $where = array( 'ID' => $post_ID );
3369 if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
3370 $data['post_name'] = sanitize_title( $data['post_title'], $post_ID );
3371 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
3374 if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
3375 wp_set_post_categories( $post_ID, $post_category );
3378 if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
3379 wp_set_post_tags( $post_ID, $postarr['tags_input'] );
3382 // New-style support for all custom taxonomies.
3383 if ( ! empty( $postarr['tax_input'] ) ) {
3384 foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
3385 $taxonomy_obj = get_taxonomy($taxonomy);
3386 // array = hierarchical, string = non-hierarchical.
3387 if ( is_array( $tags ) ) {
3388 $tags = array_filter($tags);
3390 if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
3391 wp_set_post_terms( $post_ID, $tags, $taxonomy );
3396 $current_guid = get_post_field( 'guid', $post_ID );
3399 if ( ! $update && '' == $current_guid ) {
3400 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
3403 if ( 'attachment' === $postarr['post_type'] ) {
3404 if ( ! empty( $postarr['file'] ) ) {
3405 update_attached_file( $post_ID, $postarr['file'] );
3408 if ( ! empty( $postarr['context'] ) ) {
3409 add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
3413 clean_post_cache( $post_ID );
3415 $post = get_post( $post_ID );
3417 if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
3418 $post->page_template = $postarr['page_template'];
3419 $page_templates = wp_get_theme()->get_page_templates( $post );
3420 if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
3422 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
3427 update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
3430 if ( 'attachment' !== $postarr['post_type'] ) {
3431 wp_transition_post_status( $data['post_status'], $previous_status, $post );
3435 * Fires once an existing attachment has been updated.
3439 * @param int $post_ID Attachment ID.
3441 do_action( 'edit_attachment', $post_ID );
3445 * Fires once an attachment has been added.
3449 * @param int $post_ID Attachment ID.
3451 do_action( 'add_attachment', $post_ID );
3459 * Fires once an existing post has been updated.
3463 * @param int $post_ID Post ID.
3464 * @param WP_Post $post Post object.
3466 do_action( 'edit_post', $post_ID, $post );
3467 $post_after = get_post($post_ID);
3470 * Fires once an existing post has been updated.
3474 * @param int $post_ID Post ID.
3475 * @param WP_Post $post_after Post object following the update.
3476 * @param WP_Post $post_before Post object before the update.
3478 do_action( 'post_updated', $post_ID, $post_after, $post_before);
3482 * Fires once a post has been saved.
3484 * The dynamic portion of the hook name, $post->post_type, refers to
3485 * the post type slug.
3489 * @param int $post_ID Post ID.
3490 * @param WP_Post $post Post object.
3491 * @param bool $update Whether this is an existing post being updated or not.
3493 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
3496 * Fires once a post has been saved.
3500 * @param int $post_ID Post ID.
3501 * @param WP_Post $post Post object.
3502 * @param bool $update Whether this is an existing post being updated or not.
3504 do_action( 'save_post', $post_ID, $post, $update );
3507 * Fires once a post has been saved.
3511 * @param int $post_ID Post ID.
3512 * @param WP_Post $post Post object.
3513 * @param bool $update Whether this is an existing post being updated or not.
3515 do_action( 'wp_insert_post', $post_ID, $post, $update );
3521 * Update a post with new post data.
3523 * The date does not have to be set for drafts. You can set the date and it will
3524 * not be overridden.
3528 * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
3529 * objects are not. Default array.
3530 * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
3531 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
3533 function wp_update_post( $postarr = array(), $wp_error = false ) {
3534 if ( is_object($postarr) ) {
3535 // Non-escaped post was passed.
3536 $postarr = get_object_vars($postarr);
3537 $postarr = wp_slash($postarr);
3540 // First, get all of the original fields.
3541 $post = get_post($postarr['ID'], ARRAY_A);
3543 if ( is_null( $post ) ) {
3545 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3549 // Escape data pulled from DB.
3550 $post = wp_slash($post);
3552 // Passed post category list overwrites existing category list if not empty.
3553 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3554 && 0 != count($postarr['post_category']) )
3555 $post_cats = $postarr['post_category'];
3557 $post_cats = $post['post_category'];
3559 // Drafts shouldn't be assigned a date unless explicitly done so by the user.
3560 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3561 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3564 $clear_date = false;
3566 // Merge old and new fields with new fields overwriting old ones.
3567 $postarr = array_merge($post, $postarr);
3568 $postarr['post_category'] = $post_cats;
3569 if ( $clear_date ) {
3570 $postarr['post_date'] = current_time('mysql');
3571 $postarr['post_date_gmt'] = '';
3574 if ($postarr['post_type'] == 'attachment')
3575 return wp_insert_attachment($postarr);
3577 return wp_insert_post( $postarr, $wp_error );
3581 * Publish a post by transitioning the post status.
3585 * @global wpdb $wpdb WordPress database abstraction object.
3587 * @param int|WP_Post $post Post ID or post object.
3589 function wp_publish_post( $post ) {
3592 if ( ! $post = get_post( $post ) )
3595 if ( 'publish' == $post->post_status )
3598 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3600 clean_post_cache( $post->ID );
3602 $old_status = $post->post_status;
3603 $post->post_status = 'publish';
3604 wp_transition_post_status( 'publish', $old_status, $post );
3606 /** This action is documented in wp-includes/post.php */
3607 do_action( 'edit_post', $post->ID, $post );
3609 /** This action is documented in wp-includes/post.php */
3610 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3612 /** This action is documented in wp-includes/post.php */
3613 do_action( 'save_post', $post->ID, $post, true );
3615 /** This action is documented in wp-includes/post.php */
3616 do_action( 'wp_insert_post', $post->ID, $post, true );
3620 * Publish future post and make sure post ID has future post status.
3622 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3623 * from publishing drafts, etc.
3627 * @param int|WP_Post $post_id Post ID or post object.
3628 * @return null Nothing is returned. Which can mean that no action is required
3629 * or post was published.
3631 function check_and_publish_future_post( $post_id ) {
3633 $post = get_post($post_id);
3638 if ( 'future' != $post->post_status )
3641 $time = strtotime( $post->post_date_gmt . ' GMT' );
3643 // Uh oh, someone jumped the gun!
3644 if ( $time > time() ) {
3645 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3646 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3650 return wp_publish_post($post_id);
3654 * Computes a unique slug for the post, when given the desired slug and some post details.
3658 * @global wpdb $wpdb WordPress database abstraction object.
3659 * @global WP_Rewrite $wp_rewrite
3661 * @param string $slug The desired slug (post_name).
3662 * @param int $post_ID Post ID.
3663 * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
3664 * @param string $post_type Post type.
3665 * @param int $post_parent Post parent ID.
3666 * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3668 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3669 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3672 global $wpdb, $wp_rewrite;
3674 $original_slug = $slug;
3676 $feeds = $wp_rewrite->feeds;
3677 if ( ! is_array( $feeds ) )
3680 $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
3681 if ( 'attachment' == $post_type ) {
3682 // Attachment slugs must be unique across all types.
3683 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3684 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3687 * Filter whether the post slug would make a bad attachment slug.
3691 * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
3692 * @param string $slug The post slug.
3694 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3697 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3698 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3700 } while ( $post_name_check );
3701 $slug = $alt_post_name;
3703 } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
3704 if ( 'nav_menu_item' == $post_type )
3708 * Page slugs must be unique within their own trees. Pages are in a separate
3709 * namespace than posts so page slugs are allowed to overlap post slugs.
3711 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
3712 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
3715 * Filter whether the post slug would make a bad hierarchical post slug.
3719 * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
3720 * @param string $slug The post slug.
3721 * @param string $post_type Post type.
3722 * @param int $post_parent Post parent ID.
3724 if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
3727 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3728 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
3730 } while ( $post_name_check );
3731 $slug = $alt_post_name;
3734 // Post slugs must be unique across all posts.
3735 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3736 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3739 * Filter whether the post slug would be bad as a flat slug.
3743 * @param bool $bad_slug Whether the post slug would be bad as a flat slug.
3744 * @param string $slug The post slug.
3745 * @param string $post_type Post type.
3747 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3750 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3751 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3753 } while ( $post_name_check );
3754 $slug = $alt_post_name;
3759 * Filter the unique post slug.
3763 * @param string $slug The post slug.
3764 * @param int $post_ID Post ID.
3765 * @param string $post_status The post status.
3766 * @param string $post_type Post type.
3767 * @param int $post_parent Post parent ID
3768 * @param string $original_slug The original post slug.
3770 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3774 * Truncate a post slug.
3779 * @see utf8_uri_encode()
3781 * @param string $slug The slug to truncate.
3782 * @param int $length Optional. Max length of the slug. Default 200 (characters).
3783 * @return string The truncated slug.
3785 function _truncate_post_slug( $slug, $length = 200 ) {
3786 if ( strlen( $slug ) > $length ) {
3787 $decoded_slug = urldecode( $slug );
3788 if ( $decoded_slug === $slug )
3789 $slug = substr( $slug, 0, $length );
3791 $slug = utf8_uri_encode( $decoded_slug, $length );
3794 return rtrim( $slug, '-' );
3798 * Add tags to a post.
3800 * @see wp_set_post_tags()
3804 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3806 * @param string $tags Optional. The tags to set for the post, separated by commas. Default empty.
3807 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise.
3809 function wp_add_post_tags( $post_id = 0, $tags = '' ) {
3810 return wp_set_post_tags($post_id, $tags, true);
3814 * Set the tags for a post.
3818 * @see wp_set_object_terms()
3820 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3821 * @param string $tags Optional. The tags to set for the post, separated by commas.
3823 * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
3824 * replace the tags with the new tags. Default false.
3825 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3827 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3828 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3832 * Set the terms for a post.
3836 * @see wp_set_object_terms()
3838 * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3839 * @param string $tags Optional. The tags to set for the post, separated by commas. Default empty.
3840 * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
3841 * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
3842 * replace the tags with the new tags. Default false.
3843 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3845 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3846 $post_id = (int) $post_id;
3854 if ( ! is_array( $tags ) ) {
3855 $comma = _x( ',', 'tag delimiter' );
3856 if ( ',' !== $comma )
3857 $tags = str_replace( $comma, ',', $tags );
3858 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3862 * Hierarchical taxonomies must always pass IDs rather than names so that
3863 * children with the same names but different parents aren't confused.
3865 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3866 $tags = array_unique( array_map( 'intval', $tags ) );
3869 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3873 * Set categories for a post.
3875 * If the post categories parameter is not set, then the default category is
3880 * @param int $post_ID Optional. The Post ID. Does not default to the ID
3881 * of the global $post. Default 0.
3882 * @param array|int $post_categories Optional. List of categories or ID of category.
3883 * Default empty array.
3884 * @param bool $append If true, don't delete existing categories, just add on.
3885 * If false, replace the categories with the new categories.
3886 * @return bool|mixed
3888 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3889 $post_ID = (int) $post_ID;
3890 $post_type = get_post_type( $post_ID );
3891 $post_status = get_post_status( $post_ID );
3892 // If $post_categories isn't already an array, make it one:
3893 $post_categories = (array) $post_categories;
3894 if ( empty( $post_categories ) ) {
3895 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3896 $post_categories = array( get_option('default_category') );
3899 $post_categories = array();
3901 } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
3905 return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3909 * Transition the post status of a post.
3911 * Calls hooks to transition post status.
3913 * The first is 'transition_post_status' with new status, old status, and post data.
3915 * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
3916 * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
3919 * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
3920 * parameter and POSTTYPE is post_type post data.
3924 * @param string $new_status Transition to this post status.
3925 * @param string $old_status Previous post status.
3926 * @param object $post Post data.
3928 function wp_transition_post_status( $new_status, $old_status, $post ) {
3930 * Fires when a post is transitioned from one status to another.
3934 * @param string $new_status New post status.
3935 * @param string $old_status Old post status.
3936 * @param WP_Post $post Post object.