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' ),
78 register_post_type( 'revision', array(
80 'name' => __( 'Revisions' ),
81 'singular_name' => __( 'Revision' ),
84 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
85 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
86 'capability_type' => 'post',
87 'map_meta_cap' => true,
88 'hierarchical' => false,
91 'can_export' => false,
92 'delete_with_user' => true,
93 'supports' => array( 'author' ),
96 register_post_type( 'nav_menu_item', array(
98 'name' => __( 'Navigation Menu Items' ),
99 'singular_name' => __( 'Navigation Menu Item' ),
102 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
103 'hierarchical' => false,
105 'delete_with_user' => false,
106 'query_var' => false,
109 register_post_status( 'publish', array(
110 'label' => _x( 'Published', 'post' ),
112 '_builtin' => true, /* internal use only. */
113 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
116 register_post_status( 'future', array(
117 'label' => _x( 'Scheduled', 'post' ),
119 '_builtin' => true, /* internal use only. */
120 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
123 register_post_status( 'draft', array(
124 'label' => _x( 'Draft', 'post' ),
126 '_builtin' => true, /* internal use only. */
127 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
130 register_post_status( 'pending', array(
131 'label' => _x( 'Pending', 'post' ),
133 '_builtin' => true, /* internal use only. */
134 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
137 register_post_status( 'private', array(
138 'label' => _x( 'Private', 'post' ),
140 '_builtin' => true, /* internal use only. */
141 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
144 register_post_status( 'trash', array(
145 'label' => _x( 'Trash', 'post' ),
147 '_builtin' => true, /* internal use only. */
148 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
149 'show_in_admin_status_list' => true,
152 register_post_status( 'auto-draft', array(
153 'label' => 'auto-draft',
155 '_builtin' => true, /* internal use only. */
158 register_post_status( 'inherit', array(
159 'label' => 'inherit',
161 '_builtin' => true, /* internal use only. */
162 'exclude_from_search' => false,
165 add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
168 * Retrieve attached file path based on attachment ID.
170 * By default the path will go through the 'get_attached_file' filter, but
171 * passing a true to the $unfiltered argument of get_attached_file() will
172 * return the file path unfiltered.
174 * The function works by getting the single post meta name, named
175 * '_wp_attached_file' and returning it. This is a convenience function to
176 * prevent looking up the meta name and provide a mechanism for sending the
177 * attached filename through a filter.
181 * @param int $attachment_id Attachment ID.
182 * @param bool $unfiltered Whether to apply filters.
183 * @return string|bool The file path to where the attached file should be, false otherwise.
185 function get_attached_file( $attachment_id, $unfiltered = false ) {
186 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
187 // If the file is relative, prepend upload dir
188 if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
189 $file = $uploads['basedir'] . "/$file";
192 return apply_filters( 'get_attached_file', $file, $attachment_id );
196 * Update attachment file path based on attachment ID.
198 * Used to update the file path of the attachment, which uses post meta name
199 * '_wp_attached_file' to store the path of the attachment.
202 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
204 * @param int $attachment_id Attachment ID
205 * @param string $file File path for the attachment
206 * @return bool True on success, false on failure.
208 function update_attached_file( $attachment_id, $file ) {
209 if ( !get_post( $attachment_id ) )
212 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
213 if ( $file = _wp_relative_upload_path( $file ) )
214 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
216 return delete_post_meta( $attachment_id, '_wp_attached_file' );
220 * Return relative path to an uploaded file.
222 * The path is relative to the current upload dir.
225 * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
227 * @param string $path Full path to the file
228 * @return string relative path on success, unchanged path on failure.
230 function _wp_relative_upload_path( $path ) {
233 $uploads = wp_upload_dir();
234 if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
235 $new_path = str_replace( $uploads['basedir'], '', $new_path );
236 $new_path = ltrim( $new_path, '/' );
239 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
243 * Retrieve all children of the post parent ID.
245 * Normally, without any enhancements, the children would apply to pages. In the
246 * context of the inner workings of WordPress, pages, posts, and attachments
247 * share the same table, so therefore the functionality could apply to any one
248 * of them. It is then noted that while this function does not work on posts, it
249 * does not mean that it won't work on posts. It is recommended that you know
250 * what context you wish to retrieve the children of.
252 * Attachments may also be made the child of a post, so if that is an accurate
253 * statement (which needs to be verified), it would then be possible to get
254 * all of the attachments for a post. Attachments have since changed since
255 * version 2.5, so this is most likely unaccurate, but serves generally as an
256 * example of what is possible.
258 * The arguments listed as defaults are for this function and also of the
259 * {@link get_posts()} function. The arguments are combined with the
260 * get_children defaults and are then passed to the {@link get_posts()}
261 * function, which accepts additional arguments. You can replace the defaults in
262 * this function, listed below and the additional arguments listed in the
263 * {@link get_posts()} function.
265 * The 'post_parent' is the most important argument and important attention
266 * needs to be paid to the $args parameter. If you pass either an object or an
267 * integer (number), then just the 'post_parent' is grabbed and everything else
268 * is lost. If you don't specify any arguments, then it is assumed that you are
269 * in The Loop and the post parent will be grabbed for from the current post.
271 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
272 * is the amount of posts to retrieve that has a default of '-1', which is
273 * used to get all of the posts. Giving a number higher than 0 will only
274 * retrieve that amount of posts.
276 * The 'post_type' and 'post_status' arguments can be used to choose what
277 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
278 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
279 * argument will accept any post status within the write administration panels.
281 * @see get_posts() Has additional arguments that can be replaced.
282 * @internal Claims made in the long description might be inaccurate.
286 * @param mixed $args Optional. User defined arguments for replacing the defaults.
287 * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
288 * @return array|bool False on failure and the type will be determined by $output parameter.
290 function get_children($args = '', $output = OBJECT) {
292 if ( empty( $args ) ) {
293 if ( isset( $GLOBALS['post'] ) ) {
294 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
298 } elseif ( is_object( $args ) ) {
299 $args = array('post_parent' => (int) $args->post_parent );
300 } elseif ( is_numeric( $args ) ) {
301 $args = array('post_parent' => (int) $args);
305 'numberposts' => -1, 'post_type' => 'any',
306 'post_status' => 'any', 'post_parent' => 0,
309 $r = wp_parse_args( $args, $defaults );
311 $children = get_posts( $r );
316 if ( ! empty( $r['fields'] ) )
319 update_post_cache($children);
321 foreach ( $children as $key => $child )
322 $kids[$child->ID] = $children[$key];
324 if ( $output == OBJECT ) {
326 } elseif ( $output == ARRAY_A ) {
327 foreach ( (array) $kids as $kid )
328 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
330 } elseif ( $output == ARRAY_N ) {
331 foreach ( (array) $kids as $kid )
332 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
340 * Get extended entry info (<!--more-->).
342 * There should not be any space after the second dash and before the word
343 * 'more'. There can be text or space(s) after the word 'more', but won't be
346 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
347 * the <code><!--more--></code>. The 'extended' key has the content after the
348 * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text.
352 * @param string $post Post content.
353 * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text').
355 function get_extended($post) {
356 //Match the new style more links
357 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
358 list($main, $extended) = explode($matches[0], $post, 2);
359 $more_text = $matches[1];
366 // ` leading and trailing whitespace
367 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
368 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
369 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
371 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
375 * Retrieves post data given a post ID or post object.
377 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
378 * $post, must be given as a variable, since it is passed by reference.
381 * @link http://codex.wordpress.org/Function_Reference/get_post
383 * @param int|object $post Post ID or post object. Optional, default is the current post from the loop.
384 * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
385 * @param string $filter Optional, default is raw.
386 * @return WP_Post|null WP_Post on success or null on failure
388 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
389 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
390 $post = $GLOBALS['post'];
392 if ( is_a( $post, 'WP_Post' ) ) {
394 } elseif ( is_object( $post ) ) {
395 if ( empty( $post->filter ) ) {
396 $_post = sanitize_post( $post, 'raw' );
397 $_post = new WP_Post( $_post );
398 } elseif ( 'raw' == $post->filter ) {
399 $_post = new WP_Post( $post );
401 $_post = WP_Post::get_instance( $post->ID );
404 $_post = WP_Post::get_instance( $post );
410 $_post = $_post->filter( $filter );
412 if ( $output == ARRAY_A )
413 return $_post->to_array();
414 elseif ( $output == ARRAY_N )
415 return array_values( $_post->to_array() );
421 * WordPress Post class.
426 final class WP_Post {
438 * A numeric string, for compatibility reasons.
442 public $post_author = 0;
445 * The post's local publication time.
449 public $post_date = '0000-00-00 00:00:00';
452 * The post's GMT publication time.
456 public $post_date_gmt = '0000-00-00 00:00:00';
459 * The post's content.
463 public $post_content = '';
470 public $post_title = '';
473 * The post's excerpt.
477 public $post_excerpt = '';
484 public $post_status = 'publish';
487 * Whether comments are allowed.
491 public $comment_status = 'open';
494 * Whether pings are allowed.
498 public $ping_status = 'open';
501 * The post's password in plain text.
505 public $post_password = '';
512 public $post_name = '';
515 * URLs queued to be pinged.
519 public $to_ping = '';
522 * URLs that have been pinged.
529 * The post's local modified time.
533 public $post_modified = '0000-00-00 00:00:00';
536 * The post's GMT modified time.
540 public $post_modified_gmt = '0000-00-00 00:00:00';
543 * A utility DB field for post content.
548 public $post_content_filtered = '';
551 * ID of a post's parent post.
555 public $post_parent = 0;
558 * The unique identifier for a post, not necessarily a URL, used as the feed GUID.
565 * A field used for ordering posts.
569 public $menu_order = 0;
572 * The post's type, like post or page.
576 public $post_type = 'post';
579 * An attachment's mime type.
583 public $post_mime_type = '';
586 * Cached comment count.
588 * A numeric string, for compatibility reasons.
592 public $comment_count = 0;
595 * Stores the post object's sanitization level.
597 * Does not correspond to a DB field.
603 public static function get_instance( $post_id ) {
606 $post_id = (int) $post_id;
610 $_post = wp_cache_get( $post_id, 'posts' );
613 $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
618 $_post = sanitize_post( $_post, 'raw' );
619 wp_cache_add( $_post->ID, $_post, 'posts' );
620 } elseif ( empty( $_post->filter ) ) {
621 $_post = sanitize_post( $_post, 'raw' );
624 return new WP_Post( $_post );
627 public function __construct( $post ) {
628 foreach ( get_object_vars( $post ) as $key => $value )
629 $this->$key = $value;
632 public function __isset( $key ) {
633 if ( 'ancestors' == $key )
636 if ( 'page_template' == $key )
637 return ( 'page' == $this->post_type );
639 if ( 'post_category' == $key )
642 if ( 'tags_input' == $key )
645 return metadata_exists( 'post', $this->ID, $key );
648 public function __get( $key ) {
649 if ( 'page_template' == $key && $this->__isset( $key ) ) {
650 return get_post_meta( $this->ID, '_wp_page_template', true );
653 if ( 'post_category' == $key ) {
654 if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
655 $terms = get_the_terms( $this, 'category' );
657 if ( empty( $terms ) )
660 return wp_list_pluck( $terms, 'term_id' );
663 if ( 'tags_input' == $key ) {
664 if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
665 $terms = get_the_terms( $this, 'post_tag' );
667 if ( empty( $terms ) )
670 return wp_list_pluck( $terms, 'name' );
673 // Rest of the values need filtering
675 if ( 'ancestors' == $key )
676 $value = get_post_ancestors( $this );
678 $value = get_post_meta( $this->ID, $key, true );
681 $value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
686 public function filter( $filter ) {
687 if ( $this->filter == $filter )
690 if ( $filter == 'raw' )
691 return self::get_instance( $this->ID );
693 return sanitize_post( $this, $filter );
696 public function to_array() {
697 $post = get_object_vars( $this );
699 foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
700 if ( $this->__isset( $key ) )
701 $post[ $key ] = $this->__get( $key );
709 * Retrieve ancestors of a post.
713 * @param int|object $post Post ID or post object
714 * @return array Ancestor IDs or empty array if none are found.
716 function get_post_ancestors( $post ) {
717 $post = get_post( $post );
719 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
722 $ancestors = array();
724 $id = $ancestors[] = $post->post_parent;
726 while ( $ancestor = get_post( $id ) ) {
727 // Loop detection: If the ancestor has been seen before, break.
728 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
731 $id = $ancestors[] = $ancestor->post_parent;
738 * Retrieve data from a post field based on Post ID.
740 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
741 * etc and based off of the post object property or key names.
743 * The context values are based off of the taxonomy filter functions and
744 * supported values are found within those functions.
747 * @uses sanitize_post_field() See for possible $context values.
749 * @param string $field Post field name.
750 * @param int|object $post Post ID or post object.
751 * @param string $context Optional. How to filter the field. Default is 'display'.
752 * @return string The value of the post field on success, empty string on failure.
754 function get_post_field( $field, $post, $context = 'display' ) {
755 $post = get_post( $post );
760 if ( !isset($post->$field) )
763 return sanitize_post_field($field, $post->$field, $post->ID, $context);
767 * Retrieve the mime type of an attachment based on the ID.
769 * This function can be used with any post type, but it makes more sense with
774 * @param int $ID Optional. Post ID. Default is the current post from the loop.
775 * @return string|bool The mime type on success, false on failure.
777 function get_post_mime_type($ID = '') {
778 $post = get_post($ID);
780 if ( is_object($post) )
781 return $post->post_mime_type;
787 * Retrieve the post status based on the Post ID.
789 * If the post ID is of an attachment, then the parent post status will be given
794 * @param int $ID Optional. Post ID. Default is the current post from the loop.
795 * @return string|bool Post status on success, false on failure.
797 function get_post_status($ID = '') {
798 $post = get_post($ID);
800 if ( !is_object($post) )
803 if ( 'attachment' == $post->post_type ) {
804 if ( 'private' == $post->post_status )
807 // Unattached attachments are assumed to be published
808 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
811 // Inherit status from the parent
812 if ( $post->post_parent && ( $post->ID != $post->post_parent ) )
813 return get_post_status($post->post_parent);
816 return $post->post_status;
820 * Retrieve all of the WordPress supported post statuses.
822 * Posts have a limited set of valid status values, this provides the
823 * post_status values and descriptions.
827 * @return array List of post statuses.
829 function get_post_statuses() {
831 'draft' => __('Draft'),
832 'pending' => __('Pending Review'),
833 'private' => __('Private'),
834 'publish' => __('Published')
841 * Retrieve all of the WordPress support page statuses.
843 * Pages have a limited set of valid status values, this provides the
844 * post_status values and descriptions.
848 * @return array List of page statuses.
850 function get_page_statuses() {
852 'draft' => __('Draft'),
853 'private' => __('Private'),
854 'publish' => __('Published')
861 * Register a post status. Do not use before init.
863 * A simple function for creating or modifying a post status based on the
864 * parameters given. The function will accept an array (second optional
865 * parameter), along with a string for the post status name.
868 * Optional $args contents:
870 * label - A descriptive name for the post status marked for translation. Defaults to $post_status.
871 * public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
872 * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false.
873 * show_in_admin_all_list - Whether to include posts in the edit listing for their post type
874 * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
875 * listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
877 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
882 * @uses $wp_post_statuses Inserts new post status object into the list
884 * @param string $post_status Name of the post status.
885 * @param array|string $args See above description.
887 function register_post_status($post_status, $args = array()) {
888 global $wp_post_statuses;
890 if (!is_array($wp_post_statuses))
891 $wp_post_statuses = array();
893 // Args prefixed with an underscore are reserved for internal use.
896 'label_count' => false,
897 'exclude_from_search' => null,
903 'publicly_queryable' => null,
904 'show_in_admin_status_list' => null,
905 'show_in_admin_all_list' => null,
907 $args = wp_parse_args($args, $defaults);
908 $args = (object) $args;
910 $post_status = sanitize_key($post_status);
911 $args->name = $post_status;
913 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
914 $args->internal = true;
916 if ( null === $args->public )
917 $args->public = false;
919 if ( null === $args->private )
920 $args->private = false;
922 if ( null === $args->protected )
923 $args->protected = false;
925 if ( null === $args->internal )
926 $args->internal = false;
928 if ( null === $args->publicly_queryable )
929 $args->publicly_queryable = $args->public;
931 if ( null === $args->exclude_from_search )
932 $args->exclude_from_search = $args->internal;
934 if ( null === $args->show_in_admin_all_list )
935 $args->show_in_admin_all_list = !$args->internal;
937 if ( null === $args->show_in_admin_status_list )
938 $args->show_in_admin_status_list = !$args->internal;
940 if ( false === $args->label )
941 $args->label = $post_status;
943 if ( false === $args->label_count )
944 $args->label_count = array( $args->label, $args->label );
946 $wp_post_statuses[$post_status] = $args;
952 * Retrieve a post status object by name
957 * @uses $wp_post_statuses
958 * @see register_post_status
959 * @see get_post_statuses
961 * @param string $post_status The name of a registered post status
962 * @return object A post status object
964 function get_post_status_object( $post_status ) {
965 global $wp_post_statuses;
967 if ( empty($wp_post_statuses[$post_status]) )
970 return $wp_post_statuses[$post_status];
974 * Get a list of all registered post status objects.
979 * @uses $wp_post_statuses
980 * @see register_post_status
981 * @see get_post_status_object
983 * @param array|string $args An array of key => value arguments to match against the post status objects.
984 * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
985 * @param string $operator The logical operation to perform. 'or' means only one element
986 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
987 * @return array A list of post status names or objects
989 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
990 global $wp_post_statuses;
992 $field = ('names' == $output) ? 'name' : false;
994 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
998 * Whether the post type is hierarchical.
1000 * A false return value might also mean that the post type does not exist.
1003 * @see get_post_type_object
1005 * @param string $post_type Post type name
1006 * @return bool Whether post type is hierarchical.
1008 function is_post_type_hierarchical( $post_type ) {
1009 if ( ! post_type_exists( $post_type ) )
1012 $post_type = get_post_type_object( $post_type );
1013 return $post_type->hierarchical;
1017 * Checks if a post type is registered.
1020 * @uses get_post_type_object()
1022 * @param string $post_type Post type name
1023 * @return bool Whether post type is registered.
1025 function post_type_exists( $post_type ) {
1026 return (bool) get_post_type_object( $post_type );
1030 * Retrieve the post type of the current post or of a given post.
1034 * @param int|object $post Optional. Post ID or post object. Default is the current post from the loop.
1035 * @return string|bool Post type on success, false on failure.
1037 function get_post_type( $post = null ) {
1038 if ( $post = get_post( $post ) )
1039 return $post->post_type;
1045 * Retrieve a post type object by name
1047 * @package WordPress
1050 * @uses $wp_post_types
1051 * @see register_post_type
1052 * @see get_post_types
1054 * @param string $post_type The name of a registered post type
1055 * @return object A post type object
1057 function get_post_type_object( $post_type ) {
1058 global $wp_post_types;
1060 if ( empty($wp_post_types[$post_type]) )
1063 return $wp_post_types[$post_type];
1067 * Get a list of all registered post type objects.
1069 * @package WordPress
1072 * @uses $wp_post_types
1073 * @see register_post_type
1075 * @param array|string $args An array of key => value arguments to match against the post type objects.
1076 * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
1077 * @param string $operator The logical operation to perform. 'or' means only one element
1078 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
1079 * @return array A list of post type names or objects
1081 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
1082 global $wp_post_types;
1084 $field = ('names' == $output) ? 'name' : false;
1086 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
1090 * Register a post type. Do not use before init.
1092 * A function for creating or modifying a post type based on the
1093 * parameters given. The function will accept an array (second optional
1094 * parameter), along with a string for the post type name.
1096 * Optional $args contents:
1098 * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
1099 * - labels - An array of labels for this post type.
1100 * * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones.
1101 * * You can see accepted values in {@link get_post_type_labels()}.
1102 * - description - A short descriptive summary of what the post type is. Defaults to blank.
1103 * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users.
1104 * * Defaults to false.
1105 * * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are
1106 * inherited from public, each does not rely on this relationship and controls a very specific intention.
1107 * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false.
1108 * - exclude_from_search - Whether to exclude posts with this post type from front end search results.
1109 * * If not set, the opposite of public's current value is used.
1110 * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request().
1111 * * ?post_type={post_type_key}
1112 * * ?{post_type_key}={single_post_slug}
1113 * * ?{post_type_query_var}={single_post_slug}
1114 * * If not set, the default is inherited from public.
1115 * - show_ui - Whether to generate a default UI for managing this post type in the admin.
1116 * * If not set, the default is inherited from public.
1117 * - show_in_menu - Where to show the post type in the admin menu.
1118 * * If true, the post type is shown in its own top level menu.
1119 * * If false, no menu is shown
1120 * * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will
1121 * be placed as a sub menu of that.
1122 * * show_ui must be true.
1123 * * If not set, the default is inherited from show_ui
1124 * - show_in_nav_menus - Makes this post type available for selection in navigation menus.
1125 * * If not set, the default is inherited from public.
1126 * - show_in_admin_bar - Makes this post type available via the admin bar.
1127 * * If not set, the default is inherited from show_in_menu
1128 * - menu_position - The position in the menu order the post type should appear.
1129 * * show_in_menu must be true
1130 * * Defaults to null, which places it at the bottom of its area.
1131 * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
1132 * * Pass a base64-encoded SVG using a data URI, which will be colored to match the color scheme.
1133 * This should begin with 'data:image/svg+xml;base64,'.
1134 * * Pass the name of a Dashicons helper class to use a font icon, e.g. 'dashicons-piechart'.
1135 * * Pass 'none' to leave div.wp-menu-image empty so an icon can be added via CSS.
1136 * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
1137 * * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
1138 * capabilities, e.g. array('story', 'stories').
1139 * - capabilities - Array of capabilities for this post type.
1140 * * By default the capability_type is used as a base to construct capabilities.
1141 * * You can see accepted values in {@link get_post_type_capabilities()}.
1142 * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
1143 * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
1144 * * See {@link add_post_type_support()} for documentation.
1145 * - register_meta_box_cb - Provide a callback function that sets up the meta boxes
1146 * for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
1147 * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
1148 * * Default is no taxonomies.
1149 * * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
1150 * - has_archive - True to enable post type archives. Default is false.
1151 * * Will generate the proper rewrite rules if rewrite is enabled.
1152 * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
1153 * * To prevent rewrite, set to false.
1154 * * To specify rewrite rules, an array can be passed with any of these keys
1155 * * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
1156 * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
1157 * * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
1158 * * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
1159 * * 'ep_mask' => const Assign an endpoint mask.
1160 * * If not specified and permalink_epmask is set, inherits from permalink_epmask.
1161 * * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
1162 * - query_var - Sets the query_var key for this post type. Defaults to $post_type key
1163 * * If false, a post type cannot be loaded at ?{query_var}={post_slug}
1164 * * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
1165 * - can_export - Allows this post type to be exported. Defaults to true.
1166 * - delete_with_user - Whether to delete posts of this type when deleting a user.
1167 * * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
1168 * * If false, posts of this type belonging to the user will *not* be trashed or deleted.
1169 * * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
1170 * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
1171 * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
1174 * @uses $wp_post_types Inserts new post type object into the list
1175 * @uses $wp_rewrite Gets default feeds
1176 * @uses $wp Adds query vars
1178 * @param string $post_type Post type key, must not exceed 20 characters.
1179 * @param array|string $args See optional args description above.
1180 * @return object|WP_Error the registered post type object, or an error object.
1182 function register_post_type( $post_type, $args = array() ) {
1183 global $wp_post_types, $wp_rewrite, $wp;
1185 if ( ! is_array( $wp_post_types ) )
1186 $wp_post_types = array();
1188 // Args prefixed with an underscore are reserved for internal use.
1190 'labels' => array(),
1191 'description' => '',
1193 'hierarchical' => false,
1194 'exclude_from_search' => null,
1195 'publicly_queryable' => null,
1197 'show_in_menu' => null,
1198 'show_in_nav_menus' => null,
1199 'show_in_admin_bar' => null,
1200 'menu_position' => null,
1201 'menu_icon' => null,
1202 'capability_type' => 'post',
1203 'capabilities' => array(),
1204 'map_meta_cap' => null,
1205 'supports' => array(),
1206 'register_meta_box_cb' => null,
1207 'taxonomies' => array(),
1208 'has_archive' => false,
1210 'query_var' => true,
1211 'can_export' => true,
1212 'delete_with_user' => null,
1213 '_builtin' => false,
1214 '_edit_link' => 'post.php?post=%d',
1216 $args = wp_parse_args( $args, $defaults );
1217 $args = (object) $args;
1219 $post_type = sanitize_key( $post_type );
1220 $args->name = $post_type;
1222 if ( strlen( $post_type ) > 20 )
1223 return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
1225 // If not set, default to the setting for public.
1226 if ( null === $args->publicly_queryable )
1227 $args->publicly_queryable = $args->public;
1229 // If not set, default to the setting for public.
1230 if ( null === $args->show_ui )
1231 $args->show_ui = $args->public;
1233 // If not set, default to the setting for show_ui.
1234 if ( null === $args->show_in_menu || ! $args->show_ui )
1235 $args->show_in_menu = $args->show_ui;
1237 // If not set, default to the whether the full UI is shown.
1238 if ( null === $args->show_in_admin_bar )
1239 $args->show_in_admin_bar = true === $args->show_in_menu;
1241 // If not set, default to the setting for public.
1242 if ( null === $args->show_in_nav_menus )
1243 $args->show_in_nav_menus = $args->public;
1245 // If not set, default to true if not public, false if public.
1246 if ( null === $args->exclude_from_search )
1247 $args->exclude_from_search = !$args->public;
1249 // Back compat with quirky handling in version 3.0. #14122
1250 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1251 $args->map_meta_cap = true;
1253 // If not set, default to false.
1254 if ( null === $args->map_meta_cap )
1255 $args->map_meta_cap = false;
1257 $args->cap = get_post_type_capabilities( $args );
1258 unset( $args->capabilities );
1260 if ( is_array( $args->capability_type ) )
1261 $args->capability_type = $args->capability_type[0];
1263 if ( ! empty( $args->supports ) ) {
1264 add_post_type_support( $post_type, $args->supports );
1265 unset( $args->supports );
1266 } elseif ( false !== $args->supports ) {
1267 // Add default features
1268 add_post_type_support( $post_type, array( 'title', 'editor' ) );
1271 if ( false !== $args->query_var && ! empty( $wp ) ) {
1272 if ( true === $args->query_var )
1273 $args->query_var = $post_type;
1275 $args->query_var = sanitize_title_with_dashes( $args->query_var );
1276 $wp->add_query_var( $args->query_var );
1279 if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
1280 if ( ! is_array( $args->rewrite ) )
1281 $args->rewrite = array();
1282 if ( empty( $args->rewrite['slug'] ) )
1283 $args->rewrite['slug'] = $post_type;
1284 if ( ! isset( $args->rewrite['with_front'] ) )
1285 $args->rewrite['with_front'] = true;
1286 if ( ! isset( $args->rewrite['pages'] ) )
1287 $args->rewrite['pages'] = true;
1288 if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1289 $args->rewrite['feeds'] = (bool) $args->has_archive;
1290 if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1291 if ( isset( $args->permalink_epmask ) )
1292 $args->rewrite['ep_mask'] = $args->permalink_epmask;
1294 $args->rewrite['ep_mask'] = EP_PERMALINK;
1297 if ( $args->hierarchical )
1298 add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
1300 add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
1302 if ( $args->has_archive ) {
1303 $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1304 if ( $args->rewrite['with_front'] )
1305 $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1307 $archive_slug = $wp_rewrite->root . $archive_slug;
1309 add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1310 if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1311 $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1312 add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1313 add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1315 if ( $args->rewrite['pages'] )
1316 add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1319 $permastruct_args = $args->rewrite;
1320 $permastruct_args['feed'] = $permastruct_args['feeds'];
1321 add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
1324 if ( $args->register_meta_box_cb )
1325 add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
1327 $args->labels = get_post_type_labels( $args );
1328 $args->label = $args->labels->name;
1330 $wp_post_types[ $post_type ] = $args;
1332 add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1334 foreach ( $args->taxonomies as $taxonomy ) {
1335 register_taxonomy_for_object_type( $taxonomy, $post_type );
1338 do_action( 'registered_post_type', $post_type, $args );
1344 * Builds an object with all post type capabilities out of a post type object
1346 * Post type capabilities use the 'capability_type' argument as a base, if the
1347 * capability is not set in the 'capabilities' argument array or if the
1348 * 'capabilities' argument is not supplied.
1350 * The capability_type argument can optionally be registered as an array, with
1351 * the first value being singular and the second plural, e.g. array('story, 'stories')
1352 * Otherwise, an 's' will be added to the value for the plural form. After
1353 * registration, capability_type will always be a string of the singular value.
1355 * By default, seven keys are accepted as part of the capabilities array:
1357 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1358 * generally mapped to corresponding primitive capabilities depending on the
1359 * context, which would be the post being edited/read/deleted and the user or
1360 * role being checked. Thus these capabilities would generally not be granted
1361 * directly to users or roles.
1363 * - edit_posts - Controls whether objects of this post type can be edited.
1364 * - edit_others_posts - Controls whether objects of this type owned by other users
1365 * can be edited. If the post type does not support an author, then this will
1366 * behave like edit_posts.
1367 * - publish_posts - Controls publishing objects of this post type.
1368 * - read_private_posts - Controls whether private objects can be read.
1370 * These four primitive capabilities are checked in core in various locations.
1371 * There are also seven other primitive capabilities which are not referenced
1372 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1373 * meta capabilities and translates them into one or more primitive capabilities
1374 * that must then be checked against the user or role, depending on the context.
1376 * - read - Controls whether objects of this post type can be read.
1377 * - delete_posts - Controls whether objects of this post type can be deleted.
1378 * - delete_private_posts - Controls whether private objects can be deleted.
1379 * - delete_published_posts - Controls whether published objects can be deleted.
1380 * - delete_others_posts - Controls whether objects owned by other users can be
1381 * can be deleted. If the post type does not support an author, then this will
1382 * behave like delete_posts.
1383 * - edit_private_posts - Controls whether private objects can be edited.
1384 * - edit_published_posts - Controls whether published objects can be edited.
1386 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1387 * only assigned by default if the post type is registered with the 'map_meta_cap'
1388 * argument set to true (default is false).
1390 * @see map_meta_cap()
1393 * @param object $args Post type registration arguments
1394 * @return object object with all the capabilities as member variables
1396 function get_post_type_capabilities( $args ) {
1397 if ( ! is_array( $args->capability_type ) )
1398 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1400 // Singular base for meta capabilities, plural base for primitive capabilities.
1401 list( $singular_base, $plural_base ) = $args->capability_type;
1403 $default_capabilities = array(
1404 // Meta capabilities
1405 'edit_post' => 'edit_' . $singular_base,
1406 'read_post' => 'read_' . $singular_base,
1407 'delete_post' => 'delete_' . $singular_base,
1408 // Primitive capabilities used outside of map_meta_cap():
1409 'edit_posts' => 'edit_' . $plural_base,
1410 'edit_others_posts' => 'edit_others_' . $plural_base,
1411 'publish_posts' => 'publish_' . $plural_base,
1412 'read_private_posts' => 'read_private_' . $plural_base,
1415 // Primitive capabilities used within map_meta_cap():
1416 if ( $args->map_meta_cap ) {
1417 $default_capabilities_for_mapping = array(
1419 'delete_posts' => 'delete_' . $plural_base,
1420 'delete_private_posts' => 'delete_private_' . $plural_base,
1421 'delete_published_posts' => 'delete_published_' . $plural_base,
1422 'delete_others_posts' => 'delete_others_' . $plural_base,
1423 'edit_private_posts' => 'edit_private_' . $plural_base,
1424 'edit_published_posts' => 'edit_published_' . $plural_base,
1426 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1429 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1431 // Post creation capability simply maps to edit_posts by default:
1432 if ( ! isset( $capabilities['create_posts'] ) )
1433 $capabilities['create_posts'] = $capabilities['edit_posts'];
1435 // Remember meta capabilities for future reference.
1436 if ( $args->map_meta_cap )
1437 _post_type_meta_capabilities( $capabilities );
1439 return (object) $capabilities;
1443 * Stores or returns a list of post type meta caps for map_meta_cap().
1448 function _post_type_meta_capabilities( $capabilities = null ) {
1449 static $meta_caps = array();
1450 if ( null === $capabilities )
1452 foreach ( $capabilities as $core => $custom ) {
1453 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1454 $meta_caps[ $custom ] = $core;
1459 * Builds an object with all post type labels out of a post type object
1461 * Accepted keys of the label array in the post type object:
1462 * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
1463 * - singular_name - name for one object of this post type. Default is Post/Page
1464 * - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code>
1465 * - add_new_item - Default is Add New Post/Add New Page
1466 * - edit_item - Default is Edit Post/Edit Page
1467 * - new_item - Default is New Post/New Page
1468 * - view_item - Default is View Post/View Page
1469 * - search_items - Default is Search Posts/Search Pages
1470 * - not_found - Default is No posts found/No pages found
1471 * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
1472 * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
1473 * - all_items - String for the submenu. Default is All Posts/All Pages
1474 * - menu_name - Default is the same as <code>name</code>
1476 * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
1481 * @param object $post_type_object
1482 * @return object object with all the labels as member variables
1484 function get_post_type_labels( $post_type_object ) {
1485 $nohier_vs_hier_defaults = array(
1486 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1487 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1488 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1489 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1490 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1491 'new_item' => array( __('New Post'), __('New Page') ),
1492 'view_item' => array( __('View Post'), __('View Page') ),
1493 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1494 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1495 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1496 'parent_item_colon' => array( null, __('Parent Page:') ),
1497 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
1499 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1501 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1503 $post_type = $post_type_object->name;
1504 return apply_filters( "post_type_labels_{$post_type}", $labels );
1508 * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
1513 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1514 $object->labels = (array) $object->labels;
1516 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1517 $object->labels['name'] = $object->label;
1519 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1520 $object->labels['singular_name'] = $object->labels['name'];
1522 if ( ! isset( $object->labels['name_admin_bar'] ) )
1523 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1525 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1526 $object->labels['menu_name'] = $object->labels['name'];
1528 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1529 $object->labels['all_items'] = $object->labels['menu_name'];
1531 foreach ( $nohier_vs_hier_defaults as $key => $value )
1532 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1534 $labels = array_merge( $defaults, $object->labels );
1535 return (object)$labels;
1539 * Adds submenus for post types.
1544 function _add_post_type_submenus() {
1545 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1546 $ptype_obj = get_post_type_object( $ptype );
1548 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1550 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" );
1553 add_action( 'admin_menu', '_add_post_type_submenus' );
1556 * Register support of certain features for a post type.
1558 * All features are directly associated with a functional area of the edit screen, such as the
1559 * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
1560 * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
1562 * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
1563 * and the 'comments' feature dictates whether the comments count will show on the edit screen.
1566 * @param string $post_type The post type for which to add the feature
1567 * @param string|array $feature the feature being added, can be an array of feature strings or a single string
1569 function add_post_type_support( $post_type, $feature ) {
1570 global $_wp_post_type_features;
1572 $features = (array) $feature;
1573 foreach ($features as $feature) {
1574 if ( func_num_args() == 2 )
1575 $_wp_post_type_features[$post_type][$feature] = true;
1577 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1582 * Remove support for a feature from a post type.
1585 * @param string $post_type The post type for which to remove the feature
1586 * @param string $feature The feature being removed
1588 function remove_post_type_support( $post_type, $feature ) {
1589 global $_wp_post_type_features;
1591 if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
1592 unset( $_wp_post_type_features[$post_type][$feature] );
1596 * Get all the post type features
1599 * @param string $post_type The post type
1603 function get_all_post_type_supports( $post_type ) {
1604 global $_wp_post_type_features;
1606 if ( isset( $_wp_post_type_features[$post_type] ) )
1607 return $_wp_post_type_features[$post_type];
1613 * Checks a post type's support for a given feature
1616 * @param string $post_type The post type being checked
1617 * @param string $feature the feature being checked
1621 function post_type_supports( $post_type, $feature ) {
1622 global $_wp_post_type_features;
1624 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1628 * Updates the post type for the post ID.
1630 * The page or post cache will be cleaned for the post ID.
1636 * @param int $post_id Post ID to change post type. Not actually optional.
1637 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
1639 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
1641 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1644 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1645 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1647 clean_post_cache( $post_id );
1653 * Retrieve list of latest posts or posts matching criteria.
1655 * The defaults are as follows:
1656 * 'numberposts' - Default is 5. Total number of posts to retrieve.
1657 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
1658 * 'category' - What category to pull the posts from.
1659 * 'orderby' - Default is 'date', which orders based on post_date. How to order the posts.
1660 * 'order' - Default is 'DESC'. The order to retrieve the posts.
1661 * 'include' - See {@link WP_Query::query()} for more.
1662 * 'exclude' - See {@link WP_Query::query()} for more.
1663 * 'meta_key' - See {@link WP_Query::query()} for more.
1664 * 'meta_value' - See {@link WP_Query::query()} for more.
1665 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
1666 * 'post_parent' - The parent of the post or post type.
1667 * 'post_status' - Default is 'publish'. Post status to retrieve.
1670 * @uses WP_Query::query() See for more default arguments and information.
1671 * @link http://codex.wordpress.org/Template_Tags/get_posts
1673 * @param array $args Optional. Overrides defaults.
1674 * @return array List of posts.
1676 function get_posts($args = null) {
1678 'numberposts' => 5, 'offset' => 0,
1679 'category' => 0, 'orderby' => 'date',
1680 'order' => 'DESC', 'include' => array(),
1681 'exclude' => array(), 'meta_key' => '',
1682 'meta_value' =>'', 'post_type' => 'post',
1683 'suppress_filters' => true
1686 $r = wp_parse_args( $args, $defaults );
1687 if ( empty( $r['post_status'] ) )
1688 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1689 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1690 $r['posts_per_page'] = $r['numberposts'];
1691 if ( ! empty($r['category']) )
1692 $r['cat'] = $r['category'];
1693 if ( ! empty($r['include']) ) {
1694 $incposts = wp_parse_id_list( $r['include'] );
1695 $r['posts_per_page'] = count($incposts); // only the number of posts included
1696 $r['post__in'] = $incposts;
1697 } elseif ( ! empty($r['exclude']) )
1698 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1700 $r['ignore_sticky_posts'] = true;
1701 $r['no_found_rows'] = true;
1703 $get_posts = new WP_Query;
1704 return $get_posts->query($r);
1709 // Post meta functions
1713 * Add meta data field to a post.
1715 * Post meta data is called "Custom Fields" on the Administration Screen.
1718 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
1720 * @param int $post_id Post ID.
1721 * @param string $meta_key Metadata name.
1722 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1723 * @param bool $unique Optional, default is false. Whether the same key should not be added.
1724 * @return int|bool Meta ID on success, false on failure.
1726 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
1727 // make sure meta is added to the post, not a revision
1728 if ( $the_post = wp_is_post_revision($post_id) )
1729 $post_id = $the_post;
1731 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1735 * Remove metadata matching criteria from a post.
1737 * You can match based on the key, or key and value. Removing based on key and
1738 * value, will keep from removing duplicate metadata with the same key. It also
1739 * allows removing all metadata matching key, if needed.
1742 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
1744 * @param int $post_id post ID
1745 * @param string $meta_key Metadata name.
1746 * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar.
1747 * @return bool True on success, false on failure.
1749 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
1750 // make sure meta is added to the post, not a revision
1751 if ( $the_post = wp_is_post_revision($post_id) )
1752 $post_id = $the_post;
1754 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1758 * Retrieve post meta field for a post.
1761 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
1763 * @param int $post_id Post ID.
1764 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1765 * @param bool $single Whether to return a single value.
1766 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1769 function get_post_meta($post_id, $key = '', $single = false) {
1770 return get_metadata('post', $post_id, $key, $single);
1774 * Update post meta field based on post ID.
1776 * Use the $prev_value parameter to differentiate between meta fields with the
1777 * same key and post ID.
1779 * If the meta field for the post does not exist, it will be added.
1782 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
1784 * @param int $post_id Post ID.
1785 * @param string $meta_key Metadata key.
1786 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1787 * @param mixed $prev_value Optional. Previous value to check before removing.
1788 * @return bool True on success, false on failure.
1790 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
1791 // make sure meta is added to the post, not a revision
1792 if ( $the_post = wp_is_post_revision($post_id) )
1793 $post_id = $the_post;
1795 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1799 * Delete everything from post meta matching meta key.
1803 * @param string $post_meta_key Key to search for when deleting.
1804 * @return bool Whether the post meta key was deleted from the database
1806 function delete_post_meta_by_key($post_meta_key) {
1807 return delete_metadata( 'post', null, $post_meta_key, '', true );
1811 * Retrieve post meta fields, based on post ID.
1813 * The post meta fields are retrieved from the cache where possible,
1814 * so the function is optimized to be called more than once.
1817 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
1819 * @param int $post_id Post ID.
1822 function get_post_custom( $post_id = 0 ) {
1823 $post_id = absint( $post_id );
1825 $post_id = get_the_ID();
1827 return get_post_meta( $post_id );
1831 * Retrieve meta field names for a post.
1833 * If there are no meta fields, then nothing (null) will be returned.
1836 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
1838 * @param int $post_id post ID
1839 * @return array|null Either array of the keys, or null if keys could not be retrieved.
1841 function get_post_custom_keys( $post_id = 0 ) {
1842 $custom = get_post_custom( $post_id );
1844 if ( !is_array($custom) )
1847 if ( $keys = array_keys($custom) )
1852 * Retrieve values for a custom post field.
1854 * The parameters must not be considered optional. All of the post meta fields
1855 * will be retrieved and only the meta field key values returned.
1858 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
1860 * @param string $key Meta field key.
1861 * @param int $post_id Post ID
1862 * @return array Meta field values.
1864 function get_post_custom_values( $key = '', $post_id = 0 ) {
1868 $custom = get_post_custom($post_id);
1870 return isset($custom[$key]) ? $custom[$key] : null;
1874 * Check if post is sticky.
1876 * Sticky posts should remain at the top of The Loop. If the post ID is not
1877 * given, then The Loop ID for the current post will be used.
1881 * @param int $post_id Optional. Post ID.
1882 * @return bool Whether post is sticky.
1884 function is_sticky( $post_id = 0 ) {
1885 $post_id = absint( $post_id );
1888 $post_id = get_the_ID();
1890 $stickies = get_option( 'sticky_posts' );
1892 if ( ! is_array( $stickies ) )
1895 if ( in_array( $post_id, $stickies ) )
1902 * Sanitize every post field.
1904 * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
1907 * @uses sanitize_post_field() Used to sanitize the fields.
1909 * @param object|WP_Post|array $post The Post Object or Array
1910 * @param string $context Optional, default is 'display'. How to sanitize post fields.
1911 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post)
1913 function sanitize_post($post, $context = 'display') {
1914 if ( is_object($post) ) {
1915 // Check if post already filtered for this context
1916 if ( isset($post->filter) && $context == $post->filter )
1918 if ( !isset($post->ID) )
1920 foreach ( array_keys(get_object_vars($post)) as $field )
1921 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1922 $post->filter = $context;
1924 // Check if post already filtered for this context
1925 if ( isset($post['filter']) && $context == $post['filter'] )
1927 if ( !isset($post['ID']) )
1929 foreach ( array_keys($post) as $field )
1930 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1931 $post['filter'] = $context;
1937 * Sanitize post field based on context.
1939 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1940 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1941 * when calling filters.
1944 * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
1945 * $post_id if $context == 'edit' and field name prefix == 'post_'.
1947 * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
1948 * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
1949 * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
1951 * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
1952 * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
1953 * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
1954 * 'edit' and 'db' and field name prefix != 'post_'.
1956 * @param string $field The Post Object field name.
1957 * @param mixed $value The Post Object value.
1958 * @param int $post_id Post ID.
1959 * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
1960 * 'attribute' and 'js'.
1961 * @return mixed Sanitized value.
1963 function sanitize_post_field($field, $value, $post_id, $context) {
1964 $int_fields = array('ID', 'post_parent', 'menu_order');
1965 if ( in_array($field, $int_fields) )
1966 $value = (int) $value;
1968 // Fields which contain arrays of ints.
1969 $array_int_fields = array( 'ancestors' );
1970 if ( in_array($field, $array_int_fields) ) {
1971 $value = array_map( 'absint', $value);
1975 if ( 'raw' == $context )
1979 if ( false !== strpos($field, 'post_') ) {
1981 $field_no_prefix = str_replace('post_', '', $field);
1984 if ( 'edit' == $context ) {
1985 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1988 $value = apply_filters("edit_{$field}", $value, $post_id);
1990 $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
1992 $value = apply_filters("edit_post_{$field}", $value, $post_id);
1995 if ( in_array($field, $format_to_edit) ) {
1996 if ( 'post_content' == $field )
1997 $value = format_to_edit($value, user_can_richedit());
1999 $value = format_to_edit($value);
2001 $value = esc_attr($value);
2003 } else if ( 'db' == $context ) {
2005 $value = apply_filters("pre_{$field}", $value);
2006 $value = apply_filters("{$field_no_prefix}_save_pre", $value);
2008 $value = apply_filters("pre_post_{$field}", $value);
2009 $value = apply_filters("{$field}_pre", $value);
2012 // Use display filters by default.
2014 $value = apply_filters($field, $value, $post_id, $context);
2016 $value = apply_filters("post_{$field}", $value, $post_id, $context);
2019 if ( 'attribute' == $context )
2020 $value = esc_attr($value);
2021 else if ( 'js' == $context )
2022 $value = esc_js($value);
2028 * Make a post sticky.
2030 * Sticky posts should be displayed at the top of the front page.
2034 * @param int $post_id Post ID.
2036 function stick_post($post_id) {
2037 $stickies = get_option('sticky_posts');
2039 if ( !is_array($stickies) )
2040 $stickies = array($post_id);
2042 if ( ! in_array($post_id, $stickies) )
2043 $stickies[] = $post_id;
2045 update_option('sticky_posts', $stickies);
2051 * Sticky posts should be displayed at the top of the front page.
2055 * @param int $post_id Post ID.
2057 function unstick_post($post_id) {
2058 $stickies = get_option('sticky_posts');
2060 if ( !is_array($stickies) )
2063 if ( ! in_array($post_id, $stickies) )
2066 $offset = array_search($post_id, $stickies);
2067 if ( false === $offset )
2070 array_splice($stickies, $offset, 1);
2072 update_option('sticky_posts', $stickies);
2076 * Count number of posts of a post type and if user has permissions to view.
2078 * This function provides an efficient method of finding the amount of post's
2079 * type a blog has. Another method is to count the amount of items in
2080 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2081 * when developing for 2.5+, use this function instead.
2083 * The $perm parameter checks for 'readable' value and if the user can read
2084 * private posts, it will display that for the user that is signed in.
2086 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
2090 * @param string $type Optional. Post type to retrieve count
2091 * @param string $perm Optional. 'readable' or empty.
2092 * @return object Number of posts for each status
2094 function wp_count_posts( $type = 'post', $perm = '' ) {
2097 if ( ! post_type_exists( $type ) )
2098 return new stdClass;
2100 $user = wp_get_current_user();
2102 $cache_key = 'posts-' . $type;
2104 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2105 if ( 'readable' == $perm && is_user_logged_in() ) {
2106 $post_type_object = get_post_type_object($type);
2107 if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
2108 $cache_key .= '_' . $perm . '_' . $user->ID;
2109 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
2112 $query .= ' GROUP BY post_status';
2114 $counts = wp_cache_get( $cache_key, 'counts' );
2115 if ( false === $counts ) {
2116 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2117 $counts = array_fill_keys( get_post_stati(), 0 );
2119 foreach ( $results as $row )
2120 $counts[ $row['post_status'] ] = $row['num_posts'];
2122 $counts = (object) $counts;
2123 wp_cache_set( $cache_key, $counts, 'counts' );
2127 * Modify returned post counts by status for the current post type.
2131 * @param object $counts An object containing the current post_type's post counts by status.
2132 * @param string $type The post type.
2133 * @param string $perm The permission to determine if the posts are 'readable' by the current user.
2135 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2139 * Count number of attachments for the mime type(s).
2141 * If you set the optional mime_type parameter, then an array will still be
2142 * returned, but will only have the item you are looking for. It does not give
2143 * you the number of attachments that are children of a post. You can get that
2144 * by counting the number of children that post has.
2148 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
2149 * @return array Number of posts for each mime type.
2151 function wp_count_attachments( $mime_type = '' ) {
2154 $and = wp_post_mime_type_where( $mime_type );
2155 $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 );
2158 foreach( (array) $count as $row ) {
2159 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2161 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2164 * Modify returned attachment counts by mime type.
2168 * @param object $counts An object containing the attachment counts by mime type.
2169 * @param string $mime_type The mime type pattern used to filter the attachments counted.
2171 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2175 * Get default post mime types
2181 function get_post_mime_types() {
2182 $post_mime_types = array( // array( adj, noun )
2183 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2184 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2185 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2188 return apply_filters('post_mime_types', $post_mime_types);
2192 * Check a MIME-Type against a list.
2194 * If the wildcard_mime_types parameter is a string, it must be comma separated
2195 * list. If the real_mime_types is a string, it is also comma separated to
2200 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
2201 * flash (same as *flash*).
2202 * @param string|array $real_mime_types post_mime_type values
2203 * @return array array(wildcard=>array(real types))
2205 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
2207 if ( is_string($wildcard_mime_types) )
2208 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
2209 if ( is_string($real_mime_types) )
2210 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
2211 $wild = '[-._a-z0-9]*';
2212 foreach ( (array) $wildcard_mime_types as $type ) {
2213 $type = str_replace('*', $wild, $type);
2214 $patternses[1][$type] = "^$type$";
2215 if ( false === strpos($type, '/') ) {
2216 $patternses[2][$type] = "^$type/";
2217 $patternses[3][$type] = $type;
2221 foreach ( $patternses as $patterns )
2222 foreach ( $patterns as $type => $pattern )
2223 foreach ( (array) $real_mime_types as $real )
2224 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
2225 $matches[$type][] = $real;
2230 * Convert MIME types into SQL.
2234 * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
2235 * @param string $table_alias Optional. Specify a table alias, if needed.
2236 * @return string The SQL AND clause for mime searching.
2238 function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
2240 $wildcards = array('', '%', '%/%');
2241 if ( is_string($post_mime_types) )
2242 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2243 foreach ( (array) $post_mime_types as $mime_type ) {
2244 $mime_type = preg_replace('/\s/', '', $mime_type);
2245 $slashpos = strpos($mime_type, '/');
2246 if ( false !== $slashpos ) {
2247 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2248 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2249 if ( empty($mime_subgroup) )
2250 $mime_subgroup = '*';
2252 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2253 $mime_pattern = "$mime_group/$mime_subgroup";
2255 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2256 if ( false === strpos($mime_pattern, '*') )
2257 $mime_pattern .= '/*';
2260 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2262 if ( in_array( $mime_type, $wildcards ) )
2265 if ( false !== strpos($mime_pattern, '%') )
2266 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2268 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2270 if ( !empty($wheres) )
2271 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2276 * Trashes or deletes a post or page.
2278 * When the post and page is permanently deleted, everything that is tied to it is deleted also.
2279 * This includes comments, post meta fields, and terms associated with the post.
2281 * The post or page is moved to trash instead of permanently deleted unless trash is
2282 * disabled, item is already in the trash, or $force_delete is true.
2285 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
2286 * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
2287 * @uses wp_delete_attachment() if post type is 'attachment'.
2288 * @uses wp_trash_post() if item should be trashed.
2290 * @param int $postid Post ID.
2291 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
2292 * @return mixed False on failure
2294 function wp_delete_post( $postid = 0, $force_delete = false ) {
2297 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2300 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2301 return wp_trash_post($postid);
2303 if ( $post->post_type == 'attachment' )
2304 return wp_delete_attachment( $postid, $force_delete );
2306 do_action('before_delete_post', $postid);
2308 delete_post_meta($postid,'_wp_trash_meta_status');
2309 delete_post_meta($postid,'_wp_trash_meta_time');
2311 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2313 $parent_data = array( 'post_parent' => $post->post_parent );
2314 $parent_where = array( 'post_parent' => $postid );
2316 if ( is_post_type_hierarchical( $post->post_type ) ) {
2317 // Point children of this page to its parent, also clean the cache of affected children
2318 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2319 $children = $wpdb->get_results( $children_query );
2321 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2324 // Do raw query. wp_get_post_revisions() is filtered
2325 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2326 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2327 foreach ( $revision_ids as $revision_id )
2328 wp_delete_post_revision( $revision_id );
2330 // Point all attachments to this post up one level
2331 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2333 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2334 foreach ( $comment_ids as $comment_id )
2335 wp_delete_comment( $comment_id, true );
2337 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2338 foreach ( $post_meta_ids as $mid )
2339 delete_metadata_by_mid( 'post', $mid );
2341 do_action( 'delete_post', $postid );
2342 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2346 do_action( 'deleted_post', $postid );
2348 clean_post_cache( $post );
2350 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2351 foreach ( $children as $child )
2352 clean_post_cache( $child );
2355 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2357 do_action('after_delete_post', $postid);
2363 * Resets the page_on_front, show_on_front, and page_for_post settings when a
2364 * linked page is deleted or trashed.
2366 * Also ensures the post is no longer sticky.
2372 function _reset_front_page_settings_for_post( $post_id ) {
2373 $post = get_post( $post_id );
2374 if ( 'page' == $post->post_type ) {
2375 // If the page is defined in option page_on_front or post_for_posts,
2376 // adjust the corresponding options
2377 if ( get_option( 'page_on_front' ) == $post->ID ) {
2378 update_option( 'show_on_front', 'posts' );
2379 update_option( 'page_on_front', 0 );
2381 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2382 delete_option( 'page_for_posts', 0 );
2385 unstick_post( $post->ID );
2387 add_action( 'before_delete_post', '_reset_front_page_settings_for_post' );
2388 add_action( 'wp_trash_post', '_reset_front_page_settings_for_post' );
2391 * Moves a post or page to the Trash
2393 * If trash is disabled, the post or page is permanently deleted.
2396 * @uses do_action() on 'trash_post' before trashing
2397 * @uses do_action() on 'trashed_post' after trashing
2398 * @uses wp_delete_post() if trash is disabled
2400 * @param int $post_id Post ID.
2401 * @return mixed False on failure
2403 function wp_trash_post($post_id = 0) {
2404 if ( !EMPTY_TRASH_DAYS )
2405 return wp_delete_post($post_id, true);
2407 if ( !$post = get_post($post_id, ARRAY_A) )
2410 if ( $post['post_status'] == 'trash' )
2413 do_action('wp_trash_post', $post_id);
2415 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2416 add_post_meta($post_id,'_wp_trash_meta_time', time());
2418 $post['post_status'] = 'trash';
2419 wp_insert_post($post);
2421 wp_trash_post_comments($post_id);
2423 do_action('trashed_post', $post_id);
2429 * Restores a post or page from the Trash
2432 * @uses do_action() on 'untrash_post' before undeletion
2433 * @uses do_action() on 'untrashed_post' after undeletion
2435 * @param int $post_id Post ID.
2436 * @return mixed False on failure
2438 function wp_untrash_post($post_id = 0) {
2439 if ( !$post = get_post($post_id, ARRAY_A) )
2442 if ( $post['post_status'] != 'trash' )
2445 do_action('untrash_post', $post_id);
2447 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2449 $post['post_status'] = $post_status;
2451 delete_post_meta($post_id, '_wp_trash_meta_status');
2452 delete_post_meta($post_id, '_wp_trash_meta_time');
2454 wp_insert_post($post);
2456 wp_untrash_post_comments($post_id);
2458 do_action('untrashed_post', $post_id);
2464 * Moves comments for a post to the trash
2467 * @uses do_action() on 'trash_post_comments' before trashing
2468 * @uses do_action() on 'trashed_post_comments' after trashing
2470 * @param int|object $post Post ID or object.
2471 * @return mixed False on failure
2473 function wp_trash_post_comments($post = null) {
2476 $post = get_post($post);
2480 $post_id = $post->ID;
2482 do_action('trash_post_comments', $post_id);
2484 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2485 if ( empty($comments) )
2488 // Cache current status for each comment
2489 $statuses = array();
2490 foreach ( $comments as $comment )
2491 $statuses[$comment->comment_ID] = $comment->comment_approved;
2492 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2494 // Set status for all comments to post-trashed
2495 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2497 clean_comment_cache( array_keys($statuses) );
2499 do_action('trashed_post_comments', $post_id, $statuses);
2505 * Restore comments for a post from the trash
2508 * @uses do_action() on 'untrash_post_comments' before trashing
2509 * @uses do_action() on 'untrashed_post_comments' after trashing
2511 * @param int|object $post Post ID or object.
2512 * @return mixed False on failure
2514 function wp_untrash_post_comments($post = null) {
2517 $post = get_post($post);
2521 $post_id = $post->ID;
2523 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2525 if ( empty($statuses) )
2528 do_action('untrash_post_comments', $post_id);
2530 // Restore each comment to its original status
2531 $group_by_status = array();
2532 foreach ( $statuses as $comment_id => $comment_status )
2533 $group_by_status[$comment_status][] = $comment_id;
2535 foreach ( $group_by_status as $status => $comments ) {
2536 // Sanity check. This shouldn't happen.
2537 if ( 'post-trashed' == $status )
2539 $comments_in = implode( "', '", $comments );
2540 $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
2543 clean_comment_cache( array_keys($statuses) );
2545 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2547 do_action('untrashed_post_comments', $post_id);
2551 * Retrieve the list of categories for a post.
2553 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2554 * away from the complexity of the taxonomy layer.
2558 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
2560 * @param int $post_id Optional. The Post ID.
2561 * @param array $args Optional. Overwrite the defaults.
2564 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2565 $post_id = (int) $post_id;
2567 $defaults = array('fields' => 'ids');
2568 $args = wp_parse_args( $args, $defaults );
2570 $cats = wp_get_object_terms($post_id, 'category', $args);
2575 * Retrieve the tags for a post.
2577 * There is only one default for this function, called 'fields' and by default
2578 * is set to 'all'. There are other defaults that can be overridden in
2579 * {@link wp_get_object_terms()}.
2581 * @package WordPress
2585 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2587 * @param int $post_id Optional. The Post ID
2588 * @param array $args Optional. Overwrite the defaults
2589 * @return array List of post tags.
2591 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2592 return wp_get_post_terms( $post_id, 'post_tag', $args);
2596 * Retrieve the terms for a post.
2598 * There is only one default for this function, called 'fields' and by default
2599 * is set to 'all'. There are other defaults that can be overridden in
2600 * {@link wp_get_object_terms()}.
2602 * @package WordPress
2606 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2608 * @param int $post_id Optional. The Post ID
2609 * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
2610 * @param array $args Optional. Overwrite the defaults
2611 * @return array List of post tags.
2613 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2614 $post_id = (int) $post_id;
2616 $defaults = array('fields' => 'all');
2617 $args = wp_parse_args( $args, $defaults );
2619 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2625 * Retrieve number of recent posts.
2628 * @uses wp_parse_args()
2631 * @param string $deprecated Deprecated.
2632 * @param array $args Optional. Overrides defaults.
2633 * @param string $output Optional.
2636 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2638 if ( is_numeric( $args ) ) {
2639 _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2640 $args = array( 'numberposts' => absint( $args ) );
2643 // Set default arguments
2645 'numberposts' => 10, 'offset' => 0,
2646 'category' => 0, 'orderby' => 'post_date',
2647 'order' => 'DESC', 'include' => '',
2648 'exclude' => '', 'meta_key' => '',
2649 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2650 'suppress_filters' => true
2653 $r = wp_parse_args( $args, $defaults );
2655 $results = get_posts( $r );
2657 // Backward compatibility. Prior to 3.1 expected posts to be returned in array
2658 if ( ARRAY_A == $output ){
2659 foreach( $results as $key => $result ) {
2660 $results[$key] = get_object_vars( $result );
2662 return $results ? $results : array();
2665 return $results ? $results : false;
2670 * Insert or update a post.
2672 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2674 * You can set the post date manually, by setting the values for 'post_date'
2675 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2676 * setting the value for 'comment_status' key.
2678 * @global wpdb $wpdb WordPress database abstraction object.
2682 * @param array $postarr {
2683 * An array of elements that make up a post to update or insert.
2685 * @type int 'ID' The post ID. If equal to something other than 0, the post with that ID will
2686 * be updated. Default 0.
2687 * @type string 'post_status' The post status. Default 'draft'.
2688 * @type string 'post_type' The post type. Default 'post'.
2689 * @type int 'post_author' The ID of the user who added the post. Default the current user ID.
2690 * @type bool 'ping_status' Whether the post can accept pings. Default value of 'default_ping_status' option.
2691 * @type int 'post_parent' Set this for the post it belongs to, if any. Default 0.
2692 * @type int 'menu_order' The order it is displayed. Default 0.
2693 * @type string 'to_ping' Space or carriage return-separated list of URLs to ping. Default empty string.
2694 * @type string 'pinged' Space or carriage return-separated list of URLs that have been pinged.
2695 * Default empty string.
2696 * @type string 'post_password The password to access the post. Default empty string.
2697 * @type string 'guid' Global Unique ID for referencing the post.
2698 * @type string 'post_content_filtered' The filtered post content. Default empty string.
2699 * @type string 'post_excerpt' The post excerpt. Default empty string.
2701 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2702 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2704 function wp_insert_post( $postarr, $wp_error = false ) {
2707 $user_id = get_current_user_id();
2709 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id,
2710 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2711 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
2712 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
2713 'post_content' => '', 'post_title' => '');
2715 $postarr = wp_parse_args($postarr, $defaults);
2717 unset( $postarr[ 'filter' ] );
2719 $postarr = sanitize_post($postarr, 'db');
2721 // export array as variables
2722 extract($postarr, EXTR_SKIP);
2724 // Are we updating or creating?
2727 if ( ! empty( $ID ) ) {
2730 // Get the post ID and GUID
2732 $post_before = get_post( $post_ID );
2733 if ( is_null( $post_before ) ) {
2735 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2739 $guid = get_post_field( 'guid', $post_ID );
2740 $previous_status = get_post_field('post_status', $ID);
2742 $previous_status = 'new';
2745 $maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' )
2746 && post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' );
2748 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2750 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2755 if ( empty($post_type) )
2756 $post_type = 'post';
2758 if ( empty($post_status) )
2759 $post_status = 'draft';
2761 if ( !empty($post_category) )
2762 $post_category = array_filter($post_category); // Filter out empty terms
2764 // Make sure we set a valid category.
2765 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
2766 // 'post' requires at least one category.
2767 if ( 'post' == $post_type && 'auto-draft' != $post_status )
2768 $post_category = array( get_option('default_category') );
2770 $post_category = array();
2773 if ( empty($post_author) )
2774 $post_author = $user_id;
2776 // Don't allow contributors to set the post slug for pending review posts
2777 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
2780 // Create a valid post name. Drafts and pending posts are allowed to have an empty
2782 if ( empty($post_name) ) {
2783 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2784 $post_name = sanitize_title($post_title);
2788 // On updates, we need to check to see if it's using the old, fixed sanitization context.
2789 $check_name = sanitize_title( $post_name, '', 'old-save' );
2790 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name )
2791 $post_name = $check_name;
2792 else // new post, or slug has changed.
2793 $post_name = sanitize_title($post_name);
2796 // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
2797 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
2798 $post_date = current_time('mysql');
2800 // validate the date
2801 $mm = substr( $post_date, 5, 2 );
2802 $jj = substr( $post_date, 8, 2 );
2803 $aa = substr( $post_date, 0, 4 );
2804 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
2805 if ( !$valid_date ) {
2807 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
2812 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
2813 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2814 $post_date_gmt = get_gmt_from_date($post_date);
2816 $post_date_gmt = '0000-00-00 00:00:00';
2819 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
2820 $post_modified = current_time( 'mysql' );
2821 $post_modified_gmt = current_time( 'mysql', 1 );
2823 $post_modified = $post_date;
2824 $post_modified_gmt = $post_date_gmt;
2827 if ( 'publish' == $post_status ) {
2828 $now = gmdate('Y-m-d H:i:59');
2829 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
2830 $post_status = 'future';
2831 } elseif( 'future' == $post_status ) {
2832 $now = gmdate('Y-m-d H:i:59');
2833 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
2834 $post_status = 'publish';
2837 if ( empty($comment_status) ) {
2839 $comment_status = 'closed';
2841 $comment_status = get_option('default_comment_status');
2843 if ( empty($ping_status) )
2844 $ping_status = get_option('default_ping_status');
2846 if ( isset($to_ping) )
2847 $to_ping = sanitize_trackback_urls( $to_ping );
2851 if ( ! isset($pinged) )
2854 if ( isset($post_parent) )
2855 $post_parent = (int) $post_parent;
2859 // Check the post_parent to see if it will cause a hierarchy loop
2860 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
2862 if ( isset($menu_order) )
2863 $menu_order = (int) $menu_order;
2867 if ( !isset($post_password) || 'private' == $post_status )
2868 $post_password = '';
2870 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2872 // expected_slashed (everything!)
2873 $data = compact( array( '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', 'guid' ) );
2874 $data = apply_filters('wp_insert_post_data', $data, $postarr);
2875 $data = wp_unslash( $data );
2876 $where = array( 'ID' => $post_ID );
2879 do_action( 'pre_post_update', $post_ID, $data );
2880 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
2882 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
2887 if ( isset($post_mime_type) )
2888 $data['post_mime_type'] = wp_unslash( $post_mime_type ); // This isn't in the update
2889 // If there is a suggested ID, use it if not already present
2890 if ( !empty($import_id) ) {
2891 $import_id = (int) $import_id;
2892 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2893 $data['ID'] = $import_id;
2896 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
2898 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
2902 $post_ID = (int) $wpdb->insert_id;
2904 // use the newly generated $post_ID
2905 $where = array( 'ID' => $post_ID );
2908 if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
2909 $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
2910 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
2913 if ( is_object_in_taxonomy($post_type, 'category') )
2914 wp_set_post_categories( $post_ID, $post_category );
2916 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
2917 wp_set_post_tags( $post_ID, $tags_input );
2919 // new-style support for all custom taxonomies
2920 if ( !empty($tax_input) ) {
2921 foreach ( $tax_input as $taxonomy => $tags ) {
2922 $taxonomy_obj = get_taxonomy($taxonomy);
2923 if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
2924 $tags = array_filter($tags);
2925 if ( current_user_can($taxonomy_obj->cap->assign_terms) )
2926 wp_set_post_terms( $post_ID, $tags, $taxonomy );
2930 $current_guid = get_post_field( 'guid', $post_ID );
2933 if ( !$update && '' == $current_guid )
2934 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
2936 clean_post_cache( $post_ID );
2938 $post = get_post($post_ID);
2940 if ( !empty($page_template) && 'page' == $data['post_type'] ) {
2941 $post->page_template = $page_template;
2942 $page_templates = wp_get_theme()->get_page_templates();
2943 if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) {
2945 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
2949 update_post_meta($post_ID, '_wp_page_template', $page_template);
2952 wp_transition_post_status($data['post_status'], $previous_status, $post);
2955 do_action('edit_post', $post_ID, $post);
2956 $post_after = get_post($post_ID);
2957 do_action( 'post_updated', $post_ID, $post_after, $post_before);
2960 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
2961 do_action( 'save_post', $post_ID, $post, $update );
2962 do_action( 'wp_insert_post', $post_ID, $post, $update );
2968 * Update a post with new post data.
2970 * The date does not have to be set for drafts. You can set the date and it will
2971 * not be overridden.
2975 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
2976 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2977 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
2979 function wp_update_post( $postarr = array(), $wp_error = false ) {
2980 if ( is_object($postarr) ) {
2981 // non-escaped post was passed
2982 $postarr = get_object_vars($postarr);
2983 $postarr = wp_slash($postarr);
2986 // First, get all of the original fields
2987 $post = get_post($postarr['ID'], ARRAY_A);
2989 if ( is_null( $post ) ) {
2991 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2995 // Escape data pulled from DB.
2996 $post = wp_slash($post);
2998 // Passed post category list overwrites existing category list if not empty.
2999 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3000 && 0 != count($postarr['post_category']) )
3001 $post_cats = $postarr['post_category'];
3003 $post_cats = $post['post_category'];
3005 // Drafts shouldn't be assigned a date unless explicitly done so by the user
3006 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3007 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3010 $clear_date = false;
3012 // Merge old and new fields with new fields overwriting old ones.
3013 $postarr = array_merge($post, $postarr);
3014 $postarr['post_category'] = $post_cats;
3015 if ( $clear_date ) {
3016 $postarr['post_date'] = current_time('mysql');
3017 $postarr['post_date_gmt'] = '';
3020 if ($postarr['post_type'] == 'attachment')
3021 return wp_insert_attachment($postarr);
3023 return wp_insert_post( $postarr, $wp_error );
3027 * Publish a post by transitioning the post status.
3031 * @uses do_action() Calls 'edit_post', 'save_post_{$post_type}', 'save_post' and 'wp_insert_post' on post_id and post data.
3033 * @param int|object $post Post ID or object.
3035 function wp_publish_post( $post ) {
3038 if ( ! $post = get_post( $post ) )
3041 if ( 'publish' == $post->post_status )
3044 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3046 clean_post_cache( $post->ID );
3048 $old_status = $post->post_status;
3049 $post->post_status = 'publish';
3050 wp_transition_post_status( 'publish', $old_status, $post );
3052 do_action( 'edit_post', $post->ID, $post );
3053 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3054 do_action( 'save_post', $post->ID, $post, true );
3055 do_action( 'wp_insert_post', $post->ID, $post, true );
3059 * Publish future post and make sure post ID has future post status.
3061 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3062 * from publishing drafts, etc.
3066 * @param int $post_id Post ID.
3067 * @return null Nothing is returned. Which can mean that no action is required or post was published.
3069 function check_and_publish_future_post($post_id) {
3071 $post = get_post($post_id);
3076 if ( 'future' != $post->post_status )
3079 $time = strtotime( $post->post_date_gmt . ' GMT' );
3081 if ( $time > time() ) { // Uh oh, someone jumped the gun!
3082 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3083 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3087 return wp_publish_post($post_id);
3091 * Computes a unique slug for the post, when given the desired slug and some post details.
3095 * @global wpdb $wpdb
3096 * @global WP_Rewrite $wp_rewrite
3097 * @param string $slug the desired slug (post_name)
3098 * @param integer $post_ID
3099 * @param string $post_status no uniqueness checks are made if the post is still draft or pending
3100 * @param string $post_type
3101 * @param integer $post_parent
3102 * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3104 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3105 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3108 global $wpdb, $wp_rewrite;
3110 $original_slug = $slug;
3112 $feeds = $wp_rewrite->feeds;
3113 if ( ! is_array( $feeds ) )
3116 $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
3117 if ( 'attachment' == $post_type ) {
3118 // Attachment slugs must be unique across all types.
3119 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3120 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3122 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3125 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3126 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3128 } while ( $post_name_check );
3129 $slug = $alt_post_name;
3131 } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
3132 if ( 'nav_menu_item' == $post_type )
3134 // Page slugs must be unique within their own trees. Pages are in a separate
3135 // namespace than posts so page slugs are allowed to overlap post slugs.
3136 $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";
3137 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
3139 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 ) ) {
3142 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3143 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
3145 } while ( $post_name_check );
3146 $slug = $alt_post_name;
3149 // Post slugs must be unique across all posts.
3150 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3151 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3153 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3156 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3157 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3159 } while ( $post_name_check );
3160 $slug = $alt_post_name;
3164 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3168 * Truncates a post slug.
3172 * @uses utf8_uri_encode() Makes sure UTF-8 characters are properly cut and encoded.
3174 * @param string $slug The slug to truncate.
3175 * @param int $length Max length of the slug.
3176 * @return string The truncated slug.
3178 function _truncate_post_slug( $slug, $length = 200 ) {
3179 if ( strlen( $slug ) > $length ) {
3180 $decoded_slug = urldecode( $slug );
3181 if ( $decoded_slug === $slug )
3182 $slug = substr( $slug, 0, $length );
3184 $slug = utf8_uri_encode( $decoded_slug, $length );
3187 return rtrim( $slug, '-' );
3191 * Adds tags to a post.
3193 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
3195 * @package WordPress
3199 * @param int $post_id Post ID
3200 * @param string $tags The tags to set for the post, separated by commas.
3201 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
3203 function wp_add_post_tags($post_id = 0, $tags = '') {
3204 return wp_set_post_tags($post_id, $tags, true);
3208 * Set the tags for a post.
3211 * @uses wp_set_object_terms() Sets the tags for the post.
3213 * @param int $post_id Post ID.
3214 * @param string $tags The tags to set for the post, separated by commas.
3215 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3216 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3218 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3219 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3223 * Set the terms for a post.
3226 * @uses wp_set_object_terms() Sets the tags for the post.
3228 * @param int $post_id Post ID.
3229 * @param string $tags The tags to set for the post, separated by commas.
3230 * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'.
3231 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3232 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3234 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3235 $post_id = (int) $post_id;
3243 if ( ! is_array( $tags ) ) {
3244 $comma = _x( ',', 'tag delimiter' );
3245 if ( ',' !== $comma )
3246 $tags = str_replace( $comma, ',', $tags );
3247 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3250 // Hierarchical taxonomies must always pass IDs rather than names so that children with the same
3251 // names but different parents aren't confused.
3252 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3253 $tags = array_unique( array_map( 'intval', $tags ) );
3256 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3260 * Set categories for a post.
3262 * If the post categories parameter is not set, then the default category is
3267 * @param int $post_ID Post ID.
3268 * @param array|int $post_categories Optional. List of categories or ID of category.
3269 * @param bool $append If true, don't delete existing categories, just add on. If false, replace the categories with the new categories.
3270 * @return bool|mixed
3272 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3273 $post_ID = (int) $post_ID;
3274 $post_type = get_post_type( $post_ID );
3275 $post_status = get_post_status( $post_ID );
3276 // If $post_categories isn't already an array, make it one:
3277 $post_categories = (array) $post_categories;
3278 if ( empty( $post_categories ) ) {
3279 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3280 $post_categories = array( get_option('default_category') );
3283 $post_categories = array();
3285 } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
3289 return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3293 * Transition the post status of a post.
3295 * Calls hooks to transition post status.
3297 * The first is 'transition_post_status' with new status, old status, and post data.
3299 * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
3300 * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
3303 * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
3304 * parameter and POSTTYPE is post_type post data.
3307 * @link http://codex.wordpress.org/Post_Status_Transitions
3309 * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
3310 * $post if there is a status change.
3311 * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
3312 * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
3314 * @param string $new_status Transition to this post status.
3315 * @param string $old_status Previous post status.
3316 * @param object $post Post data.
3318 function wp_transition_post_status($new_status, $old_status, $post) {
3319 do_action('transition_post_status', $new_status, $old_status, $post);
3320 do_action("{$old_status}_to_{$new_status}", $post);
3321 do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
3325 // Trackback and ping functions
3329 * Add a URL to those already pung.
3334 * @param int $post_id Post ID.
3335 * @param string $uri Ping URI.
3336 * @return int How many rows were updated.
3338 function add_ping($post_id, $uri) {
3340 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3341 $pung = trim($pung);
3342 $pung = preg_split('/\s/', $pung);
3344 $new = implode("\n", $pung);
3345 $new = apply_filters('add_ping', $new);
3346 // expected_slashed ($new)
3347 $new = wp_unslash($new);
3348 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3352 * Retrieve enclosures already enclosed for a post.
3356 * @param int $post_id Post ID.
3357 * @return array List of enclosures
3359 function get_enclosed($post_id) {
3360 $custom_fields = get_post_custom( $post_id );
3362 if ( !is_array( $custom_fields ) )
3365 foreach ( $custom_fields as $key => $val ) {
3366 if ( 'enclosure' != $key || !is_array( $val ) )
3368 foreach( $val as $enc ) {
3369 $enclosure = explode( "\n", $enc );
3370 $pung[] = trim( $enclosure[ 0 ] );
3373 $pung = apply_filters('get_enclosed', $pung, $post_id);
3378 * Retrieve URLs already pinged for a post.
3383 * @param int $post_id Post ID.
3386 function get_pung($post_id) {
3388 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3389 $pung = trim($pung);
3390 $pung = preg_split('/\s/', $pung);
3391 $pung = apply_filters('get_pung', $pung);
3396 * Retrieve URLs that need to be pinged.
3401 * @param int $post_id Post ID
3404 function get_to_ping($post_id) {
3406 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
3407 $to_ping = sanitize_trackback_urls( $to_ping );
3408 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
3409 $to_ping = apply_filters('get_to_ping', $to_ping);
3414 * Do trackbacks for a list of URLs.
3418 * @param string $tb_list Comma separated list of URLs
3419 * @param int $post_id Post ID
3421 function trackback_url_list($tb_list, $post_id) {
3422 if ( ! empty( $tb_list ) ) {
3424 $postdata = get_post($post_id, ARRAY_A);
3426 // import postdata as variables
3427 extract($postdata, EXTR_SKIP);
3430 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
3432 if (strlen($excerpt) > 255) {
3433 $excerpt = substr($excerpt,0,252) . '…';
3436 $trackback_urls = explode(',', $tb_list);
3437 foreach( (array) $trackback_urls as $tb_url) {
3438 $tb_url = trim($tb_url);
3439 trackback($tb_url, wp_unslash($post_title), $excerpt, $post_id);
3449 * Get a list of page IDs.
3454 * @return array List of page IDs.
3456 function get_all_page_ids() {
3459 $page_ids = wp_cache_get('all_page_ids', 'posts');
3460 if ( ! is_array( $page_ids ) ) {
3461 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
3462 wp_cache_add('all_page_ids', $page_ids, 'posts');
3469 * Retrieves page data given a page ID or page object.
3471 * Use get_post() instead of get_page().
3476 * @param mixed $page Page object or page ID. Passed by reference.
3477 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
3478 * @param string $filter How the return value should be filtered.
3479 * @return WP_Post|null WP_Post on success or null on failure
3481 function get_page( $page, $output = OBJECT, $filter = 'raw') {
3482 return get_post( $page, $output, $filter );
3486 * Retrieves a page given its path.
3491 * @param string $page_path Page path
3492 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3493 * @param string $post_type Optional. Post type. Default page.
3494 * @return WP_Post|null WP_Post on success or null on failure
3496 function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
3499 $page_path = rawurlencode(urldecode($page_path));
3500 $page_path = str_replace('%2F', '/', $page_path);
3501 $page_path = str_replace('%20', ' ', $page_path);
3502 $parts = explode( '/', trim( $page_path, '/' ) );
3503 $parts = esc_sql( $parts );
3504 $parts = array_map( 'sanitize_title_for_query', $parts );
3506 $in_string = "'". implode( "','", $parts ) . "'";
3507 $post_type_sql = esc_sql( $post_type );
3508 $pages = $wpdb->get_results( "SELECT ID, post_name, post_parent, post_type FROM $wpdb->posts WHERE post_name IN ($in_string) AND (post_type = '$post_type_sql' OR post_type = 'attachment')", OBJECT_K );
3510 $revparts = array_reverse( $parts );
3513 foreach ( (array) $pages as $page ) {
3514 if ( $page->post_name == $revparts[0] ) {
3517 while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
3519 $parent = $pages[ $p->post_parent ];
3520 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
3525 if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
3526 $foundid = $page->ID;
3527 if ( $page->post_type == $post_type )
3534 return get_post( $foundid, $output );
3540 * Retrieve a page given its title.
3545 * @param string $page_title Page title
3546 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3547 * @param string $post_type Optional. Post type. Default page.
3548 * @return WP_Post|null WP_Post on success or null on failure
3550 function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
3552 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
3554 return get_post( $page, $output );
3560 * Retrieve child pages from list of pages matching page ID.
3562 * Matches against the pages parameter against the page ID. Also matches all
3563 * children for the same to retrieve all children of a page. Does not make any
3564 * SQL queries to get the children.
3568 * @param int $page_id Page ID.
3569 * @param array $pages List of pages' objects.
3572 function get_page_children($page_id, $pages) {
3573 $page_list = array();
3574 foreach ( (array) $pages as $page ) {
3575 if ( $page->post_parent == $page_id ) {
3576 $page_list[] = $page;
3577 if ( $children = get_page_children($page->ID, $pages) )
3578 $page_list = array_merge($page_list, $children);
3585 * Order the pages with children under parents in a flat list.
3587 * It uses auxiliary structure to hold parent-children relationships and
3588 * runs in O(N) complexity
3592 * @param array $pages Posts array.
3593 * @param int $page_id Parent page ID.
3594 * @return array A list arranged by hierarchy. Children immediately follow their parents.
3596 function get_page_hierarchy( &$pages, $page_id = 0 ) {
3597 if ( empty( $pages ) ) {
3602 $children = array();
3603 foreach ( (array) $pages as $p ) {
3604 $parent_id = intval( $p->post_parent );
3605 $children[ $parent_id ][] = $p;
3609 _page_traverse_name( $page_id, $children, $result );
3615 * function to traverse and return all the nested children post names of a root page.
3616 * $children contains parent-children relations
3620 function _page_traverse_name( $page_id, &$children, &$result ){
3621 if ( isset( $children[ $page_id ] ) ){
3622 foreach( (array)$children[ $page_id ] as $child ) {
3623 $result[ $child->ID ] = $child->post_name;
3624 _page_traverse_name( $child->ID, $children, $result );
3630 * Builds URI for a page.
3632 * Sub pages will be in the "directory" under the parent page post name.
3636 * @param mixed $page Page object or page ID.
3637 * @return string|false Page URI, false on error.
3639 function get_page_uri( $page ) {
3640 $page = get_post( $page );
3645 $uri = $page->post_name;
3647 foreach ( $page->ancestors as $parent ) {
3648 $uri = get_post( $parent )->post_name . '/' . $uri;
3655 * Retrieve a list of pages.
3657 * @global wpdb $wpdb WordPress database abstraction object
3661 * @param mixed $args {
3662 * Array or string of arguments. Optional.
3664 * @type int 'child_of' Page ID to return child and grandchild pages of. Default 0, or no restriction.
3665 * @type string 'sort_order' How to sort retrieved pages.
3666 * Default 'ASC'. Accepts 'ASC', 'DESC'.
3667 * @type string 'sort_column' What columns to sort pages by, comma-separated.
3668 * Default 'post_title'. Accepts 'post_author', 'post_date', 'post_title', 'post_name',
3669 * 'post_modified', 'post_modified_gmt', 'menu_order', 'post_parent', 'ID', 'rand',
3670 * 'comment_count'. 'post_' can be omitted for any values that start with it.
3671 * @type bool 'hierarchical' Whether to return pages hierarchically. Default true.
3672 * @type array 'exclude' Array of page IDs to exclude.
3673 * @type array 'include' Array of page IDs to include. Cannot be used with 'child_of', 'parent', 'exclude',
3674 * 'meta_key', 'meta_value', or 'hierarchical'.
3675 * @type string 'meta_key' Only include pages with this meta key.
3676 * @type string 'meta_value' Only include pages with this meta value.
3677 * @type string 'authors' A comma-separated list of author IDs.
3678 * @type int 'parent' Page ID to return direct children of. 'hierarchical' must be false.
3679 * Default -1, or no restriction.
3680 * @type int 'exclude_tree' Remove all children of the given ID from returned pages.
3681 * @type int 'number' The number of pages to return. Default 0, or all pages.
3682 * @type int 'offset' The number of pages to skip before returning. Requires 'number'.
3684 * @type string 'post_type' The post type to query.
3686 * @type string 'post_status' A comma-separated list of post status types to include.
3687 * Default 'publish'.
3689 * @return array List of pages matching defaults or $args.
3691 function get_pages( $args = array() ) {
3697 'child_of' => 0, 'sort_order' => 'ASC',
3698 'sort_column' => 'post_title', 'hierarchical' => 1,
3699 'exclude' => array(), 'include' => array(),
3700 'meta_key' => '', 'meta_value' => '',
3701 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
3702 'number' => '', 'offset' => 0,
3703 'post_type' => 'page', 'post_status' => 'publish',
3706 $r = wp_parse_args( $args, $defaults );
3707 extract( $r, EXTR_SKIP );
3708 $number = (int) $number;
3709 $offset = (int) $offset;
3711 // Make sure the post type is hierarchical
3712 $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
3713 if ( !in_array( $post_type, $hierarchical_post_types ) )
3716 if ( $parent > 0 && ! $child_of )
3717 $hierarchical = false;
3719 // Make sure we have a valid post status
3720 if ( !is_array( $post_status ) )
3721 $post_status = explode( ',', $post_status );
3722 if ( array_diff( $post_status, get_post_stati() ) )
3725 // $args can be whatever, only use the args defined in defaults to compute the key
3726 $key = md5( serialize( compact(array_keys($defaults)) ) );
3727 $last_changed = wp_cache_get( 'last_changed', 'posts' );
3728 if ( ! $last_changed ) {
3729 $last_changed = microtime();
3730 wp_cache_set( 'last_changed', $last_changed, 'posts' );
3733 $cache_key = "get_pages:$key:$last_changed";
3734 if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
3735 // Convert to WP_Post instances
3736 $pages = array_map( 'get_post', $cache );
3737 $pages = apply_filters('get_pages', $pages, $r);
3741 if ( !is_array($cache) )
3745 if ( ! empty( $include ) ) {
3746 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
3751 $hierarchical = false;
3752 $incpages = wp_parse_id_list( $include );
3753 if ( ! empty( $incpages ) )
3754 $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
3758 if ( ! empty( $exclude ) ) {
3759 $expages = wp_parse_id_list( $exclude );
3760 if ( ! empty( $expages ) )
3761 $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
3765 if (!empty($authors)) {
3766 $post_authors = preg_split('/[\s,]+/',$authors);
3768 if ( ! empty( $post_authors ) ) {
3769 foreach ( $post_authors as $post_author ) {
3770 //Do we have an author id or an author login?
3771 if ( 0 == intval($post_author) ) {
3772 $post_author = get_user_by('login', $post_author);
3773 if ( empty($post_author) )
3775 if ( empty($post_author->ID) )
3777 $post_author = $post_author->ID;
3780 if ( '' == $author_query )
3781 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
3783 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
3785 if ( '' != $author_query )
3786 $author_query = " AND ($author_query)";
3791 $where = "$exclusions $inclusions ";
3792 if ( '' !== $meta_key || '' !== $meta_value ) {
3793 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
3795 // meta_key and meta_value might be slashed
3796 $meta_key = wp_unslash($meta_key);
3797 $meta_value = wp_unslash($meta_value);
3798 if ( '' !== $meta_key )
3799 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
3800 if ( '' !== $meta_value )
3801 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
3805 if ( is_array( $parent ) ) {
3806 $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
3807 if ( ! empty( $post_parent__in ) )
3808 $where .= " AND post_parent IN ($post_parent__in)";
3809 } elseif ( $parent >= 0 ) {
3810 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
3813 if ( 1 == count( $post_status ) ) {
3814 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
3816 $post_status = implode( "', '", $post_status );
3817 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
3820 $orderby_array = array();
3821 $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
3822 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
3823 'ID', 'rand', 'comment_count');
3824 foreach ( explode( ',', $sort_column ) as $orderby ) {
3825 $orderby = trim( $orderby );
3826 if ( !in_array( $orderby, $allowed_keys ) )
3829 switch ( $orderby ) {
3833 $orderby = "$wpdb->posts.ID";
3836 $orderby = 'RAND()';
3838 case 'comment_count':
3839 $orderby = "$wpdb->posts.comment_count";
3842 if ( 0 === strpos( $orderby, 'post_' ) )
3843 $orderby = "$wpdb->posts." . $orderby;
3845 $orderby = "$wpdb->posts.post_" . $orderby;
3848 $orderby_array[] = $orderby;
3851 $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
3853 $sort_order = strtoupper( $sort_order );
3854 if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
3855 $sort_order = 'ASC';
3857 $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
3858 $query .= $author_query;
3859 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
3861 if ( !empty($number) )
3862 $query .= ' LIMIT ' . $offset . ',' . $number;
3864 $pages = $wpdb->get_results($query);
3866 if ( empty($pages) ) {
3867 $pages = apply_filters('get_pages', array(), $r);
3871 // Sanitize before caching so it'll only get done once
3872 $num_pages = count($pages);
3873 for ($i = 0; $i < $num_pages; $i++) {
3874 $pages[$i] = sanitize_post($pages[$i], 'raw');
3878 update_post_cache( $pages );
3880 if ( $child_of || $hierarchical )
3881 $pages = get_page_children($child_of, $pages);
3883 if ( !empty($exclude_tree) ) {
3884 $exclude = (int) $exclude_tree;
3885 $children = get_page_children($exclude, $pages);
3886 $excludes = array();
3887 foreach ( $children as $child )
3888 $excludes[] = $child->ID;
3889 $excludes[] = $exclude;
3890 $num_pages = count($pages);
3891 for ( $i = 0; $i < $num_pages; $i++ ) {
3892 if ( in_array($pages[$i]->ID, $excludes) )
3897 $page_structure = array();
3898 foreach ( $pages as $page )
3899 $page_structure[] = $page->ID;
3901 wp_cache_set( $cache_key, $page_structure, 'posts' );
3903 // Convert to WP_Post instances
3904 $pages = array_map( 'get_post', $pages );
3906 $pages = apply_filters('get_pages', $pages, $r);
3912 // Attachment functions
3916 * Check if the attachment URI is local one and is really an attachment.
3920 * @param string $url URL to check
3921 * @return bool True on success, false on failure.
3923 function is_local_attachment($url) {
3924 if (strpos($url, home_url()) === false)
3926 if (strpos($url, home_url('/?attachment_id=')) !== false)
3928 if ( $id = url_to_postid($url) ) {
3929 $post = get_post($id);
3930 if ( 'attachment' == $post->post_type )
3937 * Insert an attachment.
3939 * If you set the 'ID' in the $object parameter, it will mean that you are
3940 * updating and attempt to update the attachment. You can also set the
3941 * attachment name or title by setting the key 'post_name' or 'post_title'.
3943 * You can set the dates for the attachment manually by setting the 'post_date'
3944 * and 'post_date_gmt' keys' values.
3946 * By default, the comments will use the default settings for whether the
3947 * comments are allowed. You can close them manually or keep them open by
3948 * setting the value for the 'comment_status' key.
3950 * The $object parameter can have the following:
3951 * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
3952 * 'post_type' - Default is 'post', will be set to attachment. Can not override.
3953 * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
3954 * 'ping_status' - Default is the value in default ping status option. Whether the attachment
3956 * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
3958 * 'menu_order' - Default is 0. The order it is displayed.
3959 * 'to_ping' - Whether to ping.
3960 * 'pinged' - Default is empty string.
3961 * 'post_password' - Default is empty string. The password to access the attachment.
3962 * 'guid' - Global Unique ID for referencing the attachment.
3963 * 'post_content_filtered' - Attachment post content filtered.
3964 * 'post_excerpt' - Attachment excerpt.
3968 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
3969 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
3971 * @param string|array $object Arguments to override defaults.
3972 * @param string $file Optional filename.
3973 * @param int $parent Parent post ID.
3974 * @return int Attachment ID.
3976 function wp_insert_attachment($object, $file = false, $parent = 0) {
3979 $user_id = get_current_user_id();
3981 $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id,
3982 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '',
3983 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '',
3984 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
3986 $object = wp_parse_args($object, $defaults);
3987 if ( !empty($parent) )
3988 $object['post_parent'] = $parent;
3990 unset( $object[ 'filter' ] );
3992 $object = sanitize_post($object, 'db');
3994 // export array as variables
3995 extract($object, EXTR_SKIP);
3997 if ( empty($post_author) )
3998 $post_author = $user_id;
4000 $post_type = 'attachment';
4002 if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
4003 $post_status = 'inherit';
4005 if ( !empty($post_category) )
4006 $post_category = array_filter($post_category); // Filter out empty terms
4008 // Make sure we set a valid category.
4009 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
4010 $post_category = array();
4013 // Are we updating or creating?
4014 if ( !empty($ID) ) {
4016 $post_ID = (int) $ID;
4022 // Create a valid post name.
4023 if ( empty($post_name) )
4024 $post_name = sanitize_title($post_title);
4026 $post_name = sanitize_title($post_name);
4028 // expected_slashed ($post_name)
4029 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
4031 if ( empty($post_date) )
4032 $post_date = current_time('mysql');
4033 if ( empty($post_date_gmt) )
4034 $post_date_gmt = current_time('mysql', 1);
4036 if ( empty($post_modified) )
4037 $post_modified = $post_date;
4038 if ( empty($post_modified_gmt) )
4039 $post_modified_gmt = $post_date_gmt;
4041 if ( empty($comment_status) ) {
4043 $comment_status = 'closed';
4045 $comment_status = get_option('default_comment_status');
4047 if ( empty($ping_status) )
4048 $ping_status = get_option('default_ping_status');
4050 if ( isset($to_ping) )
4051 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
4055 if ( isset($post_parent) )
4056 $post_parent = (int) $post_parent;
4060 if ( isset($menu_order) )
4061 $menu_order = (int) $menu_order;
4065 if ( !isset($post_password) )
4066 $post_password = '';
4068 if ( ! isset($pinged) )
4071 // expected_slashed (everything!)
4072 $data = compact( array( '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' ) );
4073 $data = wp_unslash( $data );
4076 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
4078 // If there is a suggested ID, use it if not already present
4079 if ( !empty($import_id) ) {
4080 $import_id = (int) $import_id;
4081 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
4082 $data['ID'] = $import_id;
4086 $wpdb->insert( $wpdb->posts, $data );
4087 $post_ID = (int) $wpdb->insert_id;
4090 if ( empty($post_name) ) {
4091 $post_name = sanitize_title($post_title, $post_ID);
4092 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
4095 if ( is_object_in_taxonomy($post_type, 'category') )
4096 wp_set_post_categories( $post_ID, $post_category );
4098 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
4099 wp_set_post_tags( $post_ID, $tags_input );
4101 // support for all custom taxonomies
4102 if ( !empty($tax_input) ) {
4103 foreach ( $tax_input as $taxonomy => $tags ) {
4104 $taxonomy_obj = get_taxonomy($taxonomy);
4105 if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
4106 $tags = array_filter($tags);
4107 if ( current_user_can($taxonomy_obj->cap->assign_terms) )
4108 wp_set_post_terms( $post_ID, $tags, $taxonomy );
4113 update_attached_file( $post_ID, $file );
4115 clean_post_cache( $post_ID );
4117 if ( ! empty( $context ) )
4118 add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
4121 do_action('edit_attachment', $post_ID);
4123 do_action('add_attachment', $post_ID);
4130 * Trashes or deletes an attachment.
4132 * When an attachment is permanently deleted, the file will also be removed.
4133 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4134 * with the attachment (except the main post).
4136 * The attachment is moved to the trash instead of permanently deleted unless trash
4137 * for media is disabled, item is already in the trash, or $force_delete is true.
4141 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
4143 * @param int $post_id Attachment ID.
4144 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
4145 * @return mixed False on failure. Post data on success.
4147 function wp_delete_attachment( $post_id, $force_delete = false ) {
4150 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4153 if ( 'attachment' != $post->post_type )
4156 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4157 return wp_trash_post( $post_id );
4159 delete_post_meta($post_id, '_wp_trash_meta_status');
4160 delete_post_meta($post_id, '_wp_trash_meta_time');
4162 $meta = wp_get_attachment_metadata( $post_id );
4163 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4164 $file = get_attached_file( $post_id );
4166 $intermediate_sizes = array();
4167 foreach ( get_intermediate_image_sizes() as $size ) {
4168 if ( $intermediate = image_get_intermediate_size( $post_id, $size ) )
4169 $intermediate_sizes[] = $intermediate;
4172 if ( is_multisite() )
4173 delete_transient( 'dirsize_cache' );
4175 do_action('delete_attachment', $post_id);
4177 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4178 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4180 delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts.
4182 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4183 foreach ( $comment_ids as $comment_id )
4184 wp_delete_comment( $comment_id, true );
4186 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4187 foreach ( $post_meta_ids as $mid )
4188 delete_metadata_by_mid( 'post', $mid );
4190 do_action( 'delete_post', $post_id );
4191 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4195 do_action( 'deleted_post', $post_id );
4197 $uploadpath = wp_upload_dir();
4199 if ( ! empty($meta['thumb']) ) {
4200 // Don't delete the thumb if another attachment uses it
4201 if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id)) ) {
4202 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4203 /** This filter is documented in wp-admin/custom-header.php */
4204 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
4205 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4209 // remove intermediate and backup images if there are any
4210 foreach ( $intermediate_sizes as $intermediate ) {
4211 /** This filter is documented in wp-admin/custom-header.php */
4212 $intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] );
4213 @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
4216 if ( is_array($backup_sizes) ) {
4217 foreach ( $backup_sizes as $size ) {
4218 $del_file = path_join( dirname($meta['file']), $size['file'] );
4219 /** This filter is documented in wp-admin/custom-header.php */
4220 $del_file = apply_filters('wp_delete_file', $del_file);
4221 @ unlink( path_join($uploadpath['basedir'], $del_file) );
4225 /** This filter is documented in wp-admin/custom-header.php */
4226 $file = apply_filters('wp_delete_file', $file);
4228 if ( ! empty($file) )
4231 clean_post_cache( $post );
4237 * Retrieve attachment meta field for attachment ID.
4241 * @param int $post_id Attachment ID
4242 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
4243 * @return string|bool Attachment meta field. False on failure.
4245 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4246 $post_id = (int) $post_id;
4247 if ( !$post = get_post( $post_id ) )
4250 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4255 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4259 * Update metadata for an attachment.
4263 * @param int $post_id Attachment ID.
4264 * @param array $data Attachment data.
4267 function wp_update_attachment_metadata( $post_id, $data ) {
4268 $post_id = (int) $post_id;
4269 if ( !$post = get_post( $post_id ) )
4272 if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4273 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4275 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4279 * Retrieve the URL for an attachment.
4283 * @param int $post_id Attachment ID.
4286 function wp_get_attachment_url( $post_id = 0 ) {
4287 $post_id = (int) $post_id;
4288 if ( !$post = get_post( $post_id ) )
4291 if ( 'attachment' != $post->post_type )
4295 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
4296 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
4297 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
4298 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
4299 elseif ( false !== strpos($file, 'wp-content/uploads') )
4300 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
4302 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
4306 if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recommended to rely upon this.
4307 $url = get_the_guid( $post->ID );
4309 $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4311 if ( empty( $url ) )
4318 * Retrieve thumbnail for an attachment.
4322 * @param int $post_id Attachment ID.
4323 * @return mixed False on failure. Thumbnail file path on success.
4325 function wp_get_attachment_thumb_file( $post_id = 0 ) {
4326 $post_id = (int) $post_id;
4327 if ( !$post = get_post( $post_id ) )
4329 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
4332 $file = get_attached_file( $post->ID );
4334 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
4335 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
4340 * Retrieve URL for an attachment thumbnail.
4344 * @param int $post_id Attachment ID
4345 * @return string|bool False on failure. Thumbnail URL on success.
4347 function wp_get_attachment_thumb_url( $post_id = 0 ) {
4348 $post_id = (int) $post_id;
4349 if ( !$post = get_post( $post_id ) )
4351 if ( !$url = wp_get_attachment_url( $post->ID ) )
4354 $sized = image_downsize( $post_id, 'thumbnail' );
4358 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
4361 $url = str_replace(basename($url), basename($thumb), $url);
4363 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
4367 * Check if the attachment is an image.
4371 * @param int $post_id Attachment ID
4374 function wp_attachment_is_image( $post_id = 0 ) {
4375 $post_id = (int) $post_id;
4376 if ( !$post = get_post( $post_id ) )
4379 if ( !$file = get_attached_file( $post->ID ) )
4382 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
4384 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
4386 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
4392 * Retrieve the icon for a MIME type.
4396 * @param string|int $mime MIME type or attachment ID.
4397 * @return string|bool
4399 function wp_mime_type_icon( $mime = 0 ) {
4400 if ( !is_numeric($mime) )
4401 $icon = wp_cache_get("mime_type_icon_$mime");
4404 if ( empty($icon) ) {
4405 $post_mimes = array();
4406 if ( is_numeric($mime) ) {
4407 $mime = (int) $mime;
4408 if ( $post = get_post( $mime ) ) {
4409 $post_id = (int) $post->ID;
4410 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
4411 if ( !empty($ext) ) {
4412 $post_mimes[] = $ext;
4413 if ( $ext_type = wp_ext2type( $ext ) )
4414 $post_mimes[] = $ext_type;
4416 $mime = $post->post_mime_type;
4421 $post_mimes[] = $mime;
4424 $icon_files = wp_cache_get('icon_files');
4426 if ( !is_array($icon_files) ) {
4427 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
4428 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
4429 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
4430 $icon_files = array();
4432 $keys = array_keys( $dirs );
4433 $dir = array_shift( $keys );
4434 $uri = array_shift($dirs);
4435 if ( $dh = opendir($dir) ) {
4436 while ( false !== $file = readdir($dh) ) {
4437 $file = basename($file);
4438 if ( substr($file, 0, 1) == '.' )
4440 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
4441 if ( is_dir("$dir/$file") )
4442 $dirs["$dir/$file"] = "$uri/$file";
4445 $icon_files["$dir/$file"] = "$uri/$file";
4450 wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
4453 // Icon basename - extension = MIME wildcard
4454 foreach ( $icon_files as $file => $uri )
4455 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
4457 if ( ! empty($mime) ) {
4458 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
4459 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
4460 $post_mimes[] = str_replace('/', '_', $mime);
4463 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
4464 $matches['default'] = array('default');
4466 foreach ( $matches as $match => $wilds ) {
4467 if ( isset($types[$wilds[0]])) {
4468 $icon = $types[$wilds[0]];
4469 if ( !is_numeric($mime) )
4470 wp_cache_add("mime_type_icon_$mime", $icon);
4476 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
4480 * Checked for changed slugs for published post objects and save the old slug.
4482 * The function is used when a post object of any type is updated,
4483 * by comparing the current and previous post objects.
4485 * If the slug was changed and not already part of the old slugs then it will be
4486 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
4489 * The most logically usage of this function is redirecting changed post objects, so
4490 * that those that linked to an changed post will be redirected to the new post.
4494 * @param int $post_id Post ID.
4495 * @param object $post The Post Object
4496 * @param object $post_before The Previous Post Object
4497 * @return int Same as $post_id
4499 function wp_check_for_changed_slugs($post_id, $post, $post_before) {
4500 // dont bother if it hasnt changed
4501 if ( $post->post_name == $post_before->post_name )
4504 // we're only concerned with published, non-hierarchical objects
4505 if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
4508 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
4510 // if we haven't added this old slug before, add it now
4511 if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
4512 add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
4514 // if the new slug was used previously, delete it from the list
4515 if ( in_array($post->post_name, $old_slugs) )
4516 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
4520 * Retrieve the private post SQL based on capability.
4522 * This function provides a standardized way to appropriately select on the
4523 * post_status of a post type. The function will return a piece of SQL code
4524 * that can be added to a WHERE clause; this SQL is constructed to allow all
4525 * published posts, and all private posts to which the user has access.
4529 * @param string $post_type currently only supports 'post' or 'page'.
4530 * @return string SQL code that can be added to a where clause.
4532 function get_private_posts_cap_sql( $post_type ) {
4533 return get_posts_by_author_sql( $post_type, false );
4537 * Retrieve the post SQL based on capability, author, and type.
4539 * @see get_private_posts_cap_sql() for full description.
4542 * @param string $post_type Post type.
4543 * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
4544 * @param int $post_author Optional. Query posts having a single author ID.
4545 * @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false.
4546 * @return string SQL WHERE code that can be added to a query.
4548 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
4552 $post_type_obj = get_post_type_object( $post_type );
4553 if ( ! $post_type_obj )
4554 return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
4556 // This hook is deprecated. Why you'd want to use it, I dunno.
4557 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) )
4558 $cap = $post_type_obj->cap->read_private_posts;
4561 if ( null === $post_author ) {
4562 $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
4564 $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
4570 $sql .= "(post_status = 'publish'";
4572 // Only need to check the cap if $public_only is false
4573 if ( false === $public_only ) {
4574 if ( current_user_can( $cap ) ) {
4575 // Does the user have the capability to view private posts? Guess so.
4576 $sql .= " OR post_status = 'private'";
4577 } elseif ( is_user_logged_in() ) {
4578 // Users can view their own private posts.
4579 $id = get_current_user_id();
4580 if ( null === $post_author || ! $full ) {
4581 $sql .= " OR post_status = 'private' AND post_author = $id";
4582 } elseif ( $id == (int) $post_author ) {
4583 $sql .= " OR post_status = 'private'";
4594 * Retrieve the date that the last post was published.
4596 * The server timezone is the default and is the difference between GMT and
4597 * server time. The 'blog' value is the date when the last post was posted. The
4598 * 'gmt' is when the last post was posted in GMT formatted date.
4602 * @uses apply_filters() Calls 'get_lastpostdate' filter
4604 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4605 * @return string The date of the last post.
4607 function get_lastpostdate($timezone = 'server') {
4608 return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
4612 * Retrieve last post modified date depending on timezone.
4614 * The server timezone is the default and is the difference between GMT and
4615 * server time. The 'blog' value is just when the last post was modified. The
4616 * 'gmt' is when the last post was modified in GMT time.
4619 * @uses apply_filters() Calls 'get_lastpostmodified' filter
4621 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4622 * @return string The date the post was last modified.
4624 function get_lastpostmodified($timezone = 'server') {
4625 $lastpostmodified = _get_last_post_time( $timezone, 'modified' );
4627 $lastpostdate = get_lastpostdate($timezone);
4628 if ( $lastpostdate > $lastpostmodified )
4629 $lastpostmodified = $lastpostdate;
4631 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
4635 * Retrieve latest post date data based on timezone.
4640 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4641 * @param string $field Field to check. Can be 'date' or 'modified'.
4642 * @return string The date.
4644 function _get_last_post_time( $timezone, $field ) {
4647 if ( !in_array( $field, array( 'date', 'modified' ) ) )
4650 $timezone = strtolower( $timezone );
4652 $key = "lastpost{$field}:$timezone";
4654 $date = wp_cache_get( $key, 'timeinfo' );
4657 $add_seconds_server = date('Z');
4659 $post_types = get_post_types( array( 'public' => true ) );
4660 array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
4661 $post_types = "'" . implode( "', '", $post_types ) . "'";
4663 switch ( $timezone ) {
4665 $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
4668 $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
4671 $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
4676 wp_cache_set( $key, $date, 'timeinfo' );
4683 * Updates posts in cache.
4685 * @package WordPress
4689 * @param array $posts Array of post objects
4691 function update_post_cache( &$posts ) {
4695 foreach ( $posts as $post )
4696 wp_cache_add( $post->ID, $post, 'posts' );
4700 * Will clean the post in the cache.
4702 * Cleaning means delete from the cache of the post. Will call to clean the term
4703 * object cache associated with the post ID.
4705 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
4706 * wp_suspend_cache_invalidation().
4708 * @package WordPress
4712 * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
4714 * @param int|object $post Post ID or object to remove from the cache
4716 function clean_post_cache( $post ) {
4717 global $_wp_suspend_cache_invalidation, $wpdb;
4719 if ( ! empty( $_wp_suspend_cache_invalidation ) )
4722 $post = get_post( $post );
4723 if ( empty( $post ) )
4726 wp_cache_delete( $post->ID, 'posts' );
4727 wp_cache_delete( $post->ID, 'post_meta' );
4729 clean_object_term_cache( $post->ID, $post->post_type );
4731 wp_cache_delete( 'wp_get_archives', 'general' );
4733 do_action( 'clean_post_cache', $post->ID, $post );
4735 if ( is_post_type_hierarchical( $post->post_type ) )
4736 wp_cache_delete( 'get_pages', 'posts' );
4738 if ( 'page' == $post->post_type ) {
4739 wp_cache_delete( 'all_page_ids', 'posts' );
4740 do_action( 'clean_page_cache', $post->ID );
4743 wp_cache_set( 'last_changed', microtime(), 'posts' );
4747 * Call major cache updating functions for list of Post objects.
4749 * @package WordPress
4753 * @uses update_post_cache()
4754 * @uses update_object_term_cache()
4755 * @uses update_postmeta_cache()
4757 * @param array $posts Array of Post objects
4758 * @param string $post_type The post type of the posts in $posts. Default is 'post'.
4759 * @param bool $update_term_cache Whether to update the term cache. Default is true.
4760 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
4762 function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
4763 // No point in doing all this work if we didn't match any posts.
4767 update_post_cache($posts);
4769 $post_ids = array();
4770 foreach ( $posts as $post )
4771 $post_ids[] = $post->ID;
4776 if ( $update_term_cache ) {
4777 if ( is_array($post_type) ) {
4778 $ptypes = $post_type;
4779 } elseif ( 'any' == $post_type ) {
4780 // Just use the post_types in the supplied posts.
4781 foreach ( $posts as $post )
4782 $ptypes[] = $post->post_type;
4783 $ptypes = array_unique($ptypes);
4785 $ptypes = array($post_type);
4788 if ( ! empty($ptypes) )
4789 update_object_term_cache($post_ids, $ptypes);
4792 if ( $update_meta_cache )
4793 update_postmeta_cache($post_ids);
4797 * Updates metadata cache for list of post IDs.
4799 * Performs SQL query to retrieve the metadata for the post IDs and updates the
4800 * metadata cache for the posts. Therefore, the functions, which call this
4801 * function, do not need to perform SQL queries on their own.
4803 * @package WordPress
4807 * @param array $post_ids List of post IDs.
4808 * @return bool|array Returns false if there is nothing to update or an array of metadata.
4810 function update_postmeta_cache($post_ids) {
4811 return update_meta_cache('post', $post_ids);
4815 * Will clean the attachment in the cache.
4817 * Cleaning means delete from the cache. Optionally will clean the term
4818 * object cache associated with the attachment ID.
4820 * This function will not run if $_wp_suspend_cache_invalidation is not empty. See
4821 * wp_suspend_cache_invalidation().
4823 * @package WordPress
4827 * @uses do_action() Calls 'clean_attachment_cache' on $id.
4829 * @param int $id The attachment ID in the cache to clean
4830 * @param bool $clean_terms optional. Whether to clean terms cache
4832 function clean_attachment_cache($id, $clean_terms = false) {
4833 global $_wp_suspend_cache_invalidation;
4835 if ( !empty($_wp_suspend_cache_invalidation) )
4840 wp_cache_delete($id, 'posts');
4841 wp_cache_delete($id, 'post_meta');
4844 clean_object_term_cache($id, 'attachment');
4846 do_action('clean_attachment_cache', $id);
4854 * Hook for managing future post transitions to published.
4859 * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
4860 * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
4862 * @param string $new_status New post status
4863 * @param string $old_status Previous post status
4864 * @param object $post Object type containing the post information
4866 function _transition_post_status($new_status, $old_status, $post) {
4869 if ( $old_status != 'publish' && $new_status == 'publish' ) {
4870 // Reset GUID if transitioning to publish and it is empty
4871 if ( '' == get_the_guid($post->ID) )
4872 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
4873 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
4876 // If published posts changed clear the lastpostmodified cache
4877 if ( 'publish' == $new_status || 'publish' == $old_status) {
4878 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
4879 wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
4880 wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
4884 // Always clears the hook in case the post status bounced from future to draft.
4885 wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
4889 * Hook used to schedule publication for a post marked for the future.
4891 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
4896 * @param int $deprecated Not used. Can be set to null. Never implemented.
4897 * Not marked as deprecated with _deprecated_argument() as it conflicts with
4898 * wp_transition_post_status() and the default filter for _future_post_hook().
4899 * @param object $post Object type containing the post information
4901 function _future_post_hook( $deprecated, $post ) {
4902 wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
4903 wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
4907 * Hook to schedule pings and enclosures when a post is published.
4911 * @uses XMLRPC_REQUEST and WP_IMPORTING constants.
4912 * @uses do_action() Calls 'xmlrpc_publish_post' on post ID if XMLRPC_REQUEST is defined.
4914 * @param int $post_id The ID in the database table of the post being published
4916 function _publish_post_hook($post_id) {
4917 if ( defined('XMLRPC_REQUEST') )
4918 do_action('xmlrpc_publish_post', $post_id);
4920 if ( defined('WP_IMPORTING') )
4923 if ( get_option('default_pingback_flag') )
4924 add_post_meta( $post_id, '_pingme', '1' );
4925 add_post_meta( $post_id, '_encloseme', '1' );
4927 wp_schedule_single_event(time(), 'do_pings');
4931 * Returns the post's parent's post_ID
4935 * @param int $post_id
4937 * @return int|bool false on error
4939 function wp_get_post_parent_id( $post_ID ) {
4940 $post = get_post( $post_ID );
4941 if ( !$post || is_wp_error( $post ) )
4943 return (int) $post->post_parent;
4947 * Checks the given subset of the post hierarchy for hierarchy loops.
4948 * Prevents loops from forming and breaks those that it finds.
4950 * Attached to the wp_insert_post_parent filter.
4953 * @uses wp_find_hierarchy_loop()
4955 * @param int $post_parent ID of the parent for the post we're checking.
4956 * @param int $post_ID ID of the post we're checking.
4958 * @return int The new post_parent for the post.
4960 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
4961 // Nothing fancy here - bail
4962 if ( !$post_parent )
4965 // New post can't cause a loop
4966 if ( empty( $post_ID ) )
4967 return $post_parent;
4969 // Can't be its own parent
4970 if ( $post_parent == $post_ID )
4973 // Now look for larger loops
4975 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
4976 return $post_parent; // No loop
4978 // Setting $post_parent to the given value causes a loop
4979 if ( isset( $loop[$post_ID] ) )
4982 // There's a loop, but it doesn't contain $post_ID. Break the loop.
4983 foreach ( array_keys( $loop ) as $loop_member )
4984 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
4986 return $post_parent;
4990 * Sets a post thumbnail.
4994 * @param int|object $post Post ID or object where thumbnail should be attached.
4995 * @param int $thumbnail_id Thumbnail to attach.
4996 * @return bool True on success, false on failure.
4998 function set_post_thumbnail( $post, $thumbnail_id ) {
4999 $post = get_post( $post );
5000 $thumbnail_id = absint( $thumbnail_id );
5001 if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
5002 if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
5003 return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
5005 return delete_post_meta( $post->ID, '_thumbnail_id' );
5011 * Removes a post thumbnail.
5015 * @param int|object $post Post ID or object where thumbnail should be removed from.
5016 * @return bool True on success, false on failure.
5018 function delete_post_thumbnail( $post ) {
5019 $post = get_post( $post );
5021 return delete_post_meta( $post->ID, '_thumbnail_id' );
5026 * Deletes auto-drafts for new posts that are > 7 days old
5030 function wp_delete_auto_drafts() {
5033 // Cleanup old auto-drafts more than 7 days old
5034 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
5035 foreach ( (array) $old_posts as $delete )
5036 wp_delete_post( $delete, true ); // Force delete
5040 * Update the custom taxonomies' term counts when a post's status is changed. For example, default posts term counts (for custom taxonomies) don't include private / draft posts.
5043 * @param string $new_status
5044 * @param string $old_status
5045 * @param object $post
5048 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
5049 // Update counts for the post's terms.
5050 foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
5051 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
5052 wp_update_term_count( $tt_ids, $taxonomy );
5057 * Adds any posts from the given ids to the cache that do not already exist in cache
5063 * @param array $post_ids ID list
5064 * @param bool $update_term_cache Whether to update the term cache. Default is true.
5065 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
5067 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
5070 $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
5071 if ( !empty( $non_cached_ids ) ) {
5072 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
5074 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );