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 * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
1133 * * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
1134 * capabilities, e.g. array('story', 'stories').
1135 * - capabilities - Array of capabilities for this post type.
1136 * * By default the capability_type is used as a base to construct capabilities.
1137 * * You can see accepted values in {@link get_post_type_capabilities()}.
1138 * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
1139 * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
1140 * * See {@link add_post_type_support()} for documentation.
1141 * - register_meta_box_cb - Provide a callback function that sets up the meta boxes
1142 * for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
1143 * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
1144 * * Default is no taxonomies.
1145 * * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
1146 * - has_archive - True to enable post type archives. Default is false.
1147 * * Will generate the proper rewrite rules if rewrite is enabled.
1148 * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
1149 * * To prevent rewrite, set to false.
1150 * * To specify rewrite rules, an array can be passed with any of these keys
1151 * * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
1152 * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
1153 * * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
1154 * * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
1155 * * 'ep_mask' => const Assign an endpoint mask.
1156 * * If not specified and permalink_epmask is set, inherits from permalink_epmask.
1157 * * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
1158 * - query_var - Sets the query_var key for this post type. Defaults to $post_type key
1159 * * If false, a post type cannot be loaded at ?{query_var}={post_slug}
1160 * * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
1161 * - can_export - Allows this post type to be exported. Defaults to true.
1162 * - delete_with_user - Whether to delete posts of this type when deleting a user.
1163 * * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
1164 * * If false, posts of this type belonging to the user will *not* be trashed or deleted.
1165 * * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
1166 * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
1167 * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
1170 * @uses $wp_post_types Inserts new post type object into the list
1171 * @uses $wp_rewrite Gets default feeds
1172 * @uses $wp Adds query vars
1174 * @param string $post_type Post type key, must not exceed 20 characters.
1175 * @param array|string $args See optional args description above.
1176 * @return object|WP_Error the registered post type object, or an error object.
1178 function register_post_type( $post_type, $args = array() ) {
1179 global $wp_post_types, $wp_rewrite, $wp;
1181 if ( ! is_array( $wp_post_types ) )
1182 $wp_post_types = array();
1184 // Args prefixed with an underscore are reserved for internal use.
1186 'labels' => array(),
1187 'description' => '',
1189 'hierarchical' => false,
1190 'exclude_from_search' => null,
1191 'publicly_queryable' => null,
1193 'show_in_menu' => null,
1194 'show_in_nav_menus' => null,
1195 'show_in_admin_bar' => null,
1196 'menu_position' => null,
1197 'menu_icon' => null,
1198 'capability_type' => 'post',
1199 'capabilities' => array(),
1200 'map_meta_cap' => null,
1201 'supports' => array(),
1202 'register_meta_box_cb' => null,
1203 'taxonomies' => array(),
1204 'has_archive' => false,
1206 'query_var' => true,
1207 'can_export' => true,
1208 'delete_with_user' => null,
1209 '_builtin' => false,
1210 '_edit_link' => 'post.php?post=%d',
1212 $args = wp_parse_args( $args, $defaults );
1213 $args = (object) $args;
1215 $post_type = sanitize_key( $post_type );
1216 $args->name = $post_type;
1218 if ( strlen( $post_type ) > 20 )
1219 return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
1221 // If not set, default to the setting for public.
1222 if ( null === $args->publicly_queryable )
1223 $args->publicly_queryable = $args->public;
1225 // If not set, default to the setting for public.
1226 if ( null === $args->show_ui )
1227 $args->show_ui = $args->public;
1229 // If not set, default to the setting for show_ui.
1230 if ( null === $args->show_in_menu || ! $args->show_ui )
1231 $args->show_in_menu = $args->show_ui;
1233 // If not set, default to the whether the full UI is shown.
1234 if ( null === $args->show_in_admin_bar )
1235 $args->show_in_admin_bar = true === $args->show_in_menu;
1237 // If not set, default to the setting for public.
1238 if ( null === $args->show_in_nav_menus )
1239 $args->show_in_nav_menus = $args->public;
1241 // If not set, default to true if not public, false if public.
1242 if ( null === $args->exclude_from_search )
1243 $args->exclude_from_search = !$args->public;
1245 // Back compat with quirky handling in version 3.0. #14122
1246 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1247 $args->map_meta_cap = true;
1249 // If not set, default to false.
1250 if ( null === $args->map_meta_cap )
1251 $args->map_meta_cap = false;
1253 $args->cap = get_post_type_capabilities( $args );
1254 unset( $args->capabilities );
1256 if ( is_array( $args->capability_type ) )
1257 $args->capability_type = $args->capability_type[0];
1259 if ( ! empty( $args->supports ) ) {
1260 add_post_type_support( $post_type, $args->supports );
1261 unset( $args->supports );
1262 } elseif ( false !== $args->supports ) {
1263 // Add default features
1264 add_post_type_support( $post_type, array( 'title', 'editor' ) );
1267 if ( false !== $args->query_var && ! empty( $wp ) ) {
1268 if ( true === $args->query_var )
1269 $args->query_var = $post_type;
1271 $args->query_var = sanitize_title_with_dashes( $args->query_var );
1272 $wp->add_query_var( $args->query_var );
1275 if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
1276 if ( ! is_array( $args->rewrite ) )
1277 $args->rewrite = array();
1278 if ( empty( $args->rewrite['slug'] ) )
1279 $args->rewrite['slug'] = $post_type;
1280 if ( ! isset( $args->rewrite['with_front'] ) )
1281 $args->rewrite['with_front'] = true;
1282 if ( ! isset( $args->rewrite['pages'] ) )
1283 $args->rewrite['pages'] = true;
1284 if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1285 $args->rewrite['feeds'] = (bool) $args->has_archive;
1286 if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1287 if ( isset( $args->permalink_epmask ) )
1288 $args->rewrite['ep_mask'] = $args->permalink_epmask;
1290 $args->rewrite['ep_mask'] = EP_PERMALINK;
1293 if ( $args->hierarchical )
1294 add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
1296 add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
1298 if ( $args->has_archive ) {
1299 $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1300 if ( $args->rewrite['with_front'] )
1301 $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1303 $archive_slug = $wp_rewrite->root . $archive_slug;
1305 add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1306 if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1307 $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1308 add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1309 add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1311 if ( $args->rewrite['pages'] )
1312 add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1315 $permastruct_args = $args->rewrite;
1316 $permastruct_args['feed'] = $permastruct_args['feeds'];
1317 add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
1320 if ( $args->register_meta_box_cb )
1321 add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
1323 $args->labels = get_post_type_labels( $args );
1324 $args->label = $args->labels->name;
1326 $wp_post_types[ $post_type ] = $args;
1328 add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1330 foreach ( $args->taxonomies as $taxonomy ) {
1331 register_taxonomy_for_object_type( $taxonomy, $post_type );
1334 do_action( 'registered_post_type', $post_type, $args );
1340 * Builds an object with all post type capabilities out of a post type object
1342 * Post type capabilities use the 'capability_type' argument as a base, if the
1343 * capability is not set in the 'capabilities' argument array or if the
1344 * 'capabilities' argument is not supplied.
1346 * The capability_type argument can optionally be registered as an array, with
1347 * the first value being singular and the second plural, e.g. array('story, 'stories')
1348 * Otherwise, an 's' will be added to the value for the plural form. After
1349 * registration, capability_type will always be a string of the singular value.
1351 * By default, seven keys are accepted as part of the capabilities array:
1353 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1354 * generally mapped to corresponding primitive capabilities depending on the
1355 * context, which would be the post being edited/read/deleted and the user or
1356 * role being checked. Thus these capabilities would generally not be granted
1357 * directly to users or roles.
1359 * - edit_posts - Controls whether objects of this post type can be edited.
1360 * - edit_others_posts - Controls whether objects of this type owned by other users
1361 * can be edited. If the post type does not support an author, then this will
1362 * behave like edit_posts.
1363 * - publish_posts - Controls publishing objects of this post type.
1364 * - read_private_posts - Controls whether private objects can be read.
1366 * These four primitive capabilities are checked in core in various locations.
1367 * There are also seven other primitive capabilities which are not referenced
1368 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1369 * meta capabilities and translates them into one or more primitive capabilities
1370 * that must then be checked against the user or role, depending on the context.
1372 * - read - Controls whether objects of this post type can be read.
1373 * - delete_posts - Controls whether objects of this post type can be deleted.
1374 * - delete_private_posts - Controls whether private objects can be deleted.
1375 * - delete_published_posts - Controls whether published objects can be deleted.
1376 * - delete_others_posts - Controls whether objects owned by other users can be
1377 * can be deleted. If the post type does not support an author, then this will
1378 * behave like delete_posts.
1379 * - edit_private_posts - Controls whether private objects can be edited.
1380 * - edit_published_posts - Controls whether published objects can be edited.
1382 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1383 * only assigned by default if the post type is registered with the 'map_meta_cap'
1384 * argument set to true (default is false).
1386 * @see map_meta_cap()
1389 * @param object $args Post type registration arguments
1390 * @return object object with all the capabilities as member variables
1392 function get_post_type_capabilities( $args ) {
1393 if ( ! is_array( $args->capability_type ) )
1394 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1396 // Singular base for meta capabilities, plural base for primitive capabilities.
1397 list( $singular_base, $plural_base ) = $args->capability_type;
1399 $default_capabilities = array(
1400 // Meta capabilities
1401 'edit_post' => 'edit_' . $singular_base,
1402 'read_post' => 'read_' . $singular_base,
1403 'delete_post' => 'delete_' . $singular_base,
1404 // Primitive capabilities used outside of map_meta_cap():
1405 'edit_posts' => 'edit_' . $plural_base,
1406 'edit_others_posts' => 'edit_others_' . $plural_base,
1407 'publish_posts' => 'publish_' . $plural_base,
1408 'read_private_posts' => 'read_private_' . $plural_base,
1411 // Primitive capabilities used within map_meta_cap():
1412 if ( $args->map_meta_cap ) {
1413 $default_capabilities_for_mapping = array(
1415 'delete_posts' => 'delete_' . $plural_base,
1416 'delete_private_posts' => 'delete_private_' . $plural_base,
1417 'delete_published_posts' => 'delete_published_' . $plural_base,
1418 'delete_others_posts' => 'delete_others_' . $plural_base,
1419 'edit_private_posts' => 'edit_private_' . $plural_base,
1420 'edit_published_posts' => 'edit_published_' . $plural_base,
1422 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1425 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1427 // Post creation capability simply maps to edit_posts by default:
1428 if ( ! isset( $capabilities['create_posts'] ) )
1429 $capabilities['create_posts'] = $capabilities['edit_posts'];
1431 // Remember meta capabilities for future reference.
1432 if ( $args->map_meta_cap )
1433 _post_type_meta_capabilities( $capabilities );
1435 return (object) $capabilities;
1439 * Stores or returns a list of post type meta caps for map_meta_cap().
1444 function _post_type_meta_capabilities( $capabilities = null ) {
1445 static $meta_caps = array();
1446 if ( null === $capabilities )
1448 foreach ( $capabilities as $core => $custom ) {
1449 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1450 $meta_caps[ $custom ] = $core;
1455 * Builds an object with all post type labels out of a post type object
1457 * Accepted keys of the label array in the post type object:
1458 * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
1459 * - singular_name - name for one object of this post type. Default is Post/Page
1460 * - 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>
1461 * - add_new_item - Default is Add New Post/Add New Page
1462 * - edit_item - Default is Edit Post/Edit Page
1463 * - new_item - Default is New Post/New Page
1464 * - view_item - Default is View Post/View Page
1465 * - search_items - Default is Search Posts/Search Pages
1466 * - not_found - Default is No posts found/No pages found
1467 * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
1468 * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
1469 * - all_items - String for the submenu. Default is All Posts/All Pages
1470 * - menu_name - Default is the same as <code>name</code>
1472 * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
1477 * @param object $post_type_object
1478 * @return object object with all the labels as member variables
1480 function get_post_type_labels( $post_type_object ) {
1481 $nohier_vs_hier_defaults = array(
1482 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1483 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1484 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1485 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1486 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1487 'new_item' => array( __('New Post'), __('New Page') ),
1488 'view_item' => array( __('View Post'), __('View Page') ),
1489 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1490 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1491 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1492 'parent_item_colon' => array( null, __('Parent Page:') ),
1493 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
1495 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1497 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1499 $post_type = $post_type_object->name;
1500 return apply_filters( "post_type_labels_{$post_type}", $labels );
1504 * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
1509 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1510 $object->labels = (array) $object->labels;
1512 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1513 $object->labels['name'] = $object->label;
1515 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1516 $object->labels['singular_name'] = $object->labels['name'];
1518 if ( ! isset( $object->labels['name_admin_bar'] ) )
1519 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1521 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1522 $object->labels['menu_name'] = $object->labels['name'];
1524 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1525 $object->labels['all_items'] = $object->labels['menu_name'];
1527 foreach ( $nohier_vs_hier_defaults as $key => $value )
1528 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1530 $labels = array_merge( $defaults, $object->labels );
1531 return (object)$labels;
1535 * Adds submenus for post types.
1540 function _add_post_type_submenus() {
1541 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1542 $ptype_obj = get_post_type_object( $ptype );
1544 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1546 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" );
1549 add_action( 'admin_menu', '_add_post_type_submenus' );
1552 * Register support of certain features for a post type.
1554 * All features are directly associated with a functional area of the edit screen, such as the
1555 * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
1556 * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
1558 * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
1559 * and the 'comments' feature dictates whether the comments count will show on the edit screen.
1562 * @param string $post_type The post type for which to add the feature
1563 * @param string|array $feature the feature being added, can be an array of feature strings or a single string
1565 function add_post_type_support( $post_type, $feature ) {
1566 global $_wp_post_type_features;
1568 $features = (array) $feature;
1569 foreach ($features as $feature) {
1570 if ( func_num_args() == 2 )
1571 $_wp_post_type_features[$post_type][$feature] = true;
1573 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1578 * Remove support for a feature from a post type.
1581 * @param string $post_type The post type for which to remove the feature
1582 * @param string $feature The feature being removed
1584 function remove_post_type_support( $post_type, $feature ) {
1585 global $_wp_post_type_features;
1587 if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
1588 unset( $_wp_post_type_features[$post_type][$feature] );
1592 * Get all the post type features
1595 * @param string $post_type The post type
1599 function get_all_post_type_supports( $post_type ) {
1600 global $_wp_post_type_features;
1602 if ( isset( $_wp_post_type_features[$post_type] ) )
1603 return $_wp_post_type_features[$post_type];
1609 * Checks a post type's support for a given feature
1612 * @param string $post_type The post type being checked
1613 * @param string $feature the feature being checked
1617 function post_type_supports( $post_type, $feature ) {
1618 global $_wp_post_type_features;
1620 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1624 * Updates the post type for the post ID.
1626 * The page or post cache will be cleaned for the post ID.
1632 * @param int $post_id Post ID to change post type. Not actually optional.
1633 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
1635 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
1637 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1640 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1641 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1643 clean_post_cache( $post_id );
1649 * Retrieve list of latest posts or posts matching criteria.
1651 * The defaults are as follows:
1652 * 'numberposts' - Default is 5. Total number of posts to retrieve.
1653 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
1654 * 'category' - What category to pull the posts from.
1655 * 'orderby' - Default is 'post_date'. How to order the posts.
1656 * 'order' - Default is 'DESC'. The order to retrieve the posts.
1657 * 'include' - See {@link WP_Query::query()} for more.
1658 * 'exclude' - See {@link WP_Query::query()} for more.
1659 * 'meta_key' - See {@link WP_Query::query()} for more.
1660 * 'meta_value' - See {@link WP_Query::query()} for more.
1661 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
1662 * 'post_parent' - The parent of the post or post type.
1663 * 'post_status' - Default is 'publish'. Post status to retrieve.
1666 * @uses WP_Query::query() See for more default arguments and information.
1667 * @link http://codex.wordpress.org/Template_Tags/get_posts
1669 * @param array $args Optional. Overrides defaults.
1670 * @return array List of posts.
1672 function get_posts($args = null) {
1674 'numberposts' => 5, 'offset' => 0,
1675 'category' => 0, 'orderby' => 'post_date',
1676 'order' => 'DESC', 'include' => array(),
1677 'exclude' => array(), 'meta_key' => '',
1678 'meta_value' =>'', 'post_type' => 'post',
1679 'suppress_filters' => true
1682 $r = wp_parse_args( $args, $defaults );
1683 if ( empty( $r['post_status'] ) )
1684 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1685 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1686 $r['posts_per_page'] = $r['numberposts'];
1687 if ( ! empty($r['category']) )
1688 $r['cat'] = $r['category'];
1689 if ( ! empty($r['include']) ) {
1690 $incposts = wp_parse_id_list( $r['include'] );
1691 $r['posts_per_page'] = count($incposts); // only the number of posts included
1692 $r['post__in'] = $incposts;
1693 } elseif ( ! empty($r['exclude']) )
1694 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1696 $r['ignore_sticky_posts'] = true;
1697 $r['no_found_rows'] = true;
1699 $get_posts = new WP_Query;
1700 return $get_posts->query($r);
1705 // Post meta functions
1709 * Add meta data field to a post.
1711 * Post meta data is called "Custom Fields" on the Administration Screen.
1714 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
1716 * @param int $post_id Post ID.
1717 * @param string $meta_key Metadata name.
1718 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1719 * @param bool $unique Optional, default is false. Whether the same key should not be added.
1720 * @return int|bool Meta ID on success, false on failure.
1722 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
1723 // make sure meta is added to the post, not a revision
1724 if ( $the_post = wp_is_post_revision($post_id) )
1725 $post_id = $the_post;
1727 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1731 * Remove metadata matching criteria from a post.
1733 * You can match based on the key, or key and value. Removing based on key and
1734 * value, will keep from removing duplicate metadata with the same key. It also
1735 * allows removing all metadata matching key, if needed.
1738 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
1740 * @param int $post_id post ID
1741 * @param string $meta_key Metadata name.
1742 * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar.
1743 * @return bool True on success, false on failure.
1745 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
1746 // make sure meta is added to the post, not a revision
1747 if ( $the_post = wp_is_post_revision($post_id) )
1748 $post_id = $the_post;
1750 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1754 * Retrieve post meta field for a post.
1757 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
1759 * @param int $post_id Post ID.
1760 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1761 * @param bool $single Whether to return a single value.
1762 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1765 function get_post_meta($post_id, $key = '', $single = false) {
1766 return get_metadata('post', $post_id, $key, $single);
1770 * Update post meta field based on post ID.
1772 * Use the $prev_value parameter to differentiate between meta fields with the
1773 * same key and post ID.
1775 * If the meta field for the post does not exist, it will be added.
1778 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
1780 * @param int $post_id Post ID.
1781 * @param string $meta_key Metadata key.
1782 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1783 * @param mixed $prev_value Optional. Previous value to check before removing.
1784 * @return bool True on success, false on failure.
1786 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
1787 // make sure meta is added to the post, not a revision
1788 if ( $the_post = wp_is_post_revision($post_id) )
1789 $post_id = $the_post;
1791 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1795 * Delete everything from post meta matching meta key.
1799 * @param string $post_meta_key Key to search for when deleting.
1800 * @return bool Whether the post meta key was deleted from the database
1802 function delete_post_meta_by_key($post_meta_key) {
1803 return delete_metadata( 'post', null, $post_meta_key, '', true );
1807 * Retrieve post meta fields, based on post ID.
1809 * The post meta fields are retrieved from the cache where possible,
1810 * so the function is optimized to be called more than once.
1813 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
1815 * @param int $post_id Post ID.
1818 function get_post_custom( $post_id = 0 ) {
1819 $post_id = absint( $post_id );
1821 $post_id = get_the_ID();
1823 return get_post_meta( $post_id );
1827 * Retrieve meta field names for a post.
1829 * If there are no meta fields, then nothing (null) will be returned.
1832 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
1834 * @param int $post_id post ID
1835 * @return array|null Either array of the keys, or null if keys could not be retrieved.
1837 function get_post_custom_keys( $post_id = 0 ) {
1838 $custom = get_post_custom( $post_id );
1840 if ( !is_array($custom) )
1843 if ( $keys = array_keys($custom) )
1848 * Retrieve values for a custom post field.
1850 * The parameters must not be considered optional. All of the post meta fields
1851 * will be retrieved and only the meta field key values returned.
1854 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
1856 * @param string $key Meta field key.
1857 * @param int $post_id Post ID
1858 * @return array Meta field values.
1860 function get_post_custom_values( $key = '', $post_id = 0 ) {
1864 $custom = get_post_custom($post_id);
1866 return isset($custom[$key]) ? $custom[$key] : null;
1870 * Check if post is sticky.
1872 * Sticky posts should remain at the top of The Loop. If the post ID is not
1873 * given, then The Loop ID for the current post will be used.
1877 * @param int $post_id Optional. Post ID.
1878 * @return bool Whether post is sticky.
1880 function is_sticky( $post_id = 0 ) {
1881 $post_id = absint( $post_id );
1884 $post_id = get_the_ID();
1886 $stickies = get_option( 'sticky_posts' );
1888 if ( ! is_array( $stickies ) )
1891 if ( in_array( $post_id, $stickies ) )
1898 * Sanitize every post field.
1900 * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
1903 * @uses sanitize_post_field() Used to sanitize the fields.
1905 * @param object|WP_Post|array $post The Post Object or Array
1906 * @param string $context Optional, default is 'display'. How to sanitize post fields.
1907 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post)
1909 function sanitize_post($post, $context = 'display') {
1910 if ( is_object($post) ) {
1911 // Check if post already filtered for this context
1912 if ( isset($post->filter) && $context == $post->filter )
1914 if ( !isset($post->ID) )
1916 foreach ( array_keys(get_object_vars($post)) as $field )
1917 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1918 $post->filter = $context;
1920 // Check if post already filtered for this context
1921 if ( isset($post['filter']) && $context == $post['filter'] )
1923 if ( !isset($post['ID']) )
1925 foreach ( array_keys($post) as $field )
1926 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1927 $post['filter'] = $context;
1933 * Sanitize post field based on context.
1935 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1936 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1937 * when calling filters.
1940 * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
1941 * $post_id if $context == 'edit' and field name prefix == 'post_'.
1943 * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
1944 * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
1945 * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
1947 * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
1948 * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
1949 * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
1950 * 'edit' and 'db' and field name prefix != 'post_'.
1952 * @param string $field The Post Object field name.
1953 * @param mixed $value The Post Object value.
1954 * @param int $post_id Post ID.
1955 * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
1956 * 'attribute' and 'js'.
1957 * @return mixed Sanitized value.
1959 function sanitize_post_field($field, $value, $post_id, $context) {
1960 $int_fields = array('ID', 'post_parent', 'menu_order');
1961 if ( in_array($field, $int_fields) )
1962 $value = (int) $value;
1964 // Fields which contain arrays of ints.
1965 $array_int_fields = array( 'ancestors' );
1966 if ( in_array($field, $array_int_fields) ) {
1967 $value = array_map( 'absint', $value);
1971 if ( 'raw' == $context )
1975 if ( false !== strpos($field, 'post_') ) {
1977 $field_no_prefix = str_replace('post_', '', $field);
1980 if ( 'edit' == $context ) {
1981 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1984 $value = apply_filters("edit_{$field}", $value, $post_id);
1986 $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
1988 $value = apply_filters("edit_post_{$field}", $value, $post_id);
1991 if ( in_array($field, $format_to_edit) ) {
1992 if ( 'post_content' == $field )
1993 $value = format_to_edit($value, user_can_richedit());
1995 $value = format_to_edit($value);
1997 $value = esc_attr($value);
1999 } else if ( 'db' == $context ) {
2001 $value = apply_filters("pre_{$field}", $value);
2002 $value = apply_filters("{$field_no_prefix}_save_pre", $value);
2004 $value = apply_filters("pre_post_{$field}", $value);
2005 $value = apply_filters("{$field}_pre", $value);
2008 // Use display filters by default.
2010 $value = apply_filters($field, $value, $post_id, $context);
2012 $value = apply_filters("post_{$field}", $value, $post_id, $context);
2015 if ( 'attribute' == $context )
2016 $value = esc_attr($value);
2017 else if ( 'js' == $context )
2018 $value = esc_js($value);
2024 * Make a post sticky.
2026 * Sticky posts should be displayed at the top of the front page.
2030 * @param int $post_id Post ID.
2032 function stick_post($post_id) {
2033 $stickies = get_option('sticky_posts');
2035 if ( !is_array($stickies) )
2036 $stickies = array($post_id);
2038 if ( ! in_array($post_id, $stickies) )
2039 $stickies[] = $post_id;
2041 update_option('sticky_posts', $stickies);
2047 * Sticky posts should be displayed at the top of the front page.
2051 * @param int $post_id Post ID.
2053 function unstick_post($post_id) {
2054 $stickies = get_option('sticky_posts');
2056 if ( !is_array($stickies) )
2059 if ( ! in_array($post_id, $stickies) )
2062 $offset = array_search($post_id, $stickies);
2063 if ( false === $offset )
2066 array_splice($stickies, $offset, 1);
2068 update_option('sticky_posts', $stickies);
2072 * Count number of posts of a post type and if user has permissions to view.
2074 * This function provides an efficient method of finding the amount of post's
2075 * type a blog has. Another method is to count the amount of items in
2076 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2077 * when developing for 2.5+, use this function instead.
2079 * The $perm parameter checks for 'readable' value and if the user can read
2080 * private posts, it will display that for the user that is signed in.
2082 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
2086 * @param string $type Optional. Post type to retrieve count
2087 * @param string $perm Optional. 'readable' or empty.
2088 * @return object Number of posts for each status
2090 function wp_count_posts( $type = 'post', $perm = '' ) {
2093 if ( ! post_type_exists( $type ) )
2094 return new stdClass;
2096 $user = wp_get_current_user();
2098 $cache_key = 'posts-' . $type;
2100 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2101 if ( 'readable' == $perm && is_user_logged_in() ) {
2102 $post_type_object = get_post_type_object($type);
2103 if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
2104 $cache_key .= '_' . $perm . '_' . $user->ID;
2105 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
2108 $query .= ' GROUP BY post_status';
2110 $counts = wp_cache_get( $cache_key, 'counts' );
2111 if ( false === $counts ) {
2112 $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2113 $counts = array_fill_keys( get_post_stati(), 0 );
2115 foreach ( $results as $row )
2116 $counts[ $row['post_status'] ] = $row['num_posts'];
2118 $counts = (object) $counts;
2119 wp_cache_set( $cache_key, $counts, 'counts' );
2123 * Modify returned post counts by status for the current post type.
2127 * @param object $counts An object containing the current post_type's post counts by status.
2128 * @param string $type The post type.
2129 * @param string $perm The permission to determine if the posts are 'readable' by the current user.
2131 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2135 * Count number of attachments for the mime type(s).
2137 * If you set the optional mime_type parameter, then an array will still be
2138 * returned, but will only have the item you are looking for. It does not give
2139 * you the number of attachments that are children of a post. You can get that
2140 * by counting the number of children that post has.
2144 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
2145 * @return array Number of posts for each mime type.
2147 function wp_count_attachments( $mime_type = '' ) {
2150 $and = wp_post_mime_type_where( $mime_type );
2151 $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 );
2154 foreach( (array) $count as $row ) {
2155 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2157 $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2160 * Modify returned attachment counts by mime type.
2164 * @param object $counts An object containing the attachment counts by mime type.
2165 * @param string $mime_type The mime type pattern used to filter the attachments counted.
2167 return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2171 * Get default post mime types
2177 function get_post_mime_types() {
2178 $post_mime_types = array( // array( adj, noun )
2179 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2180 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2181 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2184 return apply_filters('post_mime_types', $post_mime_types);
2188 * Check a MIME-Type against a list.
2190 * If the wildcard_mime_types parameter is a string, it must be comma separated
2191 * list. If the real_mime_types is a string, it is also comma separated to
2196 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
2197 * flash (same as *flash*).
2198 * @param string|array $real_mime_types post_mime_type values
2199 * @return array array(wildcard=>array(real types))
2201 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
2203 if ( is_string($wildcard_mime_types) )
2204 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
2205 if ( is_string($real_mime_types) )
2206 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
2207 $wild = '[-._a-z0-9]*';
2208 foreach ( (array) $wildcard_mime_types as $type ) {
2209 $type = str_replace('*', $wild, $type);
2210 $patternses[1][$type] = "^$type$";
2211 if ( false === strpos($type, '/') ) {
2212 $patternses[2][$type] = "^$type/";
2213 $patternses[3][$type] = $type;
2217 foreach ( $patternses as $patterns )
2218 foreach ( $patterns as $type => $pattern )
2219 foreach ( (array) $real_mime_types as $real )
2220 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
2221 $matches[$type][] = $real;
2226 * Convert MIME types into SQL.
2230 * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
2231 * @param string $table_alias Optional. Specify a table alias, if needed.
2232 * @return string The SQL AND clause for mime searching.
2234 function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
2236 $wildcards = array('', '%', '%/%');
2237 if ( is_string($post_mime_types) )
2238 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2239 foreach ( (array) $post_mime_types as $mime_type ) {
2240 $mime_type = preg_replace('/\s/', '', $mime_type);
2241 $slashpos = strpos($mime_type, '/');
2242 if ( false !== $slashpos ) {
2243 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2244 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2245 if ( empty($mime_subgroup) )
2246 $mime_subgroup = '*';
2248 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2249 $mime_pattern = "$mime_group/$mime_subgroup";
2251 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2252 if ( false === strpos($mime_pattern, '*') )
2253 $mime_pattern .= '/*';
2256 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2258 if ( in_array( $mime_type, $wildcards ) )
2261 if ( false !== strpos($mime_pattern, '%') )
2262 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2264 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2266 if ( !empty($wheres) )
2267 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2272 * Trashes or deletes a post or page.
2274 * When the post and page is permanently deleted, everything that is tied to it is deleted also.
2275 * This includes comments, post meta fields, and terms associated with the post.
2277 * The post or page is moved to trash instead of permanently deleted unless trash is
2278 * disabled, item is already in the trash, or $force_delete is true.
2281 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
2282 * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
2283 * @uses wp_delete_attachment() if post type is 'attachment'.
2284 * @uses wp_trash_post() if item should be trashed.
2286 * @param int $postid Post ID.
2287 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
2288 * @return mixed False on failure
2290 function wp_delete_post( $postid = 0, $force_delete = false ) {
2293 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2296 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2297 return wp_trash_post($postid);
2299 if ( $post->post_type == 'attachment' )
2300 return wp_delete_attachment( $postid, $force_delete );
2302 do_action('before_delete_post', $postid);
2304 delete_post_meta($postid,'_wp_trash_meta_status');
2305 delete_post_meta($postid,'_wp_trash_meta_time');
2307 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2309 $parent_data = array( 'post_parent' => $post->post_parent );
2310 $parent_where = array( 'post_parent' => $postid );
2312 if ( is_post_type_hierarchical( $post->post_type ) ) {
2313 // Point children of this page to its parent, also clean the cache of affected children
2314 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2315 $children = $wpdb->get_results( $children_query );
2317 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2320 // Do raw query. wp_get_post_revisions() is filtered
2321 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2322 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2323 foreach ( $revision_ids as $revision_id )
2324 wp_delete_post_revision( $revision_id );
2326 // Point all attachments to this post up one level
2327 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2329 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2330 foreach ( $comment_ids as $comment_id )
2331 wp_delete_comment( $comment_id, true );
2333 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2334 foreach ( $post_meta_ids as $mid )
2335 delete_metadata_by_mid( 'post', $mid );
2337 do_action( 'delete_post', $postid );
2338 $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2339 do_action( 'deleted_post', $postid );
2341 clean_post_cache( $post );
2343 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2344 foreach ( $children as $child )
2345 clean_post_cache( $child );
2348 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2350 do_action('after_delete_post', $postid);
2356 * Resets the page_on_front, show_on_front, and page_for_post settings when a
2357 * linked page is deleted or trashed.
2359 * Also ensures the post is no longer sticky.
2365 function _reset_front_page_settings_for_post( $post_id ) {
2366 $post = get_post( $post_id );
2367 if ( 'page' == $post->post_type ) {
2368 // If the page is defined in option page_on_front or post_for_posts,
2369 // adjust the corresponding options
2370 if ( get_option( 'page_on_front' ) == $post->ID ) {
2371 update_option( 'show_on_front', 'posts' );
2372 update_option( 'page_on_front', 0 );
2374 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2375 delete_option( 'page_for_posts', 0 );
2378 unstick_post( $post->ID );
2380 add_action( 'before_delete_post', '_reset_front_page_settings_for_post' );
2381 add_action( 'wp_trash_post', '_reset_front_page_settings_for_post' );
2384 * Moves a post or page to the Trash
2386 * If trash is disabled, the post or page is permanently deleted.
2389 * @uses do_action() on 'trash_post' before trashing
2390 * @uses do_action() on 'trashed_post' after trashing
2391 * @uses wp_delete_post() if trash is disabled
2393 * @param int $post_id Post ID.
2394 * @return mixed False on failure
2396 function wp_trash_post($post_id = 0) {
2397 if ( !EMPTY_TRASH_DAYS )
2398 return wp_delete_post($post_id, true);
2400 if ( !$post = get_post($post_id, ARRAY_A) )
2403 if ( $post['post_status'] == 'trash' )
2406 do_action('wp_trash_post', $post_id);
2408 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2409 add_post_meta($post_id,'_wp_trash_meta_time', time());
2411 $post['post_status'] = 'trash';
2412 wp_insert_post($post);
2414 wp_trash_post_comments($post_id);
2416 do_action('trashed_post', $post_id);
2422 * Restores a post or page from the Trash
2425 * @uses do_action() on 'untrash_post' before undeletion
2426 * @uses do_action() on 'untrashed_post' after undeletion
2428 * @param int $post_id Post ID.
2429 * @return mixed False on failure
2431 function wp_untrash_post($post_id = 0) {
2432 if ( !$post = get_post($post_id, ARRAY_A) )
2435 if ( $post['post_status'] != 'trash' )
2438 do_action('untrash_post', $post_id);
2440 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2442 $post['post_status'] = $post_status;
2444 delete_post_meta($post_id, '_wp_trash_meta_status');
2445 delete_post_meta($post_id, '_wp_trash_meta_time');
2447 wp_insert_post($post);
2449 wp_untrash_post_comments($post_id);
2451 do_action('untrashed_post', $post_id);
2457 * Moves comments for a post to the trash
2460 * @uses do_action() on 'trash_post_comments' before trashing
2461 * @uses do_action() on 'trashed_post_comments' after trashing
2463 * @param int|object $post Post ID or object.
2464 * @return mixed False on failure
2466 function wp_trash_post_comments($post = null) {
2469 $post = get_post($post);
2473 $post_id = $post->ID;
2475 do_action('trash_post_comments', $post_id);
2477 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2478 if ( empty($comments) )
2481 // Cache current status for each comment
2482 $statuses = array();
2483 foreach ( $comments as $comment )
2484 $statuses[$comment->comment_ID] = $comment->comment_approved;
2485 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2487 // Set status for all comments to post-trashed
2488 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2490 clean_comment_cache( array_keys($statuses) );
2492 do_action('trashed_post_comments', $post_id, $statuses);
2498 * Restore comments for a post from the trash
2501 * @uses do_action() on 'untrash_post_comments' before trashing
2502 * @uses do_action() on 'untrashed_post_comments' after trashing
2504 * @param int|object $post Post ID or object.
2505 * @return mixed False on failure
2507 function wp_untrash_post_comments($post = null) {
2510 $post = get_post($post);
2514 $post_id = $post->ID;
2516 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2518 if ( empty($statuses) )
2521 do_action('untrash_post_comments', $post_id);
2523 // Restore each comment to its original status
2524 $group_by_status = array();
2525 foreach ( $statuses as $comment_id => $comment_status )
2526 $group_by_status[$comment_status][] = $comment_id;
2528 foreach ( $group_by_status as $status => $comments ) {
2529 // Sanity check. This shouldn't happen.
2530 if ( 'post-trashed' == $status )
2532 $comments_in = implode( "', '", $comments );
2533 $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
2536 clean_comment_cache( array_keys($statuses) );
2538 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2540 do_action('untrashed_post_comments', $post_id);
2544 * Retrieve the list of categories for a post.
2546 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2547 * away from the complexity of the taxonomy layer.
2551 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
2553 * @param int $post_id Optional. The Post ID.
2554 * @param array $args Optional. Overwrite the defaults.
2557 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2558 $post_id = (int) $post_id;
2560 $defaults = array('fields' => 'ids');
2561 $args = wp_parse_args( $args, $defaults );
2563 $cats = wp_get_object_terms($post_id, 'category', $args);
2568 * Retrieve the tags for a post.
2570 * There is only one default for this function, called 'fields' and by default
2571 * is set to 'all'. There are other defaults that can be overridden in
2572 * {@link wp_get_object_terms()}.
2574 * @package WordPress
2578 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2580 * @param int $post_id Optional. The Post ID
2581 * @param array $args Optional. Overwrite the defaults
2582 * @return array List of post tags.
2584 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2585 return wp_get_post_terms( $post_id, 'post_tag', $args);
2589 * Retrieve the terms for a post.
2591 * There is only one default for this function, called 'fields' and by default
2592 * is set to 'all'. There are other defaults that can be overridden in
2593 * {@link wp_get_object_terms()}.
2595 * @package WordPress
2599 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2601 * @param int $post_id Optional. The Post ID
2602 * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
2603 * @param array $args Optional. Overwrite the defaults
2604 * @return array List of post tags.
2606 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2607 $post_id = (int) $post_id;
2609 $defaults = array('fields' => 'all');
2610 $args = wp_parse_args( $args, $defaults );
2612 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2618 * Retrieve number of recent posts.
2621 * @uses wp_parse_args()
2624 * @param string $deprecated Deprecated.
2625 * @param array $args Optional. Overrides defaults.
2626 * @param string $output Optional.
2629 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2631 if ( is_numeric( $args ) ) {
2632 _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2633 $args = array( 'numberposts' => absint( $args ) );
2636 // Set default arguments
2638 'numberposts' => 10, 'offset' => 0,
2639 'category' => 0, 'orderby' => 'post_date',
2640 'order' => 'DESC', 'include' => '',
2641 'exclude' => '', 'meta_key' => '',
2642 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2643 'suppress_filters' => true
2646 $r = wp_parse_args( $args, $defaults );
2648 $results = get_posts( $r );
2650 // Backward compatibility. Prior to 3.1 expected posts to be returned in array
2651 if ( ARRAY_A == $output ){
2652 foreach( $results as $key => $result ) {
2653 $results[$key] = get_object_vars( $result );
2655 return $results ? $results : array();
2658 return $results ? $results : false;
2663 * Insert or update a post.
2665 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2667 * You can set the post date manually, by setting the values for 'post_date'
2668 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2669 * setting the value for 'comment_status' key.
2671 * @global wpdb $wpdb WordPress database abstraction object.
2675 * @param array $postarr {
2676 * An array of elements that make up a post to update or insert.
2678 * @type int 'ID' The post ID. If equal to something other than 0, the post with that ID will
2679 * be updated. Default 0.
2680 * @type string 'post_status' The post status. Default 'draft'.
2681 * @type string 'post_type' The post type. Default 'post'.
2682 * @type int 'post_author' The ID of the user who added the post. Default the current user ID.
2683 * @type bool 'ping_status' Whether the post can accept pings. Default value of 'default_ping_status' option.
2684 * @type int 'post_parent' Set this for the post it belongs to, if any. Default 0.
2685 * @type int 'menu_order' The order it is displayed. Default 0.
2686 * @type string 'to_ping' Space or carriage return-separated list of URLs to ping. Default empty string.
2687 * @type string 'pinged' Space or carriage return-separated list of URLs that have been pinged.
2688 * Default empty string.
2689 * @type string 'post_password The password to access the post. Default empty string.
2690 * @type string 'guid' Global Unique ID for referencing the post.
2691 * @type string 'post_content_filtered' The filtered post content. Default empty string.
2692 * @type string 'post_excerpt' The post excerpt. Default empty string.
2694 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2695 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2697 function wp_insert_post( $postarr, $wp_error = false ) {
2700 $user_id = get_current_user_id();
2702 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id,
2703 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2704 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
2705 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
2706 'post_content' => '', 'post_title' => '');
2708 $postarr = wp_parse_args($postarr, $defaults);
2710 unset( $postarr[ 'filter' ] );
2712 $postarr = sanitize_post($postarr, 'db');
2714 // export array as variables
2715 extract($postarr, EXTR_SKIP);
2717 // Are we updating or creating?
2720 if ( ! empty( $ID ) ) {
2723 // Get the post ID and GUID
2725 $post_before = get_post( $post_ID );
2726 if ( is_null( $post_before ) ) {
2728 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2732 $guid = get_post_field( 'guid', $post_ID );
2733 $previous_status = get_post_field('post_status', $ID);
2735 $previous_status = 'new';
2738 $maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' )
2739 && post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' );
2741 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2743 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2748 if ( empty($post_type) )
2749 $post_type = 'post';
2751 if ( empty($post_status) )
2752 $post_status = 'draft';
2754 if ( !empty($post_category) )
2755 $post_category = array_filter($post_category); // Filter out empty terms
2757 // Make sure we set a valid category.
2758 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
2759 // 'post' requires at least one category.
2760 if ( 'post' == $post_type && 'auto-draft' != $post_status )
2761 $post_category = array( get_option('default_category') );
2763 $post_category = array();
2766 if ( empty($post_author) )
2767 $post_author = $user_id;
2769 // Don't allow contributors to set the post slug for pending review posts
2770 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
2773 // Create a valid post name. Drafts and pending posts are allowed to have an empty
2775 if ( empty($post_name) ) {
2776 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2777 $post_name = sanitize_title($post_title);
2781 // On updates, we need to check to see if it's using the old, fixed sanitization context.
2782 $check_name = sanitize_title( $post_name, '', 'old-save' );
2783 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name )
2784 $post_name = $check_name;
2785 else // new post, or slug has changed.
2786 $post_name = sanitize_title($post_name);
2789 // 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
2790 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
2791 $post_date = current_time('mysql');
2793 // validate the date
2794 $mm = substr( $post_date, 5, 2 );
2795 $jj = substr( $post_date, 8, 2 );
2796 $aa = substr( $post_date, 0, 4 );
2797 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
2798 if ( !$valid_date ) {
2800 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
2805 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
2806 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2807 $post_date_gmt = get_gmt_from_date($post_date);
2809 $post_date_gmt = '0000-00-00 00:00:00';
2812 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
2813 $post_modified = current_time( 'mysql' );
2814 $post_modified_gmt = current_time( 'mysql', 1 );
2816 $post_modified = $post_date;
2817 $post_modified_gmt = $post_date_gmt;
2820 if ( 'publish' == $post_status ) {
2821 $now = gmdate('Y-m-d H:i:59');
2822 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
2823 $post_status = 'future';
2824 } elseif( 'future' == $post_status ) {
2825 $now = gmdate('Y-m-d H:i:59');
2826 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
2827 $post_status = 'publish';
2830 if ( empty($comment_status) ) {
2832 $comment_status = 'closed';
2834 $comment_status = get_option('default_comment_status');
2836 if ( empty($ping_status) )
2837 $ping_status = get_option('default_ping_status');
2839 if ( isset($to_ping) )
2840 $to_ping = sanitize_trackback_urls( $to_ping );
2844 if ( ! isset($pinged) )
2847 if ( isset($post_parent) )
2848 $post_parent = (int) $post_parent;
2852 // Check the post_parent to see if it will cause a hierarchy loop
2853 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
2855 if ( isset($menu_order) )
2856 $menu_order = (int) $menu_order;
2860 if ( !isset($post_password) || 'private' == $post_status )
2861 $post_password = '';
2863 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2865 // expected_slashed (everything!)
2866 $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' ) );
2867 $data = apply_filters('wp_insert_post_data', $data, $postarr);
2868 $data = wp_unslash( $data );
2869 $where = array( 'ID' => $post_ID );
2872 do_action( 'pre_post_update', $post_ID, $data );
2873 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
2875 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
2880 if ( isset($post_mime_type) )
2881 $data['post_mime_type'] = wp_unslash( $post_mime_type ); // This isn't in the update
2882 // If there is a suggested ID, use it if not already present
2883 if ( !empty($import_id) ) {
2884 $import_id = (int) $import_id;
2885 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2886 $data['ID'] = $import_id;
2889 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
2891 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
2895 $post_ID = (int) $wpdb->insert_id;
2897 // use the newly generated $post_ID
2898 $where = array( 'ID' => $post_ID );
2901 if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
2902 $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
2903 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
2906 if ( is_object_in_taxonomy($post_type, 'category') )
2907 wp_set_post_categories( $post_ID, $post_category );
2909 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
2910 wp_set_post_tags( $post_ID, $tags_input );
2912 // new-style support for all custom taxonomies
2913 if ( !empty($tax_input) ) {
2914 foreach ( $tax_input as $taxonomy => $tags ) {
2915 $taxonomy_obj = get_taxonomy($taxonomy);
2916 if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
2917 $tags = array_filter($tags);
2918 if ( current_user_can($taxonomy_obj->cap->assign_terms) )
2919 wp_set_post_terms( $post_ID, $tags, $taxonomy );
2923 $current_guid = get_post_field( 'guid', $post_ID );
2926 if ( !$update && '' == $current_guid )
2927 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
2929 clean_post_cache( $post_ID );
2931 $post = get_post($post_ID);
2933 if ( !empty($page_template) && 'page' == $data['post_type'] ) {
2934 $post->page_template = $page_template;
2935 $page_templates = wp_get_theme()->get_page_templates();
2936 if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) {
2938 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
2942 update_post_meta($post_ID, '_wp_page_template', $page_template);
2945 wp_transition_post_status($data['post_status'], $previous_status, $post);
2948 do_action('edit_post', $post_ID, $post);
2949 $post_after = get_post($post_ID);
2950 do_action( 'post_updated', $post_ID, $post_after, $post_before);
2953 do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
2954 do_action( 'save_post', $post_ID, $post, $update );
2955 do_action( 'wp_insert_post', $post_ID, $post, $update );
2961 * Update a post with new post data.
2963 * The date does not have to be set for drafts. You can set the date and it will
2964 * not be overridden.
2968 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
2969 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2970 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
2972 function wp_update_post( $postarr = array(), $wp_error = false ) {
2973 if ( is_object($postarr) ) {
2974 // non-escaped post was passed
2975 $postarr = get_object_vars($postarr);
2976 $postarr = wp_slash($postarr);
2979 // First, get all of the original fields
2980 $post = get_post($postarr['ID'], ARRAY_A);
2982 if ( is_null( $post ) ) {
2984 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2988 // Escape data pulled from DB.
2989 $post = wp_slash($post);
2991 // Passed post category list overwrites existing category list if not empty.
2992 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
2993 && 0 != count($postarr['post_category']) )
2994 $post_cats = $postarr['post_category'];
2996 $post_cats = $post['post_category'];
2998 // Drafts shouldn't be assigned a date unless explicitly done so by the user
2999 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3000 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3003 $clear_date = false;
3005 // Merge old and new fields with new fields overwriting old ones.
3006 $postarr = array_merge($post, $postarr);
3007 $postarr['post_category'] = $post_cats;
3008 if ( $clear_date ) {
3009 $postarr['post_date'] = current_time('mysql');
3010 $postarr['post_date_gmt'] = '';
3013 if ($postarr['post_type'] == 'attachment')
3014 return wp_insert_attachment($postarr);
3016 return wp_insert_post( $postarr, $wp_error );
3020 * Publish a post by transitioning the post status.
3024 * @uses do_action() Calls 'edit_post', 'save_post_{$post_type}', 'save_post' and 'wp_insert_post' on post_id and post data.
3026 * @param int|object $post Post ID or object.
3028 function wp_publish_post( $post ) {
3031 if ( ! $post = get_post( $post ) )
3034 if ( 'publish' == $post->post_status )
3037 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3039 clean_post_cache( $post->ID );
3041 $old_status = $post->post_status;
3042 $post->post_status = 'publish';
3043 wp_transition_post_status( 'publish', $old_status, $post );
3045 do_action( 'edit_post', $post->ID, $post );
3046 do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3047 do_action( 'save_post', $post->ID, $post, true );
3048 do_action( 'wp_insert_post', $post->ID, $post, true );
3052 * Publish future post and make sure post ID has future post status.
3054 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3055 * from publishing drafts, etc.
3059 * @param int $post_id Post ID.
3060 * @return null Nothing is returned. Which can mean that no action is required or post was published.
3062 function check_and_publish_future_post($post_id) {
3064 $post = get_post($post_id);
3069 if ( 'future' != $post->post_status )
3072 $time = strtotime( $post->post_date_gmt . ' GMT' );
3074 if ( $time > time() ) { // Uh oh, someone jumped the gun!
3075 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3076 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3080 return wp_publish_post($post_id);
3084 * Computes a unique slug for the post, when given the desired slug and some post details.
3088 * @global wpdb $wpdb
3089 * @global WP_Rewrite $wp_rewrite
3090 * @param string $slug the desired slug (post_name)
3091 * @param integer $post_ID
3092 * @param string $post_status no uniqueness checks are made if the post is still draft or pending
3093 * @param string $post_type
3094 * @param integer $post_parent
3095 * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3097 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3098 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3101 global $wpdb, $wp_rewrite;
3103 $original_slug = $slug;
3105 $feeds = $wp_rewrite->feeds;
3106 if ( ! is_array( $feeds ) )
3109 $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
3110 if ( 'attachment' == $post_type ) {
3111 // Attachment slugs must be unique across all types.
3112 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3113 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3115 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3118 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3119 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3121 } while ( $post_name_check );
3122 $slug = $alt_post_name;
3124 } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
3125 if ( 'nav_menu_item' == $post_type )
3127 // Page slugs must be unique within their own trees. Pages are in a separate
3128 // namespace than posts so page slugs are allowed to overlap post slugs.
3129 $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";
3130 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
3132 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 ) ) {
3135 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3136 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
3138 } while ( $post_name_check );
3139 $slug = $alt_post_name;
3142 // Post slugs must be unique across all posts.
3143 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3144 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3146 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3149 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3150 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3152 } while ( $post_name_check );
3153 $slug = $alt_post_name;
3157 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3161 * Truncates a post slug.
3165 * @uses utf8_uri_encode() Makes sure UTF-8 characters are properly cut and encoded.
3167 * @param string $slug The slug to truncate.
3168 * @param int $length Max length of the slug.
3169 * @return string The truncated slug.
3171 function _truncate_post_slug( $slug, $length = 200 ) {
3172 if ( strlen( $slug ) > $length ) {
3173 $decoded_slug = urldecode( $slug );
3174 if ( $decoded_slug === $slug )
3175 $slug = substr( $slug, 0, $length );
3177 $slug = utf8_uri_encode( $decoded_slug, $length );
3180 return rtrim( $slug, '-' );
3184 * Adds tags to a post.
3186 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
3188 * @package WordPress
3192 * @param int $post_id Post ID
3193 * @param string $tags The tags to set for the post, separated by commas.
3194 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
3196 function wp_add_post_tags($post_id = 0, $tags = '') {
3197 return wp_set_post_tags($post_id, $tags, true);
3201 * Set the tags for a post.
3204 * @uses wp_set_object_terms() Sets the tags for the post.
3206 * @param int $post_id Post ID.
3207 * @param string $tags The tags to set for the post, separated by commas.
3208 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3209 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3211 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3212 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3216 * Set the terms for a post.
3219 * @uses wp_set_object_terms() Sets the tags for the post.
3221 * @param int $post_id Post ID.
3222 * @param string $tags The tags to set for the post, separated by commas.
3223 * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'.
3224 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3225 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3227 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3228 $post_id = (int) $post_id;
3236 if ( ! is_array( $tags ) ) {
3237 $comma = _x( ',', 'tag delimiter' );
3238 if ( ',' !== $comma )
3239 $tags = str_replace( $comma, ',', $tags );
3240 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3243 // Hierarchical taxonomies must always pass IDs rather than names so that children with the same
3244 // names but different parents aren't confused.
3245 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3246 $tags = array_unique( array_map( 'intval', $tags ) );
3249 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3253 * Set categories for a post.
3255 * If the post categories parameter is not set, then the default category is
3260 * @param int $post_ID Post ID.
3261 * @param array|int $post_categories Optional. List of categories or ID of category.
3262 * @param bool $append If true, don't delete existing categories, just add on. If false, replace the categories with the new categories.
3263 * @return bool|mixed
3265 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3266 $post_ID = (int) $post_ID;
3267 $post_type = get_post_type( $post_ID );
3268 $post_status = get_post_status( $post_ID );
3269 // If $post_categories isn't already an array, make it one:
3270 $post_categories = (array) $post_categories;
3271 if ( empty( $post_categories ) ) {
3272 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3273 $post_categories = array( get_option('default_category') );
3276 $post_categories = array();
3278 } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
3282 return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3286 * Transition the post status of a post.
3288 * Calls hooks to transition post status.
3290 * The first is 'transition_post_status' with new status, old status, and post data.
3292 * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
3293 * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
3296 * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
3297 * parameter and POSTTYPE is post_type post data.
3300 * @link http://codex.wordpress.org/Post_Status_Transitions
3302 * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
3303 * $post if there is a status change.
3304 * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
3305 * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
3307 * @param string $new_status Transition to this post status.
3308 * @param string $old_status Previous post status.
3309 * @param object $post Post data.
3311 function wp_transition_post_status($new_status, $old_status, $post) {
3312 do_action('transition_post_status', $new_status, $old_status, $post);
3313 do_action("{$old_status}_to_{$new_status}", $post);
3314 do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
3318 // Trackback and ping functions
3322 * Add a URL to those already pung.
3327 * @param int $post_id Post ID.
3328 * @param string $uri Ping URI.
3329 * @return int How many rows were updated.
3331 function add_ping($post_id, $uri) {
3333 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3334 $pung = trim($pung);
3335 $pung = preg_split('/\s/', $pung);
3337 $new = implode("\n", $pung);
3338 $new = apply_filters('add_ping', $new);
3339 // expected_slashed ($new)
3340 $new = wp_unslash($new);
3341 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3345 * Retrieve enclosures already enclosed for a post.
3349 * @param int $post_id Post ID.
3350 * @return array List of enclosures
3352 function get_enclosed($post_id) {
3353 $custom_fields = get_post_custom( $post_id );
3355 if ( !is_array( $custom_fields ) )
3358 foreach ( $custom_fields as $key => $val ) {
3359 if ( 'enclosure' != $key || !is_array( $val ) )
3361 foreach( $val as $enc ) {
3362 $enclosure = explode( "\n", $enc );
3363 $pung[] = trim( $enclosure[ 0 ] );
3366 $pung = apply_filters('get_enclosed', $pung, $post_id);
3371 * Retrieve URLs already pinged for a post.
3376 * @param int $post_id Post ID.
3379 function get_pung($post_id) {
3381 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3382 $pung = trim($pung);
3383 $pung = preg_split('/\s/', $pung);
3384 $pung = apply_filters('get_pung', $pung);
3389 * Retrieve URLs that need to be pinged.
3394 * @param int $post_id Post ID
3397 function get_to_ping($post_id) {
3399 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
3400 $to_ping = sanitize_trackback_urls( $to_ping );
3401 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
3402 $to_ping = apply_filters('get_to_ping', $to_ping);
3407 * Do trackbacks for a list of URLs.
3411 * @param string $tb_list Comma separated list of URLs
3412 * @param int $post_id Post ID
3414 function trackback_url_list($tb_list, $post_id) {
3415 if ( ! empty( $tb_list ) ) {
3417 $postdata = get_post($post_id, ARRAY_A);
3419 // import postdata as variables
3420 extract($postdata, EXTR_SKIP);
3423 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
3425 if (strlen($excerpt) > 255) {
3426 $excerpt = substr($excerpt,0,252) . '…';
3429 $trackback_urls = explode(',', $tb_list);
3430 foreach( (array) $trackback_urls as $tb_url) {
3431 $tb_url = trim($tb_url);
3432 trackback($tb_url, wp_unslash($post_title), $excerpt, $post_id);
3442 * Get a list of page IDs.
3447 * @return array List of page IDs.
3449 function get_all_page_ids() {
3452 $page_ids = wp_cache_get('all_page_ids', 'posts');
3453 if ( ! is_array( $page_ids ) ) {
3454 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
3455 wp_cache_add('all_page_ids', $page_ids, 'posts');
3462 * Retrieves page data given a page ID or page object.
3464 * Use get_post() instead of get_page().
3469 * @param mixed $page Page object or page ID. Passed by reference.
3470 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
3471 * @param string $filter How the return value should be filtered.
3472 * @return WP_Post|null WP_Post on success or null on failure
3474 function get_page( $page, $output = OBJECT, $filter = 'raw') {
3475 return get_post( $page, $output, $filter );
3479 * Retrieves a page given its path.
3484 * @param string $page_path Page path
3485 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3486 * @param string $post_type Optional. Post type. Default page.
3487 * @return WP_Post|null WP_Post on success or null on failure
3489 function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
3492 $page_path = rawurlencode(urldecode($page_path));
3493 $page_path = str_replace('%2F', '/', $page_path);
3494 $page_path = str_replace('%20', ' ', $page_path);
3495 $parts = explode( '/', trim( $page_path, '/' ) );
3496 $parts = esc_sql( $parts );
3497 $parts = array_map( 'sanitize_title_for_query', $parts );
3499 $in_string = "'". implode( "','", $parts ) . "'";
3500 $post_type_sql = esc_sql( $post_type );
3501 $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 );
3503 $revparts = array_reverse( $parts );
3506 foreach ( (array) $pages as $page ) {
3507 if ( $page->post_name == $revparts[0] ) {
3510 while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
3512 $parent = $pages[ $p->post_parent ];
3513 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
3518 if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
3519 $foundid = $page->ID;
3520 if ( $page->post_type == $post_type )
3527 return get_post( $foundid, $output );
3533 * Retrieve a page given its title.
3538 * @param string $page_title Page title
3539 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3540 * @param string $post_type Optional. Post type. Default page.
3541 * @return WP_Post|null WP_Post on success or null on failure
3543 function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
3545 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
3547 return get_post( $page, $output );
3553 * Retrieve child pages from list of pages matching page ID.
3555 * Matches against the pages parameter against the page ID. Also matches all
3556 * children for the same to retrieve all children of a page. Does not make any
3557 * SQL queries to get the children.
3561 * @param int $page_id Page ID.
3562 * @param array $pages List of pages' objects.
3565 function get_page_children($page_id, $pages) {
3566 $page_list = array();
3567 foreach ( (array) $pages as $page ) {
3568 if ( $page->post_parent == $page_id ) {
3569 $page_list[] = $page;
3570 if ( $children = get_page_children($page->ID, $pages) )
3571 $page_list = array_merge($page_list, $children);
3578 * Order the pages with children under parents in a flat list.
3580 * It uses auxiliary structure to hold parent-children relationships and
3581 * runs in O(N) complexity
3585 * @param array $pages Posts array.
3586 * @param int $page_id Parent page ID.
3587 * @return array A list arranged by hierarchy. Children immediately follow their parents.
3589 function get_page_hierarchy( &$pages, $page_id = 0 ) {
3590 if ( empty( $pages ) ) {
3595 $children = array();
3596 foreach ( (array) $pages as $p ) {
3597 $parent_id = intval( $p->post_parent );
3598 $children[ $parent_id ][] = $p;
3602 _page_traverse_name( $page_id, $children, $result );
3608 * function to traverse and return all the nested children post names of a root page.
3609 * $children contains parent-children relations
3613 function _page_traverse_name( $page_id, &$children, &$result ){
3614 if ( isset( $children[ $page_id ] ) ){
3615 foreach( (array)$children[ $page_id ] as $child ) {
3616 $result[ $child->ID ] = $child->post_name;
3617 _page_traverse_name( $child->ID, $children, $result );
3623 * Builds URI for a page.
3625 * Sub pages will be in the "directory" under the parent page post name.
3629 * @param mixed $page Page object or page ID.
3630 * @return string|false Page URI, false on error.
3632 function get_page_uri( $page ) {
3633 $page = get_post( $page );
3638 $uri = $page->post_name;
3640 foreach ( $page->ancestors as $parent ) {
3641 $uri = get_post( $parent )->post_name . '/' . $uri;
3648 * Retrieve a list of pages.
3650 * @global wpdb $wpdb WordPress database abstraction object
3654 * @param mixed $args {
3655 * Array or string of arguments. Optional.
3657 * @type int 'child_of' Page ID to return child and grandchild pages of. Default 0, or no restriction.
3658 * @type string 'sort_order' How to sort retrieved pages.
3659 * Default 'ASC'. Accepts 'ASC', 'DESC'.
3660 * @type string 'sort_column' What columns to sort pages by, comma-separated.
3661 * Default 'post_title'. Accepts 'post_author', 'post_date', 'post_title', 'post_name',
3662 * 'post_modified', 'post_modified_gmt', 'menu_order', 'post_parent', 'ID', 'rand',
3663 * 'comment_count'. 'post_' can be omitted for any values that start with it.
3664 * @type bool 'hierarchical' Whether to return pages hierarchically. Default true.
3665 * @type array 'exclude' Array of page IDs to exclude.
3666 * @type array 'include' Array of page IDs to include. Cannot be used with 'child_of', 'parent', 'exclude',
3667 * 'meta_key', 'meta_value', or 'hierarchical'.
3668 * @type string 'meta_key' Only include pages with this meta key.
3669 * @type string 'meta_value' Only include pages with this meta value.
3670 * @type string 'authors' A comma-separated list of author IDs.
3671 * @type int 'parent' Page ID to return direct children of. 'hierarchical' must be false.
3672 * Default -1, or no restriction.
3673 * @type int 'exclude_tree' Remove all children of the given ID from returned pages.
3674 * @type int 'number' The number of pages to return. Default 0, or all pages.
3675 * @type int 'offset' The number of pages to skip before returning. Requires 'number'.
3677 * @type string 'post_type' The post type to query.
3679 * @type string 'post_status' A comma-separated list of post status types to include.
3680 * Default 'publish'.
3682 * @return array List of pages matching defaults or $args.
3684 function get_pages( $args = array() ) {
3690 'child_of' => 0, 'sort_order' => 'ASC',
3691 'sort_column' => 'post_title', 'hierarchical' => 1,
3692 'exclude' => array(), 'include' => array(),
3693 'meta_key' => '', 'meta_value' => '',
3694 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
3695 'number' => '', 'offset' => 0,
3696 'post_type' => 'page', 'post_status' => 'publish',
3699 $r = wp_parse_args( $args, $defaults );
3700 extract( $r, EXTR_SKIP );
3701 $number = (int) $number;
3702 $offset = (int) $offset;
3704 // Make sure the post type is hierarchical
3705 $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
3706 if ( !in_array( $post_type, $hierarchical_post_types ) )
3709 if ( $parent > 0 && ! $child_of )
3710 $hierarchical = false;
3712 // Make sure we have a valid post status
3713 if ( !is_array( $post_status ) )
3714 $post_status = explode( ',', $post_status );
3715 if ( array_diff( $post_status, get_post_stati() ) )
3718 // $args can be whatever, only use the args defined in defaults to compute the key
3719 $key = md5( serialize( compact(array_keys($defaults)) ) );
3720 $last_changed = wp_cache_get( 'last_changed', 'posts' );
3721 if ( ! $last_changed ) {
3722 $last_changed = microtime();
3723 wp_cache_set( 'last_changed', $last_changed, 'posts' );
3726 $cache_key = "get_pages:$key:$last_changed";
3727 if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
3728 // Convert to WP_Post instances
3729 $pages = array_map( 'get_post', $cache );
3730 $pages = apply_filters('get_pages', $pages, $r);
3734 if ( !is_array($cache) )
3738 if ( ! empty( $include ) ) {
3739 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
3744 $hierarchical = false;
3745 $incpages = wp_parse_id_list( $include );
3746 if ( ! empty( $incpages ) )
3747 $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
3751 if ( ! empty( $exclude ) ) {
3752 $expages = wp_parse_id_list( $exclude );
3753 if ( ! empty( $expages ) )
3754 $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
3758 if (!empty($authors)) {
3759 $post_authors = preg_split('/[\s,]+/',$authors);
3761 if ( ! empty( $post_authors ) ) {
3762 foreach ( $post_authors as $post_author ) {
3763 //Do we have an author id or an author login?
3764 if ( 0 == intval($post_author) ) {
3765 $post_author = get_user_by('login', $post_author);
3766 if ( empty($post_author) )
3768 if ( empty($post_author->ID) )
3770 $post_author = $post_author->ID;
3773 if ( '' == $author_query )
3774 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
3776 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
3778 if ( '' != $author_query )
3779 $author_query = " AND ($author_query)";
3784 $where = "$exclusions $inclusions ";
3785 if ( '' !== $meta_key || '' !== $meta_value ) {
3786 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
3788 // meta_key and meta_value might be slashed
3789 $meta_key = wp_unslash($meta_key);
3790 $meta_value = wp_unslash($meta_value);
3791 if ( '' !== $meta_key )
3792 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
3793 if ( '' !== $meta_value )
3794 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
3798 if ( is_array( $parent ) ) {
3799 $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
3800 if ( ! empty( $post_parent__in ) )
3801 $where .= " AND post_parent IN ($post_parent__in)";
3802 } elseif ( $parent >= 0 ) {
3803 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
3806 if ( 1 == count( $post_status ) ) {
3807 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
3809 $post_status = implode( "', '", $post_status );
3810 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
3813 $orderby_array = array();
3814 $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
3815 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
3816 'ID', 'rand', 'comment_count');
3817 foreach ( explode( ',', $sort_column ) as $orderby ) {
3818 $orderby = trim( $orderby );
3819 if ( !in_array( $orderby, $allowed_keys ) )
3822 switch ( $orderby ) {
3826 $orderby = "$wpdb->posts.ID";
3829 $orderby = 'RAND()';
3831 case 'comment_count':
3832 $orderby = "$wpdb->posts.comment_count";
3835 if ( 0 === strpos( $orderby, 'post_' ) )
3836 $orderby = "$wpdb->posts." . $orderby;
3838 $orderby = "$wpdb->posts.post_" . $orderby;
3841 $orderby_array[] = $orderby;
3844 $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
3846 $sort_order = strtoupper( $sort_order );
3847 if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
3848 $sort_order = 'ASC';
3850 $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
3851 $query .= $author_query;
3852 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
3854 if ( !empty($number) )
3855 $query .= ' LIMIT ' . $offset . ',' . $number;
3857 $pages = $wpdb->get_results($query);
3859 if ( empty($pages) ) {
3860 $pages = apply_filters('get_pages', array(), $r);
3864 // Sanitize before caching so it'll only get done once
3865 $num_pages = count($pages);
3866 for ($i = 0; $i < $num_pages; $i++) {
3867 $pages[$i] = sanitize_post($pages[$i], 'raw');
3871 update_post_cache( $pages );
3873 if ( $child_of || $hierarchical )
3874 $pages = get_page_children($child_of, $pages);
3876 if ( !empty($exclude_tree) ) {
3877 $exclude = (int) $exclude_tree;
3878 $children = get_page_children($exclude, $pages);
3879 $excludes = array();
3880 foreach ( $children as $child )
3881 $excludes[] = $child->ID;
3882 $excludes[] = $exclude;
3883 $num_pages = count($pages);
3884 for ( $i = 0; $i < $num_pages; $i++ ) {
3885 if ( in_array($pages[$i]->ID, $excludes) )
3890 $page_structure = array();
3891 foreach ( $pages as $page )
3892 $page_structure[] = $page->ID;
3894 wp_cache_set( $cache_key, $page_structure, 'posts' );
3896 // Convert to WP_Post instances
3897 $pages = array_map( 'get_post', $pages );
3899 $pages = apply_filters('get_pages', $pages, $r);
3905 // Attachment functions
3909 * Check if the attachment URI is local one and is really an attachment.
3913 * @param string $url URL to check
3914 * @return bool True on success, false on failure.
3916 function is_local_attachment($url) {
3917 if (strpos($url, home_url()) === false)
3919 if (strpos($url, home_url('/?attachment_id=')) !== false)
3921 if ( $id = url_to_postid($url) ) {
3922 $post = get_post($id);
3923 if ( 'attachment' == $post->post_type )
3930 * Insert an attachment.
3932 * If you set the 'ID' in the $object parameter, it will mean that you are
3933 * updating and attempt to update the attachment. You can also set the
3934 * attachment name or title by setting the key 'post_name' or 'post_title'.
3936 * You can set the dates for the attachment manually by setting the 'post_date'
3937 * and 'post_date_gmt' keys' values.
3939 * By default, the comments will use the default settings for whether the
3940 * comments are allowed. You can close them manually or keep them open by
3941 * setting the value for the 'comment_status' key.
3943 * The $object parameter can have the following:
3944 * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
3945 * 'post_type' - Default is 'post', will be set to attachment. Can not override.
3946 * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
3947 * 'ping_status' - Default is the value in default ping status option. Whether the attachment
3949 * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
3951 * 'menu_order' - Default is 0. The order it is displayed.
3952 * 'to_ping' - Whether to ping.
3953 * 'pinged' - Default is empty string.
3954 * 'post_password' - Default is empty string. The password to access the attachment.
3955 * 'guid' - Global Unique ID for referencing the attachment.
3956 * 'post_content_filtered' - Attachment post content filtered.
3957 * 'post_excerpt' - Attachment excerpt.
3961 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
3962 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
3964 * @param string|array $object Arguments to override defaults.
3965 * @param string $file Optional filename.
3966 * @param int $parent Parent post ID.
3967 * @return int Attachment ID.
3969 function wp_insert_attachment($object, $file = false, $parent = 0) {
3972 $user_id = get_current_user_id();
3974 $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id,
3975 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '',
3976 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '',
3977 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
3979 $object = wp_parse_args($object, $defaults);
3980 if ( !empty($parent) )
3981 $object['post_parent'] = $parent;
3983 unset( $object[ 'filter' ] );
3985 $object = sanitize_post($object, 'db');
3987 // export array as variables
3988 extract($object, EXTR_SKIP);
3990 if ( empty($post_author) )
3991 $post_author = $user_id;
3993 $post_type = 'attachment';
3995 if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
3996 $post_status = 'inherit';
3998 if ( !empty($post_category) )
3999 $post_category = array_filter($post_category); // Filter out empty terms
4001 // Make sure we set a valid category.
4002 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
4003 $post_category = array();
4006 // Are we updating or creating?
4007 if ( !empty($ID) ) {
4009 $post_ID = (int) $ID;
4015 // Create a valid post name.
4016 if ( empty($post_name) )
4017 $post_name = sanitize_title($post_title);
4019 $post_name = sanitize_title($post_name);
4021 // expected_slashed ($post_name)
4022 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
4024 if ( empty($post_date) )
4025 $post_date = current_time('mysql');
4026 if ( empty($post_date_gmt) )
4027 $post_date_gmt = current_time('mysql', 1);
4029 if ( empty($post_modified) )
4030 $post_modified = $post_date;
4031 if ( empty($post_modified_gmt) )
4032 $post_modified_gmt = $post_date_gmt;
4034 if ( empty($comment_status) ) {
4036 $comment_status = 'closed';
4038 $comment_status = get_option('default_comment_status');
4040 if ( empty($ping_status) )
4041 $ping_status = get_option('default_ping_status');
4043 if ( isset($to_ping) )
4044 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
4048 if ( isset($post_parent) )
4049 $post_parent = (int) $post_parent;
4053 if ( isset($menu_order) )
4054 $menu_order = (int) $menu_order;
4058 if ( !isset($post_password) )
4059 $post_password = '';
4061 if ( ! isset($pinged) )
4064 // expected_slashed (everything!)
4065 $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' ) );
4066 $data = wp_unslash( $data );
4069 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
4071 // If there is a suggested ID, use it if not already present
4072 if ( !empty($import_id) ) {
4073 $import_id = (int) $import_id;
4074 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
4075 $data['ID'] = $import_id;
4079 $wpdb->insert( $wpdb->posts, $data );
4080 $post_ID = (int) $wpdb->insert_id;
4083 if ( empty($post_name) ) {
4084 $post_name = sanitize_title($post_title, $post_ID);
4085 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
4088 if ( is_object_in_taxonomy($post_type, 'category') )
4089 wp_set_post_categories( $post_ID, $post_category );
4091 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
4092 wp_set_post_tags( $post_ID, $tags_input );
4094 // support for all custom taxonomies
4095 if ( !empty($tax_input) ) {
4096 foreach ( $tax_input as $taxonomy => $tags ) {
4097 $taxonomy_obj = get_taxonomy($taxonomy);
4098 if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
4099 $tags = array_filter($tags);
4100 if ( current_user_can($taxonomy_obj->cap->assign_terms) )
4101 wp_set_post_terms( $post_ID, $tags, $taxonomy );
4106 update_attached_file( $post_ID, $file );
4108 clean_post_cache( $post_ID );
4110 if ( ! empty( $context ) )
4111 add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
4114 do_action('edit_attachment', $post_ID);
4116 do_action('add_attachment', $post_ID);
4123 * Trashes or deletes an attachment.
4125 * When an attachment is permanently deleted, the file will also be removed.
4126 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4127 * with the attachment (except the main post).
4129 * The attachment is moved to the trash instead of permanently deleted unless trash
4130 * for media is disabled, item is already in the trash, or $force_delete is true.
4134 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
4136 * @param int $post_id Attachment ID.
4137 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
4138 * @return mixed False on failure. Post data on success.
4140 function wp_delete_attachment( $post_id, $force_delete = false ) {
4143 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4146 if ( 'attachment' != $post->post_type )
4149 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4150 return wp_trash_post( $post_id );
4152 delete_post_meta($post_id, '_wp_trash_meta_status');
4153 delete_post_meta($post_id, '_wp_trash_meta_time');
4155 $meta = wp_get_attachment_metadata( $post_id );
4156 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4157 $file = get_attached_file( $post_id );
4159 $intermediate_sizes = array();
4160 foreach ( get_intermediate_image_sizes() as $size ) {
4161 if ( $intermediate = image_get_intermediate_size( $post_id, $size ) )
4162 $intermediate_sizes[] = $intermediate;
4165 if ( is_multisite() )
4166 delete_transient( 'dirsize_cache' );
4168 do_action('delete_attachment', $post_id);
4170 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4171 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4173 delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts.
4175 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4176 foreach ( $comment_ids as $comment_id )
4177 wp_delete_comment( $comment_id, true );
4179 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4180 foreach ( $post_meta_ids as $mid )
4181 delete_metadata_by_mid( 'post', $mid );
4183 do_action( 'delete_post', $post_id );
4184 $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4185 do_action( 'deleted_post', $post_id );
4187 $uploadpath = wp_upload_dir();
4189 if ( ! empty($meta['thumb']) ) {
4190 // Don't delete the thumb if another attachment uses it
4191 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)) ) {
4192 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4193 /** This filter is documented in wp-admin/custom-header.php */
4194 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
4195 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4199 // remove intermediate and backup images if there are any
4200 foreach ( $intermediate_sizes as $intermediate ) {
4201 /** This filter is documented in wp-admin/custom-header.php */
4202 $intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] );
4203 @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
4206 if ( is_array($backup_sizes) ) {
4207 foreach ( $backup_sizes as $size ) {
4208 $del_file = path_join( dirname($meta['file']), $size['file'] );
4209 /** This filter is documented in wp-admin/custom-header.php */
4210 $del_file = apply_filters('wp_delete_file', $del_file);
4211 @ unlink( path_join($uploadpath['basedir'], $del_file) );
4215 /** This filter is documented in wp-admin/custom-header.php */
4216 $file = apply_filters('wp_delete_file', $file);
4218 if ( ! empty($file) )
4221 clean_post_cache( $post );
4227 * Retrieve attachment meta field for attachment ID.
4231 * @param int $post_id Attachment ID
4232 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
4233 * @return string|bool Attachment meta field. False on failure.
4235 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4236 $post_id = (int) $post_id;
4237 if ( !$post = get_post( $post_id ) )
4240 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4245 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4249 * Update metadata for an attachment.
4253 * @param int $post_id Attachment ID.
4254 * @param array $data Attachment data.
4257 function wp_update_attachment_metadata( $post_id, $data ) {
4258 $post_id = (int) $post_id;
4259 if ( !$post = get_post( $post_id ) )
4262 if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4263 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4265 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4269 * Retrieve the URL for an attachment.
4273 * @param int $post_id Attachment ID.
4276 function wp_get_attachment_url( $post_id = 0 ) {
4277 $post_id = (int) $post_id;
4278 if ( !$post = get_post( $post_id ) )
4281 if ( 'attachment' != $post->post_type )
4285 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
4286 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
4287 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
4288 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
4289 elseif ( false !== strpos($file, 'wp-content/uploads') )
4290 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
4292 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
4296 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.
4297 $url = get_the_guid( $post->ID );
4299 $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4301 if ( empty( $url ) )
4308 * Retrieve thumbnail for an attachment.
4312 * @param int $post_id Attachment ID.
4313 * @return mixed False on failure. Thumbnail file path on success.
4315 function wp_get_attachment_thumb_file( $post_id = 0 ) {
4316 $post_id = (int) $post_id;
4317 if ( !$post = get_post( $post_id ) )
4319 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
4322 $file = get_attached_file( $post->ID );
4324 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
4325 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
4330 * Retrieve URL for an attachment thumbnail.
4334 * @param int $post_id Attachment ID
4335 * @return string|bool False on failure. Thumbnail URL on success.
4337 function wp_get_attachment_thumb_url( $post_id = 0 ) {
4338 $post_id = (int) $post_id;
4339 if ( !$post = get_post( $post_id ) )
4341 if ( !$url = wp_get_attachment_url( $post->ID ) )
4344 $sized = image_downsize( $post_id, 'thumbnail' );
4348 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
4351 $url = str_replace(basename($url), basename($thumb), $url);
4353 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
4357 * Check if the attachment is an image.
4361 * @param int $post_id Attachment ID
4364 function wp_attachment_is_image( $post_id = 0 ) {
4365 $post_id = (int) $post_id;
4366 if ( !$post = get_post( $post_id ) )
4369 if ( !$file = get_attached_file( $post->ID ) )
4372 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
4374 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
4376 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
4382 * Retrieve the icon for a MIME type.
4386 * @param string|int $mime MIME type or attachment ID.
4387 * @return string|bool
4389 function wp_mime_type_icon( $mime = 0 ) {
4390 if ( !is_numeric($mime) )
4391 $icon = wp_cache_get("mime_type_icon_$mime");
4394 if ( empty($icon) ) {
4395 $post_mimes = array();
4396 if ( is_numeric($mime) ) {
4397 $mime = (int) $mime;
4398 if ( $post = get_post( $mime ) ) {
4399 $post_id = (int) $post->ID;
4400 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
4401 if ( !empty($ext) ) {
4402 $post_mimes[] = $ext;
4403 if ( $ext_type = wp_ext2type( $ext ) )
4404 $post_mimes[] = $ext_type;
4406 $mime = $post->post_mime_type;
4411 $post_mimes[] = $mime;
4414 $icon_files = wp_cache_get('icon_files');
4416 if ( !is_array($icon_files) ) {
4417 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
4418 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
4419 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
4420 $icon_files = array();
4422 $keys = array_keys( $dirs );
4423 $dir = array_shift( $keys );
4424 $uri = array_shift($dirs);
4425 if ( $dh = opendir($dir) ) {
4426 while ( false !== $file = readdir($dh) ) {
4427 $file = basename($file);
4428 if ( substr($file, 0, 1) == '.' )
4430 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
4431 if ( is_dir("$dir/$file") )
4432 $dirs["$dir/$file"] = "$uri/$file";
4435 $icon_files["$dir/$file"] = "$uri/$file";
4440 wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
4443 // Icon basename - extension = MIME wildcard
4444 foreach ( $icon_files as $file => $uri )
4445 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
4447 if ( ! empty($mime) ) {
4448 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
4449 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
4450 $post_mimes[] = str_replace('/', '_', $mime);
4453 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
4454 $matches['default'] = array('default');
4456 foreach ( $matches as $match => $wilds ) {
4457 if ( isset($types[$wilds[0]])) {
4458 $icon = $types[$wilds[0]];
4459 if ( !is_numeric($mime) )
4460 wp_cache_add("mime_type_icon_$mime", $icon);
4466 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
4470 * Checked for changed slugs for published post objects and save the old slug.
4472 * The function is used when a post object of any type is updated,
4473 * by comparing the current and previous post objects.
4475 * If the slug was changed and not already part of the old slugs then it will be
4476 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
4479 * The most logically usage of this function is redirecting changed post objects, so
4480 * that those that linked to an changed post will be redirected to the new post.
4484 * @param int $post_id Post ID.
4485 * @param object $post The Post Object
4486 * @param object $post_before The Previous Post Object
4487 * @return int Same as $post_id
4489 function wp_check_for_changed_slugs($post_id, $post, $post_before) {
4490 // dont bother if it hasnt changed
4491 if ( $post->post_name == $post_before->post_name )
4494 // we're only concerned with published, non-hierarchical objects
4495 if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
4498 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
4500 // if we haven't added this old slug before, add it now
4501 if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
4502 add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
4504 // if the new slug was used previously, delete it from the list
4505 if ( in_array($post->post_name, $old_slugs) )
4506 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
4510 * Retrieve the private post SQL based on capability.
4512 * This function provides a standardized way to appropriately select on the
4513 * post_status of a post type. The function will return a piece of SQL code
4514 * that can be added to a WHERE clause; this SQL is constructed to allow all
4515 * published posts, and all private posts to which the user has access.
4519 * @param string $post_type currently only supports 'post' or 'page'.
4520 * @return string SQL code that can be added to a where clause.
4522 function get_private_posts_cap_sql( $post_type ) {
4523 return get_posts_by_author_sql( $post_type, false );
4527 * Retrieve the post SQL based on capability, author, and type.
4529 * @see get_private_posts_cap_sql() for full description.
4532 * @param string $post_type Post type.
4533 * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
4534 * @param int $post_author Optional. Query posts having a single author ID.
4535 * @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false.
4536 * @return string SQL WHERE code that can be added to a query.
4538 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
4542 $post_type_obj = get_post_type_object( $post_type );
4543 if ( ! $post_type_obj )
4544 return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
4546 // This hook is deprecated. Why you'd want to use it, I dunno.
4547 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) )
4548 $cap = $post_type_obj->cap->read_private_posts;
4551 if ( null === $post_author ) {
4552 $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
4554 $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
4560 $sql .= "(post_status = 'publish'";
4562 // Only need to check the cap if $public_only is false
4563 if ( false === $public_only ) {
4564 if ( current_user_can( $cap ) ) {
4565 // Does the user have the capability to view private posts? Guess so.
4566 $sql .= " OR post_status = 'private'";
4567 } elseif ( is_user_logged_in() ) {
4568 // Users can view their own private posts.
4569 $id = get_current_user_id();
4570 if ( null === $post_author || ! $full ) {
4571 $sql .= " OR post_status = 'private' AND post_author = $id";
4572 } elseif ( $id == (int) $post_author ) {
4573 $sql .= " OR post_status = 'private'";
4584 * Retrieve the date that the last post was published.
4586 * The server timezone is the default and is the difference between GMT and
4587 * server time. The 'blog' value is the date when the last post was posted. The
4588 * 'gmt' is when the last post was posted in GMT formatted date.
4592 * @uses apply_filters() Calls 'get_lastpostdate' filter
4594 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4595 * @return string The date of the last post.
4597 function get_lastpostdate($timezone = 'server') {
4598 return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
4602 * Retrieve last post modified date depending on timezone.
4604 * The server timezone is the default and is the difference between GMT and
4605 * server time. The 'blog' value is just when the last post was modified. The
4606 * 'gmt' is when the last post was modified in GMT time.
4609 * @uses apply_filters() Calls 'get_lastpostmodified' filter
4611 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4612 * @return string The date the post was last modified.
4614 function get_lastpostmodified($timezone = 'server') {
4615 $lastpostmodified = _get_last_post_time( $timezone, 'modified' );
4617 $lastpostdate = get_lastpostdate($timezone);
4618 if ( $lastpostdate > $lastpostmodified )
4619 $lastpostmodified = $lastpostdate;
4621 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
4625 * Retrieve latest post date data based on timezone.
4630 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4631 * @param string $field Field to check. Can be 'date' or 'modified'.
4632 * @return string The date.
4634 function _get_last_post_time( $timezone, $field ) {
4637 if ( !in_array( $field, array( 'date', 'modified' ) ) )
4640 $timezone = strtolower( $timezone );
4642 $key = "lastpost{$field}:$timezone";
4644 $date = wp_cache_get( $key, 'timeinfo' );
4647 $add_seconds_server = date('Z');
4649 $post_types = get_post_types( array( 'public' => true ) );
4650 array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
4651 $post_types = "'" . implode( "', '", $post_types ) . "'";
4653 switch ( $timezone ) {
4655 $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");
4658 $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");
4661 $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");
4666 wp_cache_set( $key, $date, 'timeinfo' );
4673 * Updates posts in cache.
4675 * @package WordPress
4679 * @param array $posts Array of post objects
4681 function update_post_cache( &$posts ) {
4685 foreach ( $posts as $post )
4686 wp_cache_add( $post->ID, $post, 'posts' );
4690 * Will clean the post in the cache.
4692 * Cleaning means delete from the cache of the post. Will call to clean the term
4693 * object cache associated with the post ID.
4695 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
4696 * wp_suspend_cache_invalidation().
4698 * @package WordPress
4702 * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
4704 * @param int|object $post Post ID or object to remove from the cache
4706 function clean_post_cache( $post ) {
4707 global $_wp_suspend_cache_invalidation, $wpdb;
4709 if ( ! empty( $_wp_suspend_cache_invalidation ) )
4712 $post = get_post( $post );
4713 if ( empty( $post ) )
4716 wp_cache_delete( $post->ID, 'posts' );
4717 wp_cache_delete( $post->ID, 'post_meta' );
4719 clean_object_term_cache( $post->ID, $post->post_type );
4721 wp_cache_delete( 'wp_get_archives', 'general' );
4723 do_action( 'clean_post_cache', $post->ID, $post );
4725 if ( is_post_type_hierarchical( $post->post_type ) )
4726 wp_cache_delete( 'get_pages', 'posts' );
4728 if ( 'page' == $post->post_type ) {
4729 wp_cache_delete( 'all_page_ids', 'posts' );
4730 do_action( 'clean_page_cache', $post->ID );
4733 wp_cache_set( 'last_changed', microtime(), 'posts' );
4737 * Call major cache updating functions for list of Post objects.
4739 * @package WordPress
4743 * @uses update_post_cache()
4744 * @uses update_object_term_cache()
4745 * @uses update_postmeta_cache()
4747 * @param array $posts Array of Post objects
4748 * @param string $post_type The post type of the posts in $posts. Default is 'post'.
4749 * @param bool $update_term_cache Whether to update the term cache. Default is true.
4750 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
4752 function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
4753 // No point in doing all this work if we didn't match any posts.
4757 update_post_cache($posts);
4759 $post_ids = array();
4760 foreach ( $posts as $post )
4761 $post_ids[] = $post->ID;
4766 if ( $update_term_cache ) {
4767 if ( is_array($post_type) ) {
4768 $ptypes = $post_type;
4769 } elseif ( 'any' == $post_type ) {
4770 // Just use the post_types in the supplied posts.
4771 foreach ( $posts as $post )
4772 $ptypes[] = $post->post_type;
4773 $ptypes = array_unique($ptypes);
4775 $ptypes = array($post_type);
4778 if ( ! empty($ptypes) )
4779 update_object_term_cache($post_ids, $ptypes);
4782 if ( $update_meta_cache )
4783 update_postmeta_cache($post_ids);
4787 * Updates metadata cache for list of post IDs.
4789 * Performs SQL query to retrieve the metadata for the post IDs and updates the
4790 * metadata cache for the posts. Therefore, the functions, which call this
4791 * function, do not need to perform SQL queries on their own.
4793 * @package WordPress
4797 * @param array $post_ids List of post IDs.
4798 * @return bool|array Returns false if there is nothing to update or an array of metadata.
4800 function update_postmeta_cache($post_ids) {
4801 return update_meta_cache('post', $post_ids);
4805 * Will clean the attachment in the cache.
4807 * Cleaning means delete from the cache. Optionally will clean the term
4808 * object cache associated with the attachment ID.
4810 * This function will not run if $_wp_suspend_cache_invalidation is not empty. See
4811 * wp_suspend_cache_invalidation().
4813 * @package WordPress
4817 * @uses do_action() Calls 'clean_attachment_cache' on $id.
4819 * @param int $id The attachment ID in the cache to clean
4820 * @param bool $clean_terms optional. Whether to clean terms cache
4822 function clean_attachment_cache($id, $clean_terms = false) {
4823 global $_wp_suspend_cache_invalidation;
4825 if ( !empty($_wp_suspend_cache_invalidation) )
4830 wp_cache_delete($id, 'posts');
4831 wp_cache_delete($id, 'post_meta');
4834 clean_object_term_cache($id, 'attachment');
4836 do_action('clean_attachment_cache', $id);
4844 * Hook for managing future post transitions to published.
4849 * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
4850 * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
4852 * @param string $new_status New post status
4853 * @param string $old_status Previous post status
4854 * @param object $post Object type containing the post information
4856 function _transition_post_status($new_status, $old_status, $post) {
4859 if ( $old_status != 'publish' && $new_status == 'publish' ) {
4860 // Reset GUID if transitioning to publish and it is empty
4861 if ( '' == get_the_guid($post->ID) )
4862 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
4863 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
4866 // If published posts changed clear the lastpostmodified cache
4867 if ( 'publish' == $new_status || 'publish' == $old_status) {
4868 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
4869 wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
4870 wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
4874 // Always clears the hook in case the post status bounced from future to draft.
4875 wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
4879 * Hook used to schedule publication for a post marked for the future.
4881 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
4886 * @param int $deprecated Not used. Can be set to null. Never implemented.
4887 * Not marked as deprecated with _deprecated_argument() as it conflicts with
4888 * wp_transition_post_status() and the default filter for _future_post_hook().
4889 * @param object $post Object type containing the post information
4891 function _future_post_hook( $deprecated, $post ) {
4892 wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
4893 wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
4897 * Hook to schedule pings and enclosures when a post is published.
4901 * @uses XMLRPC_REQUEST and WP_IMPORTING constants.
4902 * @uses do_action() Calls 'xmlrpc_publish_post' on post ID if XMLRPC_REQUEST is defined.
4904 * @param int $post_id The ID in the database table of the post being published
4906 function _publish_post_hook($post_id) {
4907 if ( defined('XMLRPC_REQUEST') )
4908 do_action('xmlrpc_publish_post', $post_id);
4910 if ( defined('WP_IMPORTING') )
4913 if ( get_option('default_pingback_flag') )
4914 add_post_meta( $post_id, '_pingme', '1' );
4915 add_post_meta( $post_id, '_encloseme', '1' );
4917 wp_schedule_single_event(time(), 'do_pings');
4921 * Returns the post's parent's post_ID
4925 * @param int $post_id
4927 * @return int|bool false on error
4929 function wp_get_post_parent_id( $post_ID ) {
4930 $post = get_post( $post_ID );
4931 if ( !$post || is_wp_error( $post ) )
4933 return (int) $post->post_parent;
4937 * Checks the given subset of the post hierarchy for hierarchy loops.
4938 * Prevents loops from forming and breaks those that it finds.
4940 * Attached to the wp_insert_post_parent filter.
4943 * @uses wp_find_hierarchy_loop()
4945 * @param int $post_parent ID of the parent for the post we're checking.
4946 * @param int $post_ID ID of the post we're checking.
4948 * @return int The new post_parent for the post.
4950 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
4951 // Nothing fancy here - bail
4952 if ( !$post_parent )
4955 // New post can't cause a loop
4956 if ( empty( $post_ID ) )
4957 return $post_parent;
4959 // Can't be its own parent
4960 if ( $post_parent == $post_ID )
4963 // Now look for larger loops
4965 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
4966 return $post_parent; // No loop
4968 // Setting $post_parent to the given value causes a loop
4969 if ( isset( $loop[$post_ID] ) )
4972 // There's a loop, but it doesn't contain $post_ID. Break the loop.
4973 foreach ( array_keys( $loop ) as $loop_member )
4974 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
4976 return $post_parent;
4980 * Sets a post thumbnail.
4984 * @param int|object $post Post ID or object where thumbnail should be attached.
4985 * @param int $thumbnail_id Thumbnail to attach.
4986 * @return bool True on success, false on failure.
4988 function set_post_thumbnail( $post, $thumbnail_id ) {
4989 $post = get_post( $post );
4990 $thumbnail_id = absint( $thumbnail_id );
4991 if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
4992 if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
4993 return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
4995 return delete_post_meta( $post->ID, '_thumbnail_id' );
5001 * Removes a post thumbnail.
5005 * @param int|object $post Post ID or object where thumbnail should be removed from.
5006 * @return bool True on success, false on failure.
5008 function delete_post_thumbnail( $post ) {
5009 $post = get_post( $post );
5011 return delete_post_meta( $post->ID, '_thumbnail_id' );
5016 * Deletes auto-drafts for new posts that are > 7 days old
5020 function wp_delete_auto_drafts() {
5023 // Cleanup old auto-drafts more than 7 days old
5024 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
5025 foreach ( (array) $old_posts as $delete )
5026 wp_delete_post( $delete, true ); // Force delete
5030 * 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.
5033 * @param string $new_status
5034 * @param string $old_status
5035 * @param object $post
5038 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
5039 // Update counts for the post's terms.
5040 foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
5041 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
5042 wp_update_term_count( $tt_ids, $taxonomy );
5047 * Adds any posts from the given ids to the cache that do not already exist in cache
5053 * @param array $post_ids ID list
5054 * @param bool $update_term_cache Whether to update the term cache. Default is true.
5055 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
5057 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
5060 $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
5061 if ( !empty( $non_cached_ids ) ) {
5062 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
5064 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );