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 * You can optionally send it through the 'get_attached_file' filter, but by
171 * default it will just return the file path unfiltered.
173 * The function works by getting the single post meta name, named
174 * '_wp_attached_file' and returning it. This is a convenience function to
175 * prevent looking up the meta name and provide a mechanism for sending the
176 * attached filename through a filter.
179 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
181 * @param int $attachment_id Attachment ID.
182 * @param bool $unfiltered Whether to apply filters.
183 * @return string|bool The file path to the attached file, or false if the attachment does not exist.
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 update_post_cache($children);
318 foreach ( $children as $key => $child )
319 $kids[$child->ID] = $children[$key];
321 if ( $output == OBJECT ) {
323 } elseif ( $output == ARRAY_A ) {
324 foreach ( (array) $kids as $kid )
325 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
327 } elseif ( $output == ARRAY_N ) {
328 foreach ( (array) $kids as $kid )
329 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
337 * Get extended entry info (<!--more-->).
339 * There should not be any space after the second dash and before the word
340 * 'more'. There can be text or space(s) after the word 'more', but won't be
343 * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
344 * the <code><!--more--></code>. The 'extended' key has the content after the
345 * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text.
349 * @param string $post Post content.
350 * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text').
352 function get_extended($post) {
353 //Match the new style more links
354 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
355 list($main, $extended) = explode($matches[0], $post, 2);
356 $more_text = $matches[1];
363 // ` leading and trailing whitespace
364 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
365 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
366 $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
368 return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
372 * Retrieves post data given a post ID or post object.
374 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
375 * $post, must be given as a variable, since it is passed by reference.
379 * @link http://codex.wordpress.org/Function_Reference/get_post
381 * @param int|object $post Post ID or post object. Optional, default is the current post from the loop.
382 * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
383 * @param string $filter Optional, default is raw.
384 * @return WP_Post|null WP_Post on success or null on failure
386 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
387 if ( empty( $post ) && isset( $GLOBALS['post'] ) )
388 $post = $GLOBALS['post'];
390 if ( is_a( $post, 'WP_Post' ) ) {
392 } elseif ( is_object( $post ) ) {
393 if ( empty( $post->filter ) ) {
394 $_post = sanitize_post( $post, 'raw' );
395 $_post = new WP_Post( $_post );
396 } elseif ( 'raw' == $post->filter ) {
397 $_post = new WP_Post( $post );
399 $_post = WP_Post::get_instance( $post->ID );
402 $_post = WP_Post::get_instance( $post );
408 $_post = $_post->filter( $filter );
410 if ( $output == ARRAY_A )
411 return $_post->to_array();
412 elseif ( $output == ARRAY_N )
413 return array_values( $_post->to_array() );
419 * WordPress Post class.
424 final class WP_Post {
436 public $post_author = 0;
442 public $post_date = '0000-00-00 00:00:00';
448 public $post_date_gmt = '0000-00-00 00:00:00';
454 public $post_content = '';
460 public $post_title = '';
466 public $post_excerpt = '';
472 public $post_status = 'publish';
478 public $comment_status = 'open';
484 public $ping_status = 'open';
490 public $post_password = '';
496 public $post_name = '';
502 public $to_ping = '';
514 public $post_modified = '0000-00-00 00:00:00';
520 public $post_modified_gmt = '0000-00-00 00:00:00';
526 public $post_content_filtered = '';
532 public $post_parent = 0;
544 public $menu_order = 0;
550 public $post_type = 'post';
556 public $post_mime_type = '';
562 public $comment_count = 0;
571 * Private variable used by post formats to cache parsed content.
578 public $format_content;
581 public static function get_instance( $post_id ) {
584 $post_id = (int) $post_id;
588 $_post = wp_cache_get( $post_id, 'posts' );
591 $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
596 $_post = sanitize_post( $_post, 'raw' );
597 wp_cache_add( $_post->ID, $_post, 'posts' );
598 } elseif ( empty( $_post->filter ) ) {
599 $_post = sanitize_post( $_post, 'raw' );
602 return new WP_Post( $_post );
605 public function __construct( $post ) {
606 foreach ( get_object_vars( $post ) as $key => $value )
607 $this->$key = $value;
610 public function __isset( $key ) {
611 if ( 'ancestors' == $key )
614 if ( 'page_template' == $key )
615 return ( 'page' == $this->post_type );
617 if ( 'post_category' == $key )
620 if ( 'tags_input' == $key )
623 return metadata_exists( 'post', $this->ID, $key );
626 public function __get( $key ) {
627 if ( 'page_template' == $key && $this->__isset( $key ) ) {
628 return get_post_meta( $this->ID, '_wp_page_template', true );
631 if ( 'post_category' == $key ) {
632 if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
633 $terms = get_the_terms( $this, 'category' );
635 if ( empty( $terms ) )
638 return wp_list_pluck( $terms, 'term_id' );
641 if ( 'tags_input' == $key ) {
642 if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
643 $terms = get_the_terms( $this, 'post_tag' );
645 if ( empty( $terms ) )
648 return wp_list_pluck( $terms, 'name' );
651 // Rest of the values need filtering
653 if ( 'ancestors' == $key )
654 $value = get_post_ancestors( $this );
656 $value = get_post_meta( $this->ID, $key, true );
659 $value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
664 public function filter( $filter ) {
665 if ( $this->filter == $filter )
668 if ( $filter == 'raw' )
669 return self::get_instance( $this->ID );
671 return sanitize_post( $this, $filter );
674 public function to_array() {
675 $post = get_object_vars( $this );
677 foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
678 if ( $this->__isset( $key ) )
679 $post[ $key ] = $this->__get( $key );
687 * Retrieve ancestors of a post.
691 * @param int|object $post Post ID or post object
692 * @return array Ancestor IDs or empty array if none are found.
694 function get_post_ancestors( $post ) {
695 $post = get_post( $post );
697 if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
700 $ancestors = array();
702 $id = $ancestors[] = $post->post_parent;
704 while ( $ancestor = get_post( $id ) ) {
705 // Loop detection: If the ancestor has been seen before, break.
706 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
709 $id = $ancestors[] = $ancestor->post_parent;
716 * Retrieve data from a post field based on Post ID.
718 * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
719 * etc and based off of the post object property or key names.
721 * The context values are based off of the taxonomy filter functions and
722 * supported values are found within those functions.
725 * @uses sanitize_post_field() See for possible $context values.
727 * @param string $field Post field name.
728 * @param int|object $post Post ID or post object.
729 * @param string $context Optional. How to filter the field. Default is 'display'.
730 * @return string The value of the post field on success, empty string on failure.
732 function get_post_field( $field, $post, $context = 'display' ) {
733 $post = get_post( $post );
738 if ( !isset($post->$field) )
741 return sanitize_post_field($field, $post->$field, $post->ID, $context);
745 * Retrieve the mime type of an attachment based on the ID.
747 * This function can be used with any post type, but it makes more sense with
752 * @param int $ID Optional. Post ID. Default is the current post from the loop.
753 * @return string|bool The mime type on success, false on failure.
755 function get_post_mime_type($ID = '') {
756 $post = get_post($ID);
758 if ( is_object($post) )
759 return $post->post_mime_type;
765 * Retrieve the post status based on the Post ID.
767 * If the post ID is of an attachment, then the parent post status will be given
772 * @param int $ID Optional. Post ID. Default is the current post from the loop.
773 * @return string|bool Post status on success, false on failure.
775 function get_post_status($ID = '') {
776 $post = get_post($ID);
778 if ( !is_object($post) )
781 if ( 'attachment' == $post->post_type ) {
782 if ( 'private' == $post->post_status )
785 // Unattached attachments are assumed to be published
786 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
789 // Inherit status from the parent
790 if ( $post->post_parent && ( $post->ID != $post->post_parent ) )
791 return get_post_status($post->post_parent);
794 return $post->post_status;
798 * Retrieve all of the WordPress supported post statuses.
800 * Posts have a limited set of valid status values, this provides the
801 * post_status values and descriptions.
805 * @return array List of post statuses.
807 function get_post_statuses() {
809 'draft' => __('Draft'),
810 'pending' => __('Pending Review'),
811 'private' => __('Private'),
812 'publish' => __('Published')
819 * Retrieve all of the WordPress support page statuses.
821 * Pages have a limited set of valid status values, this provides the
822 * post_status values and descriptions.
826 * @return array List of page statuses.
828 function get_page_statuses() {
830 'draft' => __('Draft'),
831 'private' => __('Private'),
832 'publish' => __('Published')
839 * Register a post status. Do not use before init.
841 * A simple function for creating or modifying a post status based on the
842 * parameters given. The function will accept an array (second optional
843 * parameter), along with a string for the post status name.
846 * Optional $args contents:
848 * label - A descriptive name for the post status marked for translation. Defaults to $post_status.
849 * public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
850 * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false.
851 * show_in_admin_all_list - Whether to include posts in the edit listing for their post type
852 * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
853 * listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
855 * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
860 * @uses $wp_post_statuses Inserts new post status object into the list
862 * @param string $post_status Name of the post status.
863 * @param array|string $args See above description.
865 function register_post_status($post_status, $args = array()) {
866 global $wp_post_statuses;
868 if (!is_array($wp_post_statuses))
869 $wp_post_statuses = array();
871 // Args prefixed with an underscore are reserved for internal use.
874 'label_count' => false,
875 'exclude_from_search' => null,
881 'publicly_queryable' => null,
882 'show_in_admin_status_list' => null,
883 'show_in_admin_all_list' => null,
885 $args = wp_parse_args($args, $defaults);
886 $args = (object) $args;
888 $post_status = sanitize_key($post_status);
889 $args->name = $post_status;
891 if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
892 $args->internal = true;
894 if ( null === $args->public )
895 $args->public = false;
897 if ( null === $args->private )
898 $args->private = false;
900 if ( null === $args->protected )
901 $args->protected = false;
903 if ( null === $args->internal )
904 $args->internal = false;
906 if ( null === $args->publicly_queryable )
907 $args->publicly_queryable = $args->public;
909 if ( null === $args->exclude_from_search )
910 $args->exclude_from_search = $args->internal;
912 if ( null === $args->show_in_admin_all_list )
913 $args->show_in_admin_all_list = !$args->internal;
915 if ( null === $args->show_in_admin_status_list )
916 $args->show_in_admin_status_list = !$args->internal;
918 if ( false === $args->label )
919 $args->label = $post_status;
921 if ( false === $args->label_count )
922 $args->label_count = array( $args->label, $args->label );
924 $wp_post_statuses[$post_status] = $args;
930 * Retrieve a post status object by name
935 * @uses $wp_post_statuses
936 * @see register_post_status
937 * @see get_post_statuses
939 * @param string $post_status The name of a registered post status
940 * @return object A post status object
942 function get_post_status_object( $post_status ) {
943 global $wp_post_statuses;
945 if ( empty($wp_post_statuses[$post_status]) )
948 return $wp_post_statuses[$post_status];
952 * Get a list of all registered post status objects.
957 * @uses $wp_post_statuses
958 * @see register_post_status
959 * @see get_post_status_object
961 * @param array|string $args An array of key => value arguments to match against the post status objects.
962 * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
963 * @param string $operator The logical operation to perform. 'or' means only one element
964 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
965 * @return array A list of post status names or objects
967 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
968 global $wp_post_statuses;
970 $field = ('names' == $output) ? 'name' : false;
972 return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
976 * Whether the post type is hierarchical.
978 * A false return value might also mean that the post type does not exist.
981 * @see get_post_type_object
983 * @param string $post_type Post type name
984 * @return bool Whether post type is hierarchical.
986 function is_post_type_hierarchical( $post_type ) {
987 if ( ! post_type_exists( $post_type ) )
990 $post_type = get_post_type_object( $post_type );
991 return $post_type->hierarchical;
995 * Checks if a post type is registered.
998 * @uses get_post_type_object()
1000 * @param string $post_type Post type name
1001 * @return bool Whether post type is registered.
1003 function post_type_exists( $post_type ) {
1004 return (bool) get_post_type_object( $post_type );
1008 * Retrieve the post type of the current post or of a given post.
1012 * @param int|object $post Optional. Post ID or post object. Default is the current post from the loop.
1013 * @return string|bool Post type on success, false on failure.
1015 function get_post_type( $post = null ) {
1016 if ( $post = get_post( $post ) )
1017 return $post->post_type;
1023 * Retrieve a post type object by name
1025 * @package WordPress
1028 * @uses $wp_post_types
1029 * @see register_post_type
1030 * @see get_post_types
1032 * @param string $post_type The name of a registered post type
1033 * @return object A post type object
1035 function get_post_type_object( $post_type ) {
1036 global $wp_post_types;
1038 if ( empty($wp_post_types[$post_type]) )
1041 return $wp_post_types[$post_type];
1045 * Get a list of all registered post type objects.
1047 * @package WordPress
1050 * @uses $wp_post_types
1051 * @see register_post_type
1053 * @param array|string $args An array of key => value arguments to match against the post type objects.
1054 * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
1055 * @param string $operator The logical operation to perform. 'or' means only one element
1056 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
1057 * @return array A list of post type names or objects
1059 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
1060 global $wp_post_types;
1062 $field = ('names' == $output) ? 'name' : false;
1064 return wp_filter_object_list($wp_post_types, $args, $operator, $field);
1068 * Register a post type. Do not use before init.
1070 * A function for creating or modifying a post type based on the
1071 * parameters given. The function will accept an array (second optional
1072 * parameter), along with a string for the post type name.
1074 * Optional $args contents:
1076 * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
1077 * - labels - An array of labels for this post type.
1078 * * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones.
1079 * * You can see accepted values in {@link get_post_type_labels()}.
1080 * - description - A short descriptive summary of what the post type is. Defaults to blank.
1081 * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users.
1082 * * Defaults to false.
1083 * * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are
1084 * inherited from public, each does not rely on this relationship and controls a very specific intention.
1085 * - exclude_from_search - Whether to exclude posts with this post type from front end search results.
1086 * * If not set, the opposite of public's current value is used.
1087 * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request().
1088 * * ?post_type={post_type_key}
1089 * * ?{post_type_key}={single_post_slug}
1090 * * ?{post_type_query_var}={single_post_slug}
1091 * * If not set, the default is inherited from public.
1092 * - show_ui - Whether to generate a default UI for managing this post type in the admin.
1093 * * If not set, the default is inherited from public.
1094 * - show_in_nav_menus - Makes this post type available for selection in navigation menus.
1095 * * If not set, the default is inherited from public.
1096 * - show_in_menu - Where to show the post type in the admin menu.
1097 * * If true, the post type is shown in its own top level menu.
1098 * * If false, no menu is shown
1099 * * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will
1100 * be placed as a sub menu of that.
1101 * * show_ui must be true.
1102 * * If not set, the default is inherited from show_ui
1103 * - show_in_admin_bar - Makes this post type available via the admin bar.
1104 * * If not set, the default is inherited from show_in_menu
1105 * - menu_position - The position in the menu order the post type should appear.
1106 * * show_in_menu must be true
1107 * * Defaults to null, which places it at the bottom of its area.
1108 * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
1109 * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
1110 * * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
1111 * capabilities, e.g. array('story', 'stories').
1112 * - capabilities - Array of capabilities for this post type.
1113 * * By default the capability_type is used as a base to construct capabilities.
1114 * * You can see accepted values in {@link get_post_type_capabilities()}.
1115 * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
1116 * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false.
1117 * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
1118 * * See {@link add_post_type_support()} for documentation.
1119 * - register_meta_box_cb - Provide a callback function that will be called when setting up the
1120 * meta boxes for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
1121 * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
1122 * * Default is no taxonomies.
1123 * * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
1124 * - has_archive - True to enable post type archives. Default is false.
1125 * * Will generate the proper rewrite rules if rewrite is enabled.
1126 * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
1127 * * To prevent rewrite, set to false.
1128 * * To specify rewrite rules, an array can be passed with any of these keys
1129 * * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
1130 * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
1131 * * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
1132 * * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
1133 * * 'ep_mask' => const Assign an endpoint mask.
1134 * * If not specified and permalink_epmask is set, inherits from permalink_epmask.
1135 * * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
1136 * - query_var - Sets the query_var key for this post type. Defaults to $post_type key
1137 * * If false, a post type cannot be loaded at ?{query_var}={post_slug}
1138 * * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
1139 * - can_export - Allows this post type to be exported. Defaults to true.
1140 * - delete_with_user - Whether to delete posts of this type when deleting a user.
1141 * * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
1142 * * If false, posts of this type belonging to the user will *not* be trashed or deleted.
1143 * * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
1144 * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
1145 * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
1148 * @uses $wp_post_types Inserts new post type object into the list
1150 * @param string $post_type Post type key, must not exceed 20 characters
1151 * @param array|string $args See optional args description above.
1152 * @return object|WP_Error the registered post type object, or an error object
1154 function register_post_type( $post_type, $args = array() ) {
1155 global $wp_post_types, $wp_rewrite, $wp;
1157 if ( !is_array($wp_post_types) )
1158 $wp_post_types = array();
1160 // Args prefixed with an underscore are reserved for internal use.
1162 'labels' => array(), 'description' => '', 'publicly_queryable' => null, 'exclude_from_search' => null,
1163 'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null,
1164 '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'hierarchical' => false,
1165 'public' => false, 'rewrite' => true, 'has_archive' => false, 'query_var' => true,
1166 'supports' => array(), 'register_meta_box_cb' => null,
1167 'taxonomies' => array(), 'show_ui' => null, 'menu_position' => null, 'menu_icon' => null,
1168 'can_export' => true,
1169 'show_in_nav_menus' => null, 'show_in_menu' => null, 'show_in_admin_bar' => null,
1170 'delete_with_user' => null,
1172 $args = wp_parse_args($args, $defaults);
1173 $args = (object) $args;
1175 $post_type = sanitize_key($post_type);
1176 $args->name = $post_type;
1178 if ( strlen( $post_type ) > 20 )
1179 return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
1181 // If not set, default to the setting for public.
1182 if ( null === $args->publicly_queryable )
1183 $args->publicly_queryable = $args->public;
1185 // If not set, default to the setting for public.
1186 if ( null === $args->show_ui )
1187 $args->show_ui = $args->public;
1189 // If not set, default to the setting for show_ui.
1190 if ( null === $args->show_in_menu || ! $args->show_ui )
1191 $args->show_in_menu = $args->show_ui;
1193 // If not set, default to the whether the full UI is shown.
1194 if ( null === $args->show_in_admin_bar )
1195 $args->show_in_admin_bar = true === $args->show_in_menu;
1197 // Whether to show this type in nav-menus.php. Defaults to the setting for public.
1198 if ( null === $args->show_in_nav_menus )
1199 $args->show_in_nav_menus = $args->public;
1201 // If not set, default to true if not public, false if public.
1202 if ( null === $args->exclude_from_search )
1203 $args->exclude_from_search = !$args->public;
1205 // Back compat with quirky handling in version 3.0. #14122
1206 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1207 $args->map_meta_cap = true;
1209 if ( null === $args->map_meta_cap )
1210 $args->map_meta_cap = false;
1212 $args->cap = get_post_type_capabilities( $args );
1213 unset($args->capabilities);
1215 if ( is_array( $args->capability_type ) )
1216 $args->capability_type = $args->capability_type[0];
1218 if ( ! empty($args->supports) ) {
1219 add_post_type_support($post_type, $args->supports);
1220 unset($args->supports);
1221 } elseif ( false !== $args->supports ) {
1222 // Add default features
1223 add_post_type_support($post_type, array('title', 'editor'));
1226 if ( false !== $args->query_var && !empty($wp) ) {
1227 if ( true === $args->query_var )
1228 $args->query_var = $post_type;
1230 $args->query_var = sanitize_title_with_dashes($args->query_var);
1231 $wp->add_query_var($args->query_var);
1234 if ( false !== $args->rewrite && ( is_admin() || '' != get_option('permalink_structure') ) ) {
1235 if ( ! is_array( $args->rewrite ) )
1236 $args->rewrite = array();
1237 if ( empty( $args->rewrite['slug'] ) )
1238 $args->rewrite['slug'] = $post_type;
1239 if ( ! isset( $args->rewrite['with_front'] ) )
1240 $args->rewrite['with_front'] = true;
1241 if ( ! isset( $args->rewrite['pages'] ) )
1242 $args->rewrite['pages'] = true;
1243 if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1244 $args->rewrite['feeds'] = (bool) $args->has_archive;
1245 if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1246 if ( isset( $args->permalink_epmask ) )
1247 $args->rewrite['ep_mask'] = $args->permalink_epmask;
1249 $args->rewrite['ep_mask'] = EP_PERMALINK;
1252 if ( $args->hierarchical )
1253 add_rewrite_tag("%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
1255 add_rewrite_tag("%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
1257 if ( $args->has_archive ) {
1258 $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1259 if ( $args->rewrite['with_front'] )
1260 $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1262 $archive_slug = $wp_rewrite->root . $archive_slug;
1264 add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1265 if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1266 $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1267 add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1268 add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1270 if ( $args->rewrite['pages'] )
1271 add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1274 add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $args->rewrite );
1277 if ( $args->register_meta_box_cb )
1278 add_action('add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1);
1280 $args->labels = get_post_type_labels( $args );
1281 $args->label = $args->labels->name;
1283 $wp_post_types[$post_type] = $args;
1285 add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1287 foreach ( $args->taxonomies as $taxonomy ) {
1288 register_taxonomy_for_object_type( $taxonomy, $post_type );
1291 do_action( 'registered_post_type', $post_type, $args );
1297 * Builds an object with all post type capabilities out of a post type object
1299 * Post type capabilities use the 'capability_type' argument as a base, if the
1300 * capability is not set in the 'capabilities' argument array or if the
1301 * 'capabilities' argument is not supplied.
1303 * The capability_type argument can optionally be registered as an array, with
1304 * the first value being singular and the second plural, e.g. array('story, 'stories')
1305 * Otherwise, an 's' will be added to the value for the plural form. After
1306 * registration, capability_type will always be a string of the singular value.
1308 * By default, seven keys are accepted as part of the capabilities array:
1310 * - edit_post, read_post, and delete_post are meta capabilities, which are then
1311 * generally mapped to corresponding primitive capabilities depending on the
1312 * context, which would be the post being edited/read/deleted and the user or
1313 * role being checked. Thus these capabilities would generally not be granted
1314 * directly to users or roles.
1316 * - edit_posts - Controls whether objects of this post type can be edited.
1317 * - edit_others_posts - Controls whether objects of this type owned by other users
1318 * can be edited. If the post type does not support an author, then this will
1319 * behave like edit_posts.
1320 * - publish_posts - Controls publishing objects of this post type.
1321 * - read_private_posts - Controls whether private objects can be read.
1323 * These four primitive capabilities are checked in core in various locations.
1324 * There are also seven other primitive capabilities which are not referenced
1325 * directly in core, except in map_meta_cap(), which takes the three aforementioned
1326 * meta capabilities and translates them into one or more primitive capabilities
1327 * that must then be checked against the user or role, depending on the context.
1329 * - read - Controls whether objects of this post type can be read.
1330 * - delete_posts - Controls whether objects of this post type can be deleted.
1331 * - delete_private_posts - Controls whether private objects can be deleted.
1332 * - delete_published_posts - Controls whether published objects can be deleted.
1333 * - delete_others_posts - Controls whether objects owned by other users can be
1334 * can be deleted. If the post type does not support an author, then this will
1335 * behave like delete_posts.
1336 * - edit_private_posts - Controls whether private objects can be edited.
1337 * - edit_published_posts - Controls whether published objects can be edited.
1339 * These additional capabilities are only used in map_meta_cap(). Thus, they are
1340 * only assigned by default if the post type is registered with the 'map_meta_cap'
1341 * argument set to true (default is false).
1343 * @see map_meta_cap()
1346 * @param object $args Post type registration arguments
1347 * @return object object with all the capabilities as member variables
1349 function get_post_type_capabilities( $args ) {
1350 if ( ! is_array( $args->capability_type ) )
1351 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1353 // Singular base for meta capabilities, plural base for primitive capabilities.
1354 list( $singular_base, $plural_base ) = $args->capability_type;
1356 $default_capabilities = array(
1357 // Meta capabilities
1358 'edit_post' => 'edit_' . $singular_base,
1359 'read_post' => 'read_' . $singular_base,
1360 'delete_post' => 'delete_' . $singular_base,
1361 // Primitive capabilities used outside of map_meta_cap():
1362 'edit_posts' => 'edit_' . $plural_base,
1363 'edit_others_posts' => 'edit_others_' . $plural_base,
1364 'publish_posts' => 'publish_' . $plural_base,
1365 'read_private_posts' => 'read_private_' . $plural_base,
1368 // Primitive capabilities used within map_meta_cap():
1369 if ( $args->map_meta_cap ) {
1370 $default_capabilities_for_mapping = array(
1372 'delete_posts' => 'delete_' . $plural_base,
1373 'delete_private_posts' => 'delete_private_' . $plural_base,
1374 'delete_published_posts' => 'delete_published_' . $plural_base,
1375 'delete_others_posts' => 'delete_others_' . $plural_base,
1376 'edit_private_posts' => 'edit_private_' . $plural_base,
1377 'edit_published_posts' => 'edit_published_' . $plural_base,
1379 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1382 $capabilities = array_merge( $default_capabilities, $args->capabilities );
1384 // Post creation capability simply maps to edit_posts by default:
1385 if ( ! isset( $capabilities['create_posts'] ) )
1386 $capabilities['create_posts'] = $capabilities['edit_posts'];
1388 // Remember meta capabilities for future reference.
1389 if ( $args->map_meta_cap )
1390 _post_type_meta_capabilities( $capabilities );
1392 return (object) $capabilities;
1396 * Stores or returns a list of post type meta caps for map_meta_cap().
1401 function _post_type_meta_capabilities( $capabilities = null ) {
1402 static $meta_caps = array();
1403 if ( null === $capabilities )
1405 foreach ( $capabilities as $core => $custom ) {
1406 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1407 $meta_caps[ $custom ] = $core;
1412 * Builds an object with all post type labels out of a post type object
1414 * Accepted keys of the label array in the post type object:
1415 * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
1416 * - singular_name - name for one object of this post type. Default is Post/Page
1417 * - 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>
1418 * - add_new_item - Default is Add New Post/Add New Page
1419 * - edit_item - Default is Edit Post/Edit Page
1420 * - new_item - Default is New Post/New Page
1421 * - view_item - Default is View Post/View Page
1422 * - search_items - Default is Search Posts/Search Pages
1423 * - not_found - Default is No posts found/No pages found
1424 * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
1425 * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
1426 * - all_items - String for the submenu. Default is All Posts/All Pages
1427 * - menu_name - Default is the same as <code>name</code>
1429 * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
1432 * @param object $post_type_object
1433 * @return object object with all the labels as member variables
1435 function get_post_type_labels( $post_type_object ) {
1436 $nohier_vs_hier_defaults = array(
1437 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1438 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1439 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1440 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1441 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1442 'new_item' => array( __('New Post'), __('New Page') ),
1443 'view_item' => array( __('View Post'), __('View Page') ),
1444 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1445 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1446 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1447 'parent_item_colon' => array( null, __('Parent Page:') ),
1448 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
1450 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1452 $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1454 $post_type = $post_type_object->name;
1455 return apply_filters( "post_type_labels_{$post_type}", $labels );
1459 * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
1464 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1466 if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1467 $object->labels['name'] = $object->label;
1469 if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1470 $object->labels['singular_name'] = $object->labels['name'];
1472 if ( ! isset( $object->labels['name_admin_bar'] ) )
1473 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1475 if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1476 $object->labels['menu_name'] = $object->labels['name'];
1478 if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1479 $object->labels['all_items'] = $object->labels['menu_name'];
1481 foreach ( $nohier_vs_hier_defaults as $key => $value )
1482 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1484 $labels = array_merge( $defaults, $object->labels );
1485 return (object)$labels;
1489 * Adds submenus for post types.
1494 function _add_post_type_submenus() {
1495 foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1496 $ptype_obj = get_post_type_object( $ptype );
1498 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1500 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" );
1503 add_action( 'admin_menu', '_add_post_type_submenus' );
1506 * Register support of certain features for a post type.
1508 * All features are directly associated with a functional area of the edit screen, such as the
1509 * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
1510 * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
1512 * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
1513 * and the 'comments' feature dictates whether the comments count will show on the edit screen.
1516 * @param string $post_type The post type for which to add the feature
1517 * @param string|array $feature the feature being added, can be an array of feature strings or a single string
1519 function add_post_type_support( $post_type, $feature ) {
1520 global $_wp_post_type_features;
1522 $features = (array) $feature;
1523 foreach ($features as $feature) {
1524 if ( func_num_args() == 2 )
1525 $_wp_post_type_features[$post_type][$feature] = true;
1527 $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1532 * Remove support for a feature from a post type.
1535 * @param string $post_type The post type for which to remove the feature
1536 * @param string $feature The feature being removed
1538 function remove_post_type_support( $post_type, $feature ) {
1539 global $_wp_post_type_features;
1541 if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
1542 unset( $_wp_post_type_features[$post_type][$feature] );
1546 * Get all the post type features
1549 * @param string $post_type The post type
1553 function get_all_post_type_supports( $post_type ) {
1554 global $_wp_post_type_features;
1556 if ( isset( $_wp_post_type_features[$post_type] ) )
1557 return $_wp_post_type_features[$post_type];
1563 * Checks a post type's support for a given feature
1566 * @param string $post_type The post type being checked
1567 * @param string $feature the feature being checked
1571 function post_type_supports( $post_type, $feature ) {
1572 global $_wp_post_type_features;
1574 return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1578 * Updates the post type for the post ID.
1580 * The page or post cache will be cleaned for the post ID.
1586 * @param int $post_id Post ID to change post type. Not actually optional.
1587 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
1589 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
1591 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1594 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1595 $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1597 clean_post_cache( $post_id );
1603 * Retrieve list of latest posts or posts matching criteria.
1605 * The defaults are as follows:
1606 * 'numberposts' - Default is 5. Total number of posts to retrieve.
1607 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
1608 * 'category' - What category to pull the posts from.
1609 * 'orderby' - Default is 'post_date'. How to order the posts.
1610 * 'order' - Default is 'DESC'. The order to retrieve the posts.
1611 * 'include' - See {@link WP_Query::query()} for more.
1612 * 'exclude' - See {@link WP_Query::query()} for more.
1613 * 'meta_key' - See {@link WP_Query::query()} for more.
1614 * 'meta_value' - See {@link WP_Query::query()} for more.
1615 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
1616 * 'post_parent' - The parent of the post or post type.
1617 * 'post_status' - Default is 'publish'. Post status to retrieve.
1621 * @uses WP_Query::query() See for more default arguments and information.
1622 * @link http://codex.wordpress.org/Template_Tags/get_posts
1624 * @param array $args Optional. Overrides defaults.
1625 * @return array List of posts.
1627 function get_posts($args = null) {
1629 'numberposts' => 5, 'offset' => 0,
1630 'category' => 0, 'orderby' => 'post_date',
1631 'order' => 'DESC', 'include' => array(),
1632 'exclude' => array(), 'meta_key' => '',
1633 'meta_value' =>'', 'post_type' => 'post',
1634 'suppress_filters' => true
1637 $r = wp_parse_args( $args, $defaults );
1638 if ( empty( $r['post_status'] ) )
1639 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1640 if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1641 $r['posts_per_page'] = $r['numberposts'];
1642 if ( ! empty($r['category']) )
1643 $r['cat'] = $r['category'];
1644 if ( ! empty($r['include']) ) {
1645 $incposts = wp_parse_id_list( $r['include'] );
1646 $r['posts_per_page'] = count($incposts); // only the number of posts included
1647 $r['post__in'] = $incposts;
1648 } elseif ( ! empty($r['exclude']) )
1649 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1651 $r['ignore_sticky_posts'] = true;
1652 $r['no_found_rows'] = true;
1654 $get_posts = new WP_Query;
1655 return $get_posts->query($r);
1660 // Post meta functions
1664 * Add meta data field to a post.
1666 * Post meta data is called "Custom Fields" on the Administration Screen.
1670 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
1672 * @param int $post_id Post ID.
1673 * @param string $meta_key Metadata name.
1674 * @param mixed $meta_value Metadata value.
1675 * @param bool $unique Optional, default is false. Whether the same key should not be added.
1676 * @return int|bool Meta ID on success, false on failure.
1678 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
1679 // make sure meta is added to the post, not a revision
1680 if ( $the_post = wp_is_post_revision($post_id) )
1681 $post_id = $the_post;
1683 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1687 * Remove metadata matching criteria from a post.
1689 * You can match based on the key, or key and value. Removing based on key and
1690 * value, will keep from removing duplicate metadata with the same key. It also
1691 * allows removing all metadata matching key, if needed.
1695 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
1697 * @param int $post_id post ID
1698 * @param string $meta_key Metadata name.
1699 * @param mixed $meta_value Optional. Metadata value.
1700 * @return bool True on success, false on failure.
1702 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
1703 // make sure meta is added to the post, not a revision
1704 if ( $the_post = wp_is_post_revision($post_id) )
1705 $post_id = $the_post;
1707 return delete_metadata('post', $post_id, $meta_key, $meta_value);
1711 * Retrieve post meta field for a post.
1715 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
1717 * @param int $post_id Post ID.
1718 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1719 * @param bool $single Whether to return a single value.
1720 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1723 function get_post_meta($post_id, $key = '', $single = false) {
1724 return get_metadata('post', $post_id, $key, $single);
1728 * Update post meta field based on post ID.
1730 * Use the $prev_value parameter to differentiate between meta fields with the
1731 * same key and post ID.
1733 * If the meta field for the post does not exist, it will be added.
1737 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
1739 * @param int $post_id Post ID.
1740 * @param string $meta_key Metadata key.
1741 * @param mixed $meta_value Metadata value.
1742 * @param mixed $prev_value Optional. Previous value to check before removing.
1743 * @return bool True on success, false on failure.
1745 function update_post_meta($post_id, $meta_key, $meta_value, $prev_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 update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1754 * Delete everything from post meta matching meta key.
1759 * @param string $post_meta_key Key to search for when deleting.
1760 * @return bool Whether the post meta key was deleted from the database
1762 function delete_post_meta_by_key($post_meta_key) {
1763 return delete_metadata( 'post', null, $post_meta_key, '', true );
1767 * Retrieve post meta fields, based on post ID.
1769 * The post meta fields are retrieved from the cache where possible,
1770 * so the function is optimized to be called more than once.
1773 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
1775 * @param int $post_id Post ID.
1778 function get_post_custom( $post_id = 0 ) {
1779 $post_id = absint( $post_id );
1781 $post_id = get_the_ID();
1783 return get_post_meta( $post_id );
1787 * Retrieve meta field names for a post.
1789 * If there are no meta fields, then nothing (null) will be returned.
1792 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
1794 * @param int $post_id post ID
1795 * @return array|null Either array of the keys, or null if keys could not be retrieved.
1797 function get_post_custom_keys( $post_id = 0 ) {
1798 $custom = get_post_custom( $post_id );
1800 if ( !is_array($custom) )
1803 if ( $keys = array_keys($custom) )
1808 * Retrieve values for a custom post field.
1810 * The parameters must not be considered optional. All of the post meta fields
1811 * will be retrieved and only the meta field key values returned.
1814 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
1816 * @param string $key Meta field key.
1817 * @param int $post_id Post ID
1818 * @return array Meta field values.
1820 function get_post_custom_values( $key = '', $post_id = 0 ) {
1824 $custom = get_post_custom($post_id);
1826 return isset($custom[$key]) ? $custom[$key] : null;
1830 * Check if post is sticky.
1832 * Sticky posts should remain at the top of The Loop. If the post ID is not
1833 * given, then The Loop ID for the current post will be used.
1837 * @param int $post_id Optional. Post ID.
1838 * @return bool Whether post is sticky.
1840 function is_sticky( $post_id = 0 ) {
1841 $post_id = absint( $post_id );
1844 $post_id = get_the_ID();
1846 $stickies = get_option( 'sticky_posts' );
1848 if ( ! is_array( $stickies ) )
1851 if ( in_array( $post_id, $stickies ) )
1858 * Sanitize every post field.
1860 * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
1863 * @uses sanitize_post_field() Used to sanitize the fields.
1865 * @param object|WP_Post|array $post The Post Object or Array
1866 * @param string $context Optional, default is 'display'. How to sanitize post fields.
1867 * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post)
1869 function sanitize_post($post, $context = 'display') {
1870 if ( is_object($post) ) {
1871 // Check if post already filtered for this context
1872 if ( isset($post->filter) && $context == $post->filter )
1874 if ( !isset($post->ID) )
1876 foreach ( array_keys(get_object_vars($post)) as $field )
1877 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1878 $post->filter = $context;
1880 // Check if post already filtered for this context
1881 if ( isset($post['filter']) && $context == $post['filter'] )
1883 if ( !isset($post['ID']) )
1885 foreach ( array_keys($post) as $field )
1886 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1887 $post['filter'] = $context;
1893 * Sanitize post field based on context.
1895 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1896 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1897 * when calling filters.
1900 * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
1901 * $post_id if $context == 'edit' and field name prefix == 'post_'.
1903 * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
1904 * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
1905 * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
1907 * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
1908 * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
1909 * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
1910 * 'edit' and 'db' and field name prefix != 'post_'.
1912 * @param string $field The Post Object field name.
1913 * @param mixed $value The Post Object value.
1914 * @param int $post_id Post ID.
1915 * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
1916 * 'attribute' and 'js'.
1917 * @return mixed Sanitized value.
1919 function sanitize_post_field($field, $value, $post_id, $context) {
1920 $int_fields = array('ID', 'post_parent', 'menu_order');
1921 if ( in_array($field, $int_fields) )
1922 $value = (int) $value;
1924 // Fields which contain arrays of ints.
1925 $array_int_fields = array( 'ancestors' );
1926 if ( in_array($field, $array_int_fields) ) {
1927 $value = array_map( 'absint', $value);
1931 if ( 'raw' == $context )
1935 if ( false !== strpos($field, 'post_') ) {
1937 $field_no_prefix = str_replace('post_', '', $field);
1940 if ( 'edit' == $context ) {
1941 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1944 $value = apply_filters("edit_{$field}", $value, $post_id);
1946 $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
1948 $value = apply_filters("edit_post_{$field}", $value, $post_id);
1951 if ( in_array($field, $format_to_edit) ) {
1952 if ( 'post_content' == $field )
1953 $value = format_to_edit($value, user_can_richedit());
1955 $value = format_to_edit($value);
1957 $value = esc_attr($value);
1959 } else if ( 'db' == $context ) {
1961 $value = apply_filters("pre_{$field}", $value);
1962 $value = apply_filters("{$field_no_prefix}_save_pre", $value);
1964 $value = apply_filters("pre_post_{$field}", $value);
1965 $value = apply_filters("{$field}_pre", $value);
1968 // Use display filters by default.
1970 $value = apply_filters($field, $value, $post_id, $context);
1972 $value = apply_filters("post_{$field}", $value, $post_id, $context);
1975 if ( 'attribute' == $context )
1976 $value = esc_attr($value);
1977 else if ( 'js' == $context )
1978 $value = esc_js($value);
1984 * Make a post sticky.
1986 * Sticky posts should be displayed at the top of the front page.
1990 * @param int $post_id Post ID.
1992 function stick_post($post_id) {
1993 $stickies = get_option('sticky_posts');
1995 if ( !is_array($stickies) )
1996 $stickies = array($post_id);
1998 if ( ! in_array($post_id, $stickies) )
1999 $stickies[] = $post_id;
2001 update_option('sticky_posts', $stickies);
2007 * Sticky posts should be displayed at the top of the front page.
2011 * @param int $post_id Post ID.
2013 function unstick_post($post_id) {
2014 $stickies = get_option('sticky_posts');
2016 if ( !is_array($stickies) )
2019 if ( ! in_array($post_id, $stickies) )
2022 $offset = array_search($post_id, $stickies);
2023 if ( false === $offset )
2026 array_splice($stickies, $offset, 1);
2028 update_option('sticky_posts', $stickies);
2032 * Count number of posts of a post type and is user has permissions to view.
2034 * This function provides an efficient method of finding the amount of post's
2035 * type a blog has. Another method is to count the amount of items in
2036 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2037 * when developing for 2.5+, use this function instead.
2039 * The $perm parameter checks for 'readable' value and if the user can read
2040 * private posts, it will display that for the user that is signed in.
2043 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
2045 * @param string $type Optional. Post type to retrieve count
2046 * @param string $perm Optional. 'readable' or empty.
2047 * @return object Number of posts for each status
2049 function wp_count_posts( $type = 'post', $perm = '' ) {
2052 $user = wp_get_current_user();
2056 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2057 if ( 'readable' == $perm && is_user_logged_in() ) {
2058 $post_type_object = get_post_type_object($type);
2059 if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
2060 $cache_key .= '_' . $perm . '_' . $user->ID;
2061 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
2064 $query .= ' GROUP BY post_status';
2066 $count = wp_cache_get($cache_key, 'counts');
2067 if ( false !== $count )
2070 $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2073 foreach ( get_post_stati() as $state )
2076 foreach ( (array) $count as $row )
2077 $stats[$row['post_status']] = $row['num_posts'];
2079 $stats = (object) $stats;
2080 wp_cache_set($cache_key, $stats, 'counts');
2086 * Count number of attachments for the mime type(s).
2088 * If you set the optional mime_type parameter, then an array will still be
2089 * returned, but will only have the item you are looking for. It does not give
2090 * you the number of attachments that are children of a post. You can get that
2091 * by counting the number of children that post has.
2095 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
2096 * @return array Number of posts for each mime type.
2098 function wp_count_attachments( $mime_type = '' ) {
2101 $and = wp_post_mime_type_where( $mime_type );
2102 $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 );
2105 foreach( (array) $count as $row ) {
2106 $stats[$row['post_mime_type']] = $row['num_posts'];
2108 $stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2110 return (object) $stats;
2114 * Get default post mime types
2120 function get_post_mime_types() {
2121 $post_mime_types = array( // array( adj, noun )
2122 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2123 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2124 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2127 return apply_filters('post_mime_types', $post_mime_types);
2131 * Check a MIME-Type against a list.
2133 * If the wildcard_mime_types parameter is a string, it must be comma separated
2134 * list. If the real_mime_types is a string, it is also comma separated to
2139 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
2140 * flash (same as *flash*).
2141 * @param string|array $real_mime_types post_mime_type values
2142 * @return array array(wildcard=>array(real types))
2144 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
2146 if ( is_string($wildcard_mime_types) )
2147 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
2148 if ( is_string($real_mime_types) )
2149 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
2150 $wild = '[-._a-z0-9]*';
2151 foreach ( (array) $wildcard_mime_types as $type ) {
2152 $type = str_replace('*', $wild, $type);
2153 $patternses[1][$type] = "^$type$";
2154 if ( false === strpos($type, '/') ) {
2155 $patternses[2][$type] = "^$type/";
2156 $patternses[3][$type] = $type;
2160 foreach ( $patternses as $patterns )
2161 foreach ( $patterns as $type => $pattern )
2162 foreach ( (array) $real_mime_types as $real )
2163 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
2164 $matches[$type][] = $real;
2169 * Convert MIME types into SQL.
2173 * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
2174 * @param string $table_alias Optional. Specify a table alias, if needed.
2175 * @return string The SQL AND clause for mime searching.
2177 function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
2179 $wildcards = array('', '%', '%/%');
2180 if ( is_string($post_mime_types) )
2181 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2182 foreach ( (array) $post_mime_types as $mime_type ) {
2183 $mime_type = preg_replace('/\s/', '', $mime_type);
2184 $slashpos = strpos($mime_type, '/');
2185 if ( false !== $slashpos ) {
2186 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2187 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2188 if ( empty($mime_subgroup) )
2189 $mime_subgroup = '*';
2191 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2192 $mime_pattern = "$mime_group/$mime_subgroup";
2194 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2195 if ( false === strpos($mime_pattern, '*') )
2196 $mime_pattern .= '/*';
2199 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2201 if ( in_array( $mime_type, $wildcards ) )
2204 if ( false !== strpos($mime_pattern, '%') )
2205 $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2207 $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2209 if ( !empty($wheres) )
2210 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2215 * Trashes or deletes a post or page.
2217 * When the post and page is permanently deleted, everything that is tied to it is deleted also.
2218 * This includes comments, post meta fields, and terms associated with the post.
2220 * The post or page is moved to trash instead of permanently deleted unless trash is
2221 * disabled, item is already in the trash, or $force_delete is true.
2224 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
2225 * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
2226 * @uses wp_delete_attachment() if post type is 'attachment'.
2227 * @uses wp_trash_post() if item should be trashed.
2229 * @param int $postid Post ID.
2230 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
2231 * @return mixed False on failure
2233 function wp_delete_post( $postid = 0, $force_delete = false ) {
2236 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2239 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2240 return wp_trash_post($postid);
2242 if ( $post->post_type == 'attachment' )
2243 return wp_delete_attachment( $postid, $force_delete );
2245 do_action('before_delete_post', $postid);
2247 delete_post_meta($postid,'_wp_trash_meta_status');
2248 delete_post_meta($postid,'_wp_trash_meta_time');
2250 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2252 $parent_data = array( 'post_parent' => $post->post_parent );
2253 $parent_where = array( 'post_parent' => $postid );
2255 if ( is_post_type_hierarchical( $post->post_type ) ) {
2256 // Point children of this page to its parent, also clean the cache of affected children
2257 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2258 $children = $wpdb->get_results( $children_query );
2260 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2263 if ( 'page' == $post->post_type) {
2264 // if the page is defined in option page_on_front or post_for_posts,
2265 // adjust the corresponding options
2266 if ( get_option('page_on_front') == $postid ) {
2267 update_option('show_on_front', 'posts');
2268 delete_option('page_on_front');
2270 if ( get_option('page_for_posts') == $postid ) {
2271 delete_option('page_for_posts');
2274 unstick_post($postid);
2277 // Do raw query. wp_get_post_revisions() is filtered
2278 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2279 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2280 foreach ( $revision_ids as $revision_id )
2281 wp_delete_post_revision( $revision_id );
2283 // Point all attachments to this post up one level
2284 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2286 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2287 foreach ( $comment_ids as $comment_id )
2288 wp_delete_comment( $comment_id, true );
2290 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2291 foreach ( $post_meta_ids as $mid )
2292 delete_metadata_by_mid( 'post', $mid );
2294 do_action( 'delete_post', $postid );
2295 $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2296 do_action( 'deleted_post', $postid );
2298 clean_post_cache( $post );
2300 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2301 foreach ( $children as $child )
2302 clean_post_cache( $child );
2305 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2307 do_action('after_delete_post', $postid);
2313 * Moves a post or page to the Trash
2315 * If trash is disabled, the post or page is permanently deleted.
2318 * @uses do_action() on 'trash_post' before trashing
2319 * @uses do_action() on 'trashed_post' after trashing
2320 * @uses wp_delete_post() if trash is disabled
2322 * @param int $post_id Post ID.
2323 * @return mixed False on failure
2325 function wp_trash_post($post_id = 0) {
2326 if ( !EMPTY_TRASH_DAYS )
2327 return wp_delete_post($post_id, true);
2329 if ( !$post = get_post($post_id, ARRAY_A) )
2332 if ( $post['post_status'] == 'trash' )
2335 do_action('wp_trash_post', $post_id);
2337 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2338 add_post_meta($post_id,'_wp_trash_meta_time', time());
2340 $post['post_status'] = 'trash';
2341 wp_insert_post($post);
2343 wp_trash_post_comments($post_id);
2345 do_action('trashed_post', $post_id);
2351 * Restores a post or page from the Trash
2354 * @uses do_action() on 'untrash_post' before undeletion
2355 * @uses do_action() on 'untrashed_post' after undeletion
2357 * @param int $post_id Post ID.
2358 * @return mixed False on failure
2360 function wp_untrash_post($post_id = 0) {
2361 if ( !$post = get_post($post_id, ARRAY_A) )
2364 if ( $post['post_status'] != 'trash' )
2367 do_action('untrash_post', $post_id);
2369 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2371 $post['post_status'] = $post_status;
2373 delete_post_meta($post_id, '_wp_trash_meta_status');
2374 delete_post_meta($post_id, '_wp_trash_meta_time');
2376 wp_insert_post($post);
2378 wp_untrash_post_comments($post_id);
2380 do_action('untrashed_post', $post_id);
2386 * Moves comments for a post to the trash
2389 * @uses do_action() on 'trash_post_comments' before trashing
2390 * @uses do_action() on 'trashed_post_comments' after trashing
2392 * @param int|object $post Post ID or object.
2393 * @return mixed False on failure
2395 function wp_trash_post_comments($post = null) {
2398 $post = get_post($post);
2402 $post_id = $post->ID;
2404 do_action('trash_post_comments', $post_id);
2406 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2407 if ( empty($comments) )
2410 // Cache current status for each comment
2411 $statuses = array();
2412 foreach ( $comments as $comment )
2413 $statuses[$comment->comment_ID] = $comment->comment_approved;
2414 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2416 // Set status for all comments to post-trashed
2417 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2419 clean_comment_cache( array_keys($statuses) );
2421 do_action('trashed_post_comments', $post_id, $statuses);
2427 * Restore comments for a post from the trash
2430 * @uses do_action() on 'untrash_post_comments' before trashing
2431 * @uses do_action() on 'untrashed_post_comments' after trashing
2433 * @param int|object $post Post ID or object.
2434 * @return mixed False on failure
2436 function wp_untrash_post_comments($post = null) {
2439 $post = get_post($post);
2443 $post_id = $post->ID;
2445 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2447 if ( empty($statuses) )
2450 do_action('untrash_post_comments', $post_id);
2452 // Restore each comment to its original status
2453 $group_by_status = array();
2454 foreach ( $statuses as $comment_id => $comment_status )
2455 $group_by_status[$comment_status][] = $comment_id;
2457 foreach ( $group_by_status as $status => $comments ) {
2458 // Sanity check. This shouldn't happen.
2459 if ( 'post-trashed' == $status )
2461 $comments_in = implode( "', '", $comments );
2462 $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
2465 clean_comment_cache( array_keys($statuses) );
2467 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2469 do_action('untrashed_post_comments', $post_id);
2473 * Retrieve the list of categories for a post.
2475 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2476 * away from the complexity of the taxonomy layer.
2480 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
2482 * @param int $post_id Optional. The Post ID.
2483 * @param array $args Optional. Overwrite the defaults.
2486 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2487 $post_id = (int) $post_id;
2489 $defaults = array('fields' => 'ids');
2490 $args = wp_parse_args( $args, $defaults );
2492 $cats = wp_get_object_terms($post_id, 'category', $args);
2497 * Retrieve the tags for a post.
2499 * There is only one default for this function, called 'fields' and by default
2500 * is set to 'all'. There are other defaults that can be overridden in
2501 * {@link wp_get_object_terms()}.
2503 * @package WordPress
2507 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2509 * @param int $post_id Optional. The Post ID
2510 * @param array $args Optional. Overwrite the defaults
2511 * @return array List of post tags.
2513 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2514 return wp_get_post_terms( $post_id, 'post_tag', $args);
2518 * Retrieve the terms for a post.
2520 * There is only one default for this function, called 'fields' and by default
2521 * is set to 'all'. There are other defaults that can be overridden in
2522 * {@link wp_get_object_terms()}.
2524 * @package WordPress
2528 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2530 * @param int $post_id Optional. The Post ID
2531 * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
2532 * @param array $args Optional. Overwrite the defaults
2533 * @return array List of post tags.
2535 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2536 $post_id = (int) $post_id;
2538 $defaults = array('fields' => 'all');
2539 $args = wp_parse_args( $args, $defaults );
2541 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2547 * Retrieve number of recent posts.
2550 * @uses wp_parse_args()
2553 * @param string $deprecated Deprecated.
2554 * @param array $args Optional. Overrides defaults.
2555 * @param string $output Optional.
2558 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2560 if ( is_numeric( $args ) ) {
2561 _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2562 $args = array( 'numberposts' => absint( $args ) );
2565 // Set default arguments
2567 'numberposts' => 10, 'offset' => 0,
2568 'category' => 0, 'orderby' => 'post_date',
2569 'order' => 'DESC', 'include' => '',
2570 'exclude' => '', 'meta_key' => '',
2571 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2572 'suppress_filters' => true
2575 $r = wp_parse_args( $args, $defaults );
2577 $results = get_posts( $r );
2579 // Backward compatibility. Prior to 3.1 expected posts to be returned in array
2580 if ( ARRAY_A == $output ){
2581 foreach( $results as $key => $result ) {
2582 $results[$key] = get_object_vars( $result );
2584 return $results ? $results : array();
2587 return $results ? $results : false;
2594 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2596 * You can set the post date manually, by setting the values for 'post_date'
2597 * and 'post_date_gmt' keys. You can close the comments or open the comments by
2598 * setting the value for 'comment_status' key.
2600 * The defaults for the parameter $postarr are:
2601 * 'post_status' - Default is 'draft'.
2602 * 'post_type' - Default is 'post'.
2603 * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post.
2604 * 'ping_status' - Default is the value in 'default_ping_status' option.
2605 * Whether the attachment can accept pings.
2606 * 'post_parent' - Default is 0. Set this for the post it belongs to, if any.
2607 * 'menu_order' - Default is 0. The order it is displayed.
2608 * 'to_ping' - Whether to ping.
2609 * 'pinged' - Default is empty string.
2610 * 'post_password' - Default is empty string. The password to access the attachment.
2611 * 'guid' - Global Unique ID for referencing the attachment.
2612 * 'post_content_filtered' - Post content filtered.
2613 * 'post_excerpt' - Post excerpt.
2618 * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
2619 * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
2620 * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
2621 * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
2622 * @uses wp_transition_post_status()
2624 * @param array $postarr Elements that make up post to insert.
2625 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2626 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
2628 function wp_insert_post($postarr, $wp_error = false) {
2629 global $wpdb, $user_ID;
2631 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
2632 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2633 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
2634 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
2635 'post_content' => '', 'post_title' => '');
2637 $postarr = wp_parse_args($postarr, $defaults);
2639 unset( $postarr[ 'filter' ] );
2641 $postarr = sanitize_post($postarr, 'db');
2643 // export array as variables
2644 extract($postarr, EXTR_SKIP);
2646 // Are we updating or creating?
2649 if ( ! empty( $ID ) ) {
2652 // Get the post ID and GUID
2654 $post_before = get_post( $post_ID );
2655 if ( is_null( $post_before ) ) {
2657 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2661 $guid = get_post_field( 'guid', $post_ID );
2662 $previous_status = get_post_field('post_status', $ID);
2664 $previous_status = 'new';
2667 $maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' )
2668 && post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' );
2670 if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2672 return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2677 if ( empty($post_type) )
2678 $post_type = 'post';
2680 if ( empty($post_status) )
2681 $post_status = 'draft';
2683 if ( !empty($post_category) )
2684 $post_category = array_filter($post_category); // Filter out empty terms
2686 // Make sure we set a valid category.
2687 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
2688 // 'post' requires at least one category.
2689 if ( 'post' == $post_type && 'auto-draft' != $post_status )
2690 $post_category = array( get_option('default_category') );
2692 $post_category = array();
2695 if ( empty($post_author) )
2696 $post_author = $user_ID;
2698 // Don't allow contributors to set the post slug for pending review posts
2699 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
2702 // Create a valid post name. Drafts and pending posts are allowed to have an empty
2704 if ( empty($post_name) ) {
2705 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2706 $post_name = sanitize_title($post_title);
2710 // On updates, we need to check to see if it's using the old, fixed sanitization context.
2711 $check_name = sanitize_title( $post_name, '', 'old-save' );
2712 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name )
2713 $post_name = $check_name;
2714 else // new post, or slug has changed.
2715 $post_name = sanitize_title($post_name);
2718 // 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
2719 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
2720 $post_date = current_time('mysql');
2722 // validate the date
2723 $mm = substr( $post_date, 5, 2 );
2724 $jj = substr( $post_date, 8, 2 );
2725 $aa = substr( $post_date, 0, 4 );
2726 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
2727 if ( !$valid_date ) {
2729 return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
2734 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
2735 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2736 $post_date_gmt = get_gmt_from_date($post_date);
2738 $post_date_gmt = '0000-00-00 00:00:00';
2741 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
2742 $post_modified = current_time( 'mysql' );
2743 $post_modified_gmt = current_time( 'mysql', 1 );
2745 $post_modified = $post_date;
2746 $post_modified_gmt = $post_date_gmt;
2749 if ( 'publish' == $post_status ) {
2750 $now = gmdate('Y-m-d H:i:59');
2751 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
2752 $post_status = 'future';
2753 } elseif( 'future' == $post_status ) {
2754 $now = gmdate('Y-m-d H:i:59');
2755 if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
2756 $post_status = 'publish';
2759 if ( empty($comment_status) ) {
2761 $comment_status = 'closed';
2763 $comment_status = get_option('default_comment_status');
2765 if ( empty($ping_status) )
2766 $ping_status = get_option('default_ping_status');
2768 if ( isset($to_ping) )
2769 $to_ping = sanitize_trackback_urls( $to_ping );
2773 if ( ! isset($pinged) )
2776 if ( isset($post_parent) )
2777 $post_parent = (int) $post_parent;
2781 // Check the post_parent to see if it will cause a hierarchy loop
2782 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
2784 if ( isset($menu_order) )
2785 $menu_order = (int) $menu_order;
2789 if ( !isset($post_password) || 'private' == $post_status )
2790 $post_password = '';
2792 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2794 // expected_slashed (everything!)
2795 $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' ) );
2796 $data = apply_filters('wp_insert_post_data', $data, $postarr);
2797 $data = wp_unslash( $data );
2798 $where = array( 'ID' => $post_ID );
2801 do_action( 'pre_post_update', $post_ID, $data );
2802 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
2804 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
2809 if ( isset($post_mime_type) )
2810 $data['post_mime_type'] = wp_unslash( $post_mime_type ); // This isn't in the update
2811 // If there is a suggested ID, use it if not already present
2812 if ( !empty($import_id) ) {
2813 $import_id = (int) $import_id;
2814 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2815 $data['ID'] = $import_id;
2818 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
2820 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
2824 $post_ID = (int) $wpdb->insert_id;
2826 // use the newly generated $post_ID
2827 $where = array( 'ID' => $post_ID );
2830 if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
2831 $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
2832 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
2835 if ( is_object_in_taxonomy($post_type, 'category') )
2836 wp_set_post_categories( $post_ID, $post_category );
2838 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
2839 wp_set_post_tags( $post_ID, $tags_input );
2841 // new-style support for all custom taxonomies
2842 if ( !empty($tax_input) ) {
2843 foreach ( $tax_input as $taxonomy => $tags ) {
2844 $taxonomy_obj = get_taxonomy($taxonomy);
2845 if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
2846 $tags = array_filter($tags);
2847 if ( current_user_can($taxonomy_obj->cap->assign_terms) )
2848 wp_set_post_terms( $post_ID, $tags, $taxonomy );
2852 $current_guid = get_post_field( 'guid', $post_ID );
2855 if ( !$update && '' == $current_guid )
2856 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
2858 clean_post_cache( $post_ID );
2860 $post = get_post($post_ID);
2862 if ( !empty($page_template) && 'page' == $data['post_type'] ) {
2863 $post->page_template = $page_template;
2864 $page_templates = wp_get_theme()->get_page_templates();
2865 if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) {
2867 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
2871 update_post_meta($post_ID, '_wp_page_template', $page_template);
2874 wp_transition_post_status($data['post_status'], $previous_status, $post);
2877 do_action('edit_post', $post_ID, $post);
2878 $post_after = get_post($post_ID);
2879 do_action( 'post_updated', $post_ID, $post_after, $post_before);
2882 do_action('save_post', $post_ID, $post);
2883 do_action('wp_insert_post', $post_ID, $post);
2889 * Update a post with new post data.
2891 * The date does not have to be set for drafts. You can set the date and it will
2892 * not be overridden.
2896 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
2897 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2898 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
2900 function wp_update_post( $postarr = array(), $wp_error = false ) {
2901 if ( is_object($postarr) ) {
2902 // non-escaped post was passed
2903 $postarr = get_object_vars($postarr);
2904 $postarr = wp_slash($postarr);
2907 // First, get all of the original fields
2908 $post = get_post($postarr['ID'], ARRAY_A);
2910 if ( is_null( $post ) ) {
2912 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2916 // Escape data pulled from DB.
2917 $post = wp_slash($post);
2919 // Passed post category list overwrites existing category list if not empty.
2920 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
2921 && 0 != count($postarr['post_category']) )
2922 $post_cats = $postarr['post_category'];
2924 $post_cats = $post['post_category'];
2926 // Drafts shouldn't be assigned a date unless explicitly done so by the user
2927 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
2928 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
2931 $clear_date = false;
2933 // Merge old and new fields with new fields overwriting old ones.
2934 $postarr = array_merge($post, $postarr);
2935 $postarr['post_category'] = $post_cats;
2936 if ( $clear_date ) {
2937 $postarr['post_date'] = current_time('mysql');
2938 $postarr['post_date_gmt'] = '';
2941 if ($postarr['post_type'] == 'attachment')
2942 return wp_insert_attachment($postarr);
2944 return wp_insert_post( $postarr, $wp_error );
2948 * Publish a post by transitioning the post status.
2952 * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
2954 * @param int|object $post Post ID or object.
2956 function wp_publish_post( $post ) {
2959 if ( ! $post = get_post( $post ) )
2962 if ( 'publish' == $post->post_status )
2965 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
2967 clean_post_cache( $post->ID );
2969 $old_status = $post->post_status;
2970 $post->post_status = 'publish';
2971 wp_transition_post_status( 'publish', $old_status, $post );
2973 do_action( 'edit_post', $post->ID, $post );
2974 do_action( 'save_post', $post->ID, $post );
2975 do_action( 'wp_insert_post', $post->ID, $post );
2979 * Publish future post and make sure post ID has future post status.
2981 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
2982 * from publishing drafts, etc.
2986 * @param int $post_id Post ID.
2987 * @return null Nothing is returned. Which can mean that no action is required or post was published.
2989 function check_and_publish_future_post($post_id) {
2991 $post = get_post($post_id);
2996 if ( 'future' != $post->post_status )
2999 $time = strtotime( $post->post_date_gmt . ' GMT' );
3001 if ( $time > time() ) { // Uh oh, someone jumped the gun!
3002 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3003 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3007 return wp_publish_post($post_id);
3011 * Computes a unique slug for the post, when given the desired slug and some post details.
3015 * @global wpdb $wpdb
3016 * @global WP_Rewrite $wp_rewrite
3017 * @param string $slug the desired slug (post_name)
3018 * @param integer $post_ID
3019 * @param string $post_status no uniqueness checks are made if the post is still draft or pending
3020 * @param string $post_type
3021 * @param integer $post_parent
3022 * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3024 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3025 if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3028 global $wpdb, $wp_rewrite;
3030 $original_slug = $slug;
3032 $feeds = $wp_rewrite->feeds;
3033 if ( ! is_array( $feeds ) )
3036 $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
3037 if ( 'attachment' == $post_type ) {
3038 // Attachment slugs must be unique across all types.
3039 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3040 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3042 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3045 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3046 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3048 } while ( $post_name_check );
3049 $slug = $alt_post_name;
3051 } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
3052 if ( 'nav_menu_item' == $post_type )
3054 // Page slugs must be unique within their own trees. Pages are in a separate
3055 // namespace than posts so page slugs are allowed to overlap post slugs.
3056 $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";
3057 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
3059 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 ) ) {
3062 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3063 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
3065 } while ( $post_name_check );
3066 $slug = $alt_post_name;
3069 // Post slugs must be unique across all posts.
3070 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3071 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3073 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3076 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3077 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3079 } while ( $post_name_check );
3080 $slug = $alt_post_name;
3084 return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3088 * Truncates a post slug.
3092 * @uses utf8_uri_encode() Makes sure UTF-8 characters are properly cut and encoded.
3094 * @param string $slug The slug to truncate.
3095 * @param int $length Max length of the slug.
3096 * @return string The truncated slug.
3098 function _truncate_post_slug( $slug, $length = 200 ) {
3099 if ( strlen( $slug ) > $length ) {
3100 $decoded_slug = urldecode( $slug );
3101 if ( $decoded_slug === $slug )
3102 $slug = substr( $slug, 0, $length );
3104 $slug = utf8_uri_encode( $decoded_slug, $length );
3107 return rtrim( $slug, '-' );
3111 * Adds tags to a post.
3113 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
3115 * @package WordPress
3119 * @param int $post_id Post ID
3120 * @param string $tags The tags to set for the post, separated by commas.
3121 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
3123 function wp_add_post_tags($post_id = 0, $tags = '') {
3124 return wp_set_post_tags($post_id, $tags, true);
3128 * Set the tags for a post.
3131 * @uses wp_set_object_terms() Sets the tags for the post.
3133 * @param int $post_id Post ID.
3134 * @param string $tags The tags to set for the post, separated by commas.
3135 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3136 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3138 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3139 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3143 * Set the terms for a post.
3146 * @uses wp_set_object_terms() Sets the tags for the post.
3148 * @param int $post_id Post ID.
3149 * @param string $tags The tags to set for the post, separated by commas.
3150 * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'.
3151 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3152 * @return mixed Array of affected term IDs. WP_Error or false on failure.
3154 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3155 $post_id = (int) $post_id;
3163 if ( ! is_array( $tags ) ) {
3164 $comma = _x( ',', 'tag delimiter' );
3165 if ( ',' !== $comma )
3166 $tags = str_replace( $comma, ',', $tags );
3167 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3170 // Hierarchical taxonomies must always pass IDs rather than names so that children with the same
3171 // names but different parents aren't confused.
3172 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3173 $tags = array_unique( array_map( 'intval', $tags ) );
3176 return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3180 * Set categories for a post.
3182 * If the post categories parameter is not set, then the default category is
3187 * @param int $post_ID Post ID.
3188 * @param array $post_categories Optional. List of categories.
3189 * @return bool|mixed
3191 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
3192 $post_ID = (int) $post_ID;
3193 $post_type = get_post_type( $post_ID );
3194 $post_status = get_post_status( $post_ID );
3195 // If $post_categories isn't already an array, make it one:
3196 if ( !is_array($post_categories) || empty($post_categories) ) {
3197 if ( 'post' == $post_type && 'auto-draft' != $post_status )
3198 $post_categories = array( get_option('default_category') );
3200 $post_categories = array();
3201 } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
3205 return wp_set_post_terms($post_ID, $post_categories, 'category');
3209 * Transition the post status of a post.
3211 * Calls hooks to transition post status.
3213 * The first is 'transition_post_status' with new status, old status, and post data.
3215 * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
3216 * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
3219 * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
3220 * parameter and POSTTYPE is post_type post data.
3223 * @link http://codex.wordpress.org/Post_Status_Transitions
3225 * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
3226 * $post if there is a status change.
3227 * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
3228 * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
3230 * @param string $new_status Transition to this post status.
3231 * @param string $old_status Previous post status.
3232 * @param object $post Post data.
3234 function wp_transition_post_status($new_status, $old_status, $post) {
3235 do_action('transition_post_status', $new_status, $old_status, $post);
3236 do_action("{$old_status}_to_{$new_status}", $post);
3237 do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
3241 // Trackback and ping functions
3245 * Add a URL to those already pung.
3250 * @param int $post_id Post ID.
3251 * @param string $uri Ping URI.
3252 * @return int How many rows were updated.
3254 function add_ping($post_id, $uri) {
3256 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3257 $pung = trim($pung);
3258 $pung = preg_split('/\s/', $pung);
3260 $new = implode("\n", $pung);
3261 $new = apply_filters('add_ping', $new);
3262 // expected_slashed ($new)
3263 $new = wp_unslash($new);
3264 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3268 * Retrieve enclosures already enclosed for a post.
3273 * @param int $post_id Post ID.
3274 * @return array List of enclosures
3276 function get_enclosed($post_id) {
3277 $custom_fields = get_post_custom( $post_id );
3279 if ( !is_array( $custom_fields ) )
3282 foreach ( $custom_fields as $key => $val ) {
3283 if ( 'enclosure' != $key || !is_array( $val ) )
3285 foreach( $val as $enc ) {
3286 $enclosure = explode( "\n", $enc );
3287 $pung[] = trim( $enclosure[ 0 ] );
3290 $pung = apply_filters('get_enclosed', $pung, $post_id);
3295 * Retrieve URLs already pinged for a post.
3300 * @param int $post_id Post ID.
3303 function get_pung($post_id) {
3305 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3306 $pung = trim($pung);
3307 $pung = preg_split('/\s/', $pung);
3308 $pung = apply_filters('get_pung', $pung);
3313 * Retrieve URLs that need to be pinged.
3318 * @param int $post_id Post ID
3321 function get_to_ping($post_id) {
3323 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
3324 $to_ping = sanitize_trackback_urls( $to_ping );
3325 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
3326 $to_ping = apply_filters('get_to_ping', $to_ping);
3331 * Do trackbacks for a list of URLs.
3335 * @param string $tb_list Comma separated list of URLs
3336 * @param int $post_id Post ID
3338 function trackback_url_list($tb_list, $post_id) {
3339 if ( ! empty( $tb_list ) ) {
3341 $postdata = get_post($post_id, ARRAY_A);
3343 // import postdata as variables
3344 extract($postdata, EXTR_SKIP);
3347 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
3349 if (strlen($excerpt) > 255) {
3350 $excerpt = substr($excerpt,0,252) . '…';
3353 $trackback_urls = explode(',', $tb_list);
3354 foreach( (array) $trackback_urls as $tb_url) {
3355 $tb_url = trim($tb_url);
3356 trackback($tb_url, wp_unslash($post_title), $excerpt, $post_id);
3366 * Get a list of page IDs.
3371 * @return array List of page IDs.
3373 function get_all_page_ids() {
3376 $page_ids = wp_cache_get('all_page_ids', 'posts');
3377 if ( ! is_array( $page_ids ) ) {
3378 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
3379 wp_cache_add('all_page_ids', $page_ids, 'posts');
3386 * Retrieves page data given a page ID or page object.
3388 * Use get_post() instead of get_page().
3393 * @param mixed $page Page object or page ID. Passed by reference.
3394 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
3395 * @param string $filter How the return value should be filtered.
3396 * @return WP_Post|null WP_Post on success or null on failure
3398 function get_page( $page, $output = OBJECT, $filter = 'raw') {
3399 return get_post( $page, $output, $filter );
3403 * Retrieves a page given its path.
3408 * @param string $page_path Page path
3409 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3410 * @param string $post_type Optional. Post type. Default page.
3411 * @return WP_Post|null WP_Post on success or null on failure
3413 function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
3416 $page_path = rawurlencode(urldecode($page_path));
3417 $page_path = str_replace('%2F', '/', $page_path);
3418 $page_path = str_replace('%20', ' ', $page_path);
3419 $parts = explode( '/', trim( $page_path, '/' ) );
3420 $parts = esc_sql( $parts );
3421 $parts = array_map( 'sanitize_title_for_query', $parts );
3423 $in_string = "'". implode( "','", $parts ) . "'";
3424 $post_type_sql = esc_sql( $post_type );
3425 $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 );
3427 $revparts = array_reverse( $parts );
3430 foreach ( (array) $pages as $page ) {
3431 if ( $page->post_name == $revparts[0] ) {
3434 while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
3436 $parent = $pages[ $p->post_parent ];
3437 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
3442 if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
3443 $foundid = $page->ID;
3444 if ( $page->post_type == $post_type )
3451 return get_post( $foundid, $output );
3457 * Retrieve a page given its title.
3462 * @param string $page_title Page title
3463 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3464 * @param string $post_type Optional. Post type. Default page.
3465 * @return WP_Post|null WP_Post on success or null on failure
3467 function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
3469 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
3471 return get_post( $page, $output );
3477 * Retrieve child pages from list of pages matching page ID.
3479 * Matches against the pages parameter against the page ID. Also matches all
3480 * children for the same to retrieve all children of a page. Does not make any
3481 * SQL queries to get the children.
3485 * @param int $page_id Page ID.
3486 * @param array $pages List of pages' objects.
3489 function get_page_children($page_id, $pages) {
3490 $page_list = array();
3491 foreach ( (array) $pages as $page ) {
3492 if ( $page->post_parent == $page_id ) {
3493 $page_list[] = $page;
3494 if ( $children = get_page_children($page->ID, $pages) )
3495 $page_list = array_merge($page_list, $children);
3502 * Order the pages with children under parents in a flat list.
3504 * It uses auxiliary structure to hold parent-children relationships and
3505 * runs in O(N) complexity
3509 * @param array $pages Posts array.
3510 * @param int $page_id Parent page ID.
3511 * @return array A list arranged by hierarchy. Children immediately follow their parents.
3513 function get_page_hierarchy( &$pages, $page_id = 0 ) {
3514 if ( empty( $pages ) ) {
3519 $children = array();
3520 foreach ( (array) $pages as $p ) {
3521 $parent_id = intval( $p->post_parent );
3522 $children[ $parent_id ][] = $p;
3526 _page_traverse_name( $page_id, $children, $result );
3532 * function to traverse and return all the nested children post names of a root page.
3533 * $children contains parent-children relations
3537 function _page_traverse_name( $page_id, &$children, &$result ){
3538 if ( isset( $children[ $page_id ] ) ){
3539 foreach( (array)$children[ $page_id ] as $child ) {
3540 $result[ $child->ID ] = $child->post_name;
3541 _page_traverse_name( $child->ID, $children, $result );
3547 * Builds URI for a page.
3549 * Sub pages will be in the "directory" under the parent page post name.
3553 * @param mixed $page Page object or page ID.
3554 * @return string Page URI.
3556 function get_page_uri($page) {
3557 $page = get_post( $page );
3559 $uri = $page->post_name;
3561 foreach ( $page->ancestors as $parent ) {
3562 $uri = get_post( $parent )->post_name . "/" . $uri;
3569 * Retrieve a list of pages.
3571 * The defaults that can be overridden are the following: 'child_of',
3572 * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
3573 * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
3578 * @param mixed $args Optional. Array or string of options that overrides defaults.
3579 * @return array List of pages matching defaults or $args
3581 function get_pages($args = '') {
3587 'child_of' => 0, 'sort_order' => 'ASC',
3588 'sort_column' => 'post_title', 'hierarchical' => 1,
3589 'exclude' => array(), 'include' => array(),
3590 'meta_key' => '', 'meta_value' => '',
3591 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
3592 'number' => '', 'offset' => 0,
3593 'post_type' => 'page', 'post_status' => 'publish',
3596 $r = wp_parse_args( $args, $defaults );
3597 extract( $r, EXTR_SKIP );
3598 $number = (int) $number;
3599 $offset = (int) $offset;
3601 // Make sure the post type is hierarchical
3602 $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
3603 if ( !in_array( $post_type, $hierarchical_post_types ) )
3606 // Make sure we have a valid post status
3607 if ( !is_array( $post_status ) )
3608 $post_status = explode( ',', $post_status );
3609 if ( array_diff( $post_status, get_post_stati() ) )
3612 // $args can be whatever, only use the args defined in defaults to compute the key
3613 $key = md5( serialize( compact(array_keys($defaults)) ) );
3614 $last_changed = wp_cache_get( 'last_changed', 'posts' );
3615 if ( ! $last_changed ) {
3616 $last_changed = microtime();
3617 wp_cache_set( 'last_changed', $last_changed, 'posts' );
3620 $cache_key = "get_pages:$key:$last_changed";
3621 if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
3622 // Convert to WP_Post instances
3623 $pages = array_map( 'get_post', $cache );
3624 $pages = apply_filters('get_pages', $pages, $r);
3628 if ( !is_array($cache) )
3632 if ( !empty($include) ) {
3633 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
3638 $hierarchical = false;
3639 $incpages = wp_parse_id_list( $include );
3640 if ( ! empty( $incpages ) ) {
3641 foreach ( $incpages as $incpage ) {
3642 if (empty($inclusions))
3643 $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
3645 $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
3649 if (!empty($inclusions))
3653 if ( !empty($exclude) ) {
3654 $expages = wp_parse_id_list( $exclude );
3655 if ( ! empty( $expages ) ) {
3656 foreach ( $expages as $expage ) {
3657 if (empty($exclusions))
3658 $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
3660 $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
3664 if (!empty($exclusions))
3668 if (!empty($authors)) {
3669 $post_authors = preg_split('/[\s,]+/',$authors);
3671 if ( ! empty( $post_authors ) ) {
3672 foreach ( $post_authors as $post_author ) {
3673 //Do we have an author id or an author login?
3674 if ( 0 == intval($post_author) ) {
3675 $post_author = get_user_by('login', $post_author);
3676 if ( empty($post_author) )
3678 if ( empty($post_author->ID) )
3680 $post_author = $post_author->ID;
3683 if ( '' == $author_query )
3684 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
3686 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
3688 if ( '' != $author_query )
3689 $author_query = " AND ($author_query)";
3694 $where = "$exclusions $inclusions ";
3695 if ( '' !== $meta_key || '' !== $meta_value ) {
3696 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
3698 // meta_key and meta_value might be slashed
3699 $meta_key = wp_unslash($meta_key);
3700 $meta_value = wp_unslash($meta_value);
3701 if ( '' !== $meta_key )
3702 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
3703 if ( '' !== $meta_value )
3704 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
3709 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
3711 if ( 1 == count( $post_status ) ) {
3712 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
3714 $post_status = implode( "', '", $post_status );
3715 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
3718 $orderby_array = array();
3719 $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
3720 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
3721 'ID', 'rand', 'comment_count');
3722 foreach ( explode( ',', $sort_column ) as $orderby ) {
3723 $orderby = trim( $orderby );
3724 if ( !in_array( $orderby, $allowed_keys ) )
3727 switch ( $orderby ) {
3731 $orderby = "$wpdb->posts.ID";
3734 $orderby = 'RAND()';
3736 case 'comment_count':
3737 $orderby = "$wpdb->posts.comment_count";
3740 if ( 0 === strpos( $orderby, 'post_' ) )
3741 $orderby = "$wpdb->posts." . $orderby;
3743 $orderby = "$wpdb->posts.post_" . $orderby;
3746 $orderby_array[] = $orderby;
3749 $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
3751 $sort_order = strtoupper( $sort_order );
3752 if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
3753 $sort_order = 'ASC';
3755 $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
3756 $query .= $author_query;
3757 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
3759 if ( !empty($number) )
3760 $query .= ' LIMIT ' . $offset . ',' . $number;
3762 $pages = $wpdb->get_results($query);
3764 if ( empty($pages) ) {
3765 $pages = apply_filters('get_pages', array(), $r);
3769 // Sanitize before caching so it'll only get done once
3770 $num_pages = count($pages);
3771 for ($i = 0; $i < $num_pages; $i++) {
3772 $pages[$i] = sanitize_post($pages[$i], 'raw');
3776 update_post_cache( $pages );
3778 if ( $child_of || $hierarchical )
3779 $pages = get_page_children($child_of, $pages);
3781 if ( !empty($exclude_tree) ) {
3782 $exclude = (int) $exclude_tree;
3783 $children = get_page_children($exclude, $pages);
3784 $excludes = array();
3785 foreach ( $children as $child )
3786 $excludes[] = $child->ID;
3787 $excludes[] = $exclude;
3788 $num_pages = count($pages);
3789 for ( $i = 0; $i < $num_pages; $i++ ) {
3790 if ( in_array($pages[$i]->ID, $excludes) )
3795 $page_structure = array();
3796 foreach ( $pages as $page )
3797 $page_structure[] = $page->ID;
3799 wp_cache_set( $cache_key, $page_structure, 'posts' );
3801 // Convert to WP_Post instances
3802 $pages = array_map( 'get_post', $pages );
3804 $pages = apply_filters('get_pages', $pages, $r);
3810 // Attachment functions
3814 * Check if the attachment URI is local one and is really an attachment.
3818 * @param string $url URL to check
3819 * @return bool True on success, false on failure.
3821 function is_local_attachment($url) {
3822 if (strpos($url, home_url()) === false)
3824 if (strpos($url, home_url('/?attachment_id=')) !== false)
3826 if ( $id = url_to_postid($url) ) {
3827 $post = get_post($id);
3828 if ( 'attachment' == $post->post_type )
3835 * Insert an attachment.
3837 * If you set the 'ID' in the $object parameter, it will mean that you are
3838 * updating and attempt to update the attachment. You can also set the
3839 * attachment name or title by setting the key 'post_name' or 'post_title'.
3841 * You can set the dates for the attachment manually by setting the 'post_date'
3842 * and 'post_date_gmt' keys' values.
3844 * By default, the comments will use the default settings for whether the
3845 * comments are allowed. You can close them manually or keep them open by
3846 * setting the value for the 'comment_status' key.
3848 * The $object parameter can have the following:
3849 * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
3850 * 'post_type' - Default is 'post', will be set to attachment. Can not override.
3851 * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
3852 * 'ping_status' - Default is the value in default ping status option. Whether the attachment
3854 * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
3856 * 'menu_order' - Default is 0. The order it is displayed.
3857 * 'to_ping' - Whether to ping.
3858 * 'pinged' - Default is empty string.
3859 * 'post_password' - Default is empty string. The password to access the attachment.
3860 * 'guid' - Global Unique ID for referencing the attachment.
3861 * 'post_content_filtered' - Attachment post content filtered.
3862 * 'post_excerpt' - Attachment excerpt.
3867 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
3868 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
3870 * @param string|array $object Arguments to override defaults.
3871 * @param string $file Optional filename.
3872 * @param int $parent Parent post ID.
3873 * @return int Attachment ID.
3875 function wp_insert_attachment($object, $file = false, $parent = 0) {
3876 global $wpdb, $user_ID;
3878 $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_ID,
3879 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '',
3880 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
3881 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
3883 $object = wp_parse_args($object, $defaults);
3884 if ( !empty($parent) )
3885 $object['post_parent'] = $parent;
3887 unset( $object[ 'filter' ] );
3889 $object = sanitize_post($object, 'db');
3891 // export array as variables
3892 extract($object, EXTR_SKIP);
3894 if ( empty($post_author) )
3895 $post_author = $user_ID;
3897 $post_type = 'attachment';
3899 if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
3900 $post_status = 'inherit';
3902 if ( !empty($post_category) )
3903 $post_category = array_filter($post_category); // Filter out empty terms
3905 // Make sure we set a valid category.
3906 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
3907 $post_category = array();
3910 // Are we updating or creating?
3911 if ( !empty($ID) ) {
3913 $post_ID = (int) $ID;
3919 // Create a valid post name.
3920 if ( empty($post_name) )
3921 $post_name = sanitize_title($post_title);
3923 $post_name = sanitize_title($post_name);
3925 // expected_slashed ($post_name)
3926 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
3928 if ( empty($post_date) )
3929 $post_date = current_time('mysql');
3930 if ( empty($post_date_gmt) )
3931 $post_date_gmt = current_time('mysql', 1);
3933 if ( empty($post_modified) )
3934 $post_modified = $post_date;
3935 if ( empty($post_modified_gmt) )
3936 $post_modified_gmt = $post_date_gmt;
3938 if ( empty($comment_status) ) {
3940 $comment_status = 'closed';
3942 $comment_status = get_option('default_comment_status');
3944 if ( empty($ping_status) )
3945 $ping_status = get_option('default_ping_status');
3947 if ( isset($to_ping) )
3948 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
3952 if ( isset($post_parent) )
3953 $post_parent = (int) $post_parent;
3957 if ( isset($menu_order) )
3958 $menu_order = (int) $menu_order;
3962 if ( !isset($post_password) )
3963 $post_password = '';
3965 if ( ! isset($pinged) )
3968 // expected_slashed (everything!)
3969 $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' ) );
3970 $data = wp_unslash( $data );
3973 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
3975 // If there is a suggested ID, use it if not already present
3976 if ( !empty($import_id) ) {
3977 $import_id = (int) $import_id;
3978 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3979 $data['ID'] = $import_id;
3983 $wpdb->insert( $wpdb->posts, $data );
3984 $post_ID = (int) $wpdb->insert_id;
3987 if ( empty($post_name) ) {
3988 $post_name = sanitize_title($post_title, $post_ID);
3989 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
3992 if ( is_object_in_taxonomy($post_type, 'category') )
3993 wp_set_post_categories( $post_ID, $post_category );
3995 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
3996 wp_set_post_tags( $post_ID, $tags_input );
3998 // support for all custom taxonomies
3999 if ( !empty($tax_input) ) {
4000 foreach ( $tax_input as $taxonomy => $tags ) {
4001 $taxonomy_obj = get_taxonomy($taxonomy);
4002 if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
4003 $tags = array_filter($tags);
4004 if ( current_user_can($taxonomy_obj->cap->assign_terms) )
4005 wp_set_post_terms( $post_ID, $tags, $taxonomy );
4010 update_attached_file( $post_ID, $file );
4012 clean_post_cache( $post_ID );
4014 if ( ! empty( $context ) )
4015 add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
4018 do_action('edit_attachment', $post_ID);
4020 do_action('add_attachment', $post_ID);
4027 * Trashes or deletes an attachment.
4029 * When an attachment is permanently deleted, the file will also be removed.
4030 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4031 * with the attachment (except the main post).
4033 * The attachment is moved to the trash instead of permanently deleted unless trash
4034 * for media is disabled, item is already in the trash, or $force_delete is true.
4038 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
4040 * @param int $post_id Attachment ID.
4041 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
4042 * @return mixed False on failure. Post data on success.
4044 function wp_delete_attachment( $post_id, $force_delete = false ) {
4047 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4050 if ( 'attachment' != $post->post_type )
4053 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4054 return wp_trash_post( $post_id );
4056 delete_post_meta($post_id, '_wp_trash_meta_status');
4057 delete_post_meta($post_id, '_wp_trash_meta_time');
4059 $meta = wp_get_attachment_metadata( $post_id );
4060 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4061 $file = get_attached_file( $post_id );
4063 $intermediate_sizes = array();
4064 foreach ( get_intermediate_image_sizes() as $size ) {
4065 if ( $intermediate = image_get_intermediate_size( $post_id, $size ) )
4066 $intermediate_sizes[] = $intermediate;
4069 if ( is_multisite() )
4070 delete_transient( 'dirsize_cache' );
4072 do_action('delete_attachment', $post_id);
4074 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4075 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4077 delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts.
4079 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4080 foreach ( $comment_ids as $comment_id )
4081 wp_delete_comment( $comment_id, true );
4083 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4084 foreach ( $post_meta_ids as $mid )
4085 delete_metadata_by_mid( 'post', $mid );
4087 do_action( 'delete_post', $post_id );
4088 $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4089 do_action( 'deleted_post', $post_id );
4091 $uploadpath = wp_upload_dir();
4093 if ( ! empty($meta['thumb']) ) {
4094 // Don't delete the thumb if another attachment uses it
4095 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)) ) {
4096 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4097 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
4098 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4102 // remove intermediate and backup images if there are any
4103 foreach ( $intermediate_sizes as $intermediate ) {
4104 $intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] );
4105 @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
4108 if ( is_array($backup_sizes) ) {
4109 foreach ( $backup_sizes as $size ) {
4110 $del_file = path_join( dirname($meta['file']), $size['file'] );
4111 $del_file = apply_filters('wp_delete_file', $del_file);
4112 @ unlink( path_join($uploadpath['basedir'], $del_file) );
4116 $file = apply_filters('wp_delete_file', $file);
4118 if ( ! empty($file) )
4121 clean_post_cache( $post );
4127 * Retrieve attachment meta field for attachment ID.
4131 * @param int $post_id Attachment ID
4132 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
4133 * @return string|bool Attachment meta field. False on failure.
4135 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4136 $post_id = (int) $post_id;
4137 if ( !$post = get_post( $post_id ) )
4140 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4145 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4149 * Update metadata for an attachment.
4153 * @param int $post_id Attachment ID.
4154 * @param array $data Attachment data.
4157 function wp_update_attachment_metadata( $post_id, $data ) {
4158 $post_id = (int) $post_id;
4159 if ( !$post = get_post( $post_id ) )
4162 if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4163 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4165 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4169 * Retrieve the URL for an attachment.
4173 * @param int $post_id Attachment ID.
4176 function wp_get_attachment_url( $post_id = 0 ) {
4177 $post_id = (int) $post_id;
4178 if ( !$post = get_post( $post_id ) )
4181 if ( 'attachment' != $post->post_type )
4185 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
4186 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
4187 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
4188 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
4189 elseif ( false !== strpos($file, 'wp-content/uploads') )
4190 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
4192 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
4196 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.
4197 $url = get_the_guid( $post->ID );
4199 $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4201 if ( empty( $url ) )
4208 * Retrieve thumbnail for an attachment.
4212 * @param int $post_id Attachment ID.
4213 * @return mixed False on failure. Thumbnail file path on success.
4215 function wp_get_attachment_thumb_file( $post_id = 0 ) {
4216 $post_id = (int) $post_id;
4217 if ( !$post = get_post( $post_id ) )
4219 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
4222 $file = get_attached_file( $post->ID );
4224 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
4225 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
4230 * Retrieve URL for an attachment thumbnail.
4234 * @param int $post_id Attachment ID
4235 * @return string|bool False on failure. Thumbnail URL on success.
4237 function wp_get_attachment_thumb_url( $post_id = 0 ) {
4238 $post_id = (int) $post_id;
4239 if ( !$post = get_post( $post_id ) )
4241 if ( !$url = wp_get_attachment_url( $post->ID ) )
4244 $sized = image_downsize( $post_id, 'thumbnail' );
4248 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
4251 $url = str_replace(basename($url), basename($thumb), $url);
4253 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
4257 * Check if the attachment is an image.
4261 * @param int $post_id Attachment ID
4264 function wp_attachment_is_image( $post_id = 0 ) {
4265 $post_id = (int) $post_id;
4266 if ( !$post = get_post( $post_id ) )
4269 if ( !$file = get_attached_file( $post->ID ) )
4272 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
4274 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
4276 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
4282 * Retrieve the icon for a MIME type.
4286 * @param string|int $mime MIME type or attachment ID.
4287 * @return string|bool
4289 function wp_mime_type_icon( $mime = 0 ) {
4290 if ( !is_numeric($mime) )
4291 $icon = wp_cache_get("mime_type_icon_$mime");
4294 if ( empty($icon) ) {
4295 $post_mimes = array();
4296 if ( is_numeric($mime) ) {
4297 $mime = (int) $mime;
4298 if ( $post = get_post( $mime ) ) {
4299 $post_id = (int) $post->ID;
4300 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
4301 if ( !empty($ext) ) {
4302 $post_mimes[] = $ext;
4303 if ( $ext_type = wp_ext2type( $ext ) )
4304 $post_mimes[] = $ext_type;
4306 $mime = $post->post_mime_type;
4311 $post_mimes[] = $mime;
4314 $icon_files = wp_cache_get('icon_files');
4316 if ( !is_array($icon_files) ) {
4317 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
4318 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
4319 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
4320 $icon_files = array();
4322 $keys = array_keys( $dirs );
4323 $dir = array_shift( $keys );
4324 $uri = array_shift($dirs);
4325 if ( $dh = opendir($dir) ) {
4326 while ( false !== $file = readdir($dh) ) {
4327 $file = basename($file);
4328 if ( substr($file, 0, 1) == '.' )
4330 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
4331 if ( is_dir("$dir/$file") )
4332 $dirs["$dir/$file"] = "$uri/$file";
4335 $icon_files["$dir/$file"] = "$uri/$file";
4340 wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
4343 // Icon basename - extension = MIME wildcard
4344 foreach ( $icon_files as $file => $uri )
4345 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
4347 if ( ! empty($mime) ) {
4348 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
4349 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
4350 $post_mimes[] = str_replace('/', '_', $mime);
4353 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
4354 $matches['default'] = array('default');
4356 foreach ( $matches as $match => $wilds ) {
4357 if ( isset($types[$wilds[0]])) {
4358 $icon = $types[$wilds[0]];
4359 if ( !is_numeric($mime) )
4360 wp_cache_add("mime_type_icon_$mime", $icon);
4366 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
4370 * Checked for changed slugs for published post objects and save the old slug.
4372 * The function is used when a post object of any type is updated,
4373 * by comparing the current and previous post objects.
4375 * If the slug was changed and not already part of the old slugs then it will be
4376 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
4379 * The most logically usage of this function is redirecting changed post objects, so
4380 * that those that linked to an changed post will be redirected to the new post.
4384 * @param int $post_id Post ID.
4385 * @param object $post The Post Object
4386 * @param object $post_before The Previous Post Object
4387 * @return int Same as $post_id
4389 function wp_check_for_changed_slugs($post_id, $post, $post_before) {
4390 // dont bother if it hasnt changed
4391 if ( $post->post_name == $post_before->post_name )
4394 // we're only concerned with published, non-hierarchical objects
4395 if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
4398 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
4400 // if we haven't added this old slug before, add it now
4401 if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
4402 add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
4404 // if the new slug was used previously, delete it from the list
4405 if ( in_array($post->post_name, $old_slugs) )
4406 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
4410 * Retrieve the private post SQL based on capability.
4412 * This function provides a standardized way to appropriately select on the
4413 * post_status of a post type. The function will return a piece of SQL code
4414 * that can be added to a WHERE clause; this SQL is constructed to allow all
4415 * published posts, and all private posts to which the user has access.
4421 * @param string $post_type currently only supports 'post' or 'page'.
4422 * @return string SQL code that can be added to a where clause.
4424 function get_private_posts_cap_sql( $post_type ) {
4425 return get_posts_by_author_sql( $post_type, false );
4429 * Retrieve the post SQL based on capability, author, and type.
4431 * @see get_private_posts_cap_sql() for full description.
4434 * @param string $post_type Post type.
4435 * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
4436 * @param int $post_author Optional. Query posts having a single author ID.
4437 * @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false.
4438 * @return string SQL WHERE code that can be added to a query.
4440 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
4441 global $user_ID, $wpdb;
4444 $post_type_obj = get_post_type_object( $post_type );
4445 if ( ! $post_type_obj )
4446 return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
4448 // This hook is deprecated. Why you'd want to use it, I dunno.
4449 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) )
4450 $cap = $post_type_obj->cap->read_private_posts;
4453 if ( null === $post_author ) {
4454 $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
4456 $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
4462 $sql .= "(post_status = 'publish'";
4464 // Only need to check the cap if $public_only is false
4465 if ( false === $public_only ) {
4466 if ( current_user_can( $cap ) ) {
4467 // Does the user have the capability to view private posts? Guess so.
4468 $sql .= " OR post_status = 'private'";
4469 } elseif ( is_user_logged_in() ) {
4470 // Users can view their own private posts.
4471 $id = (int) $user_ID;
4472 if ( null === $post_author || ! $full ) {
4473 $sql .= " OR post_status = 'private' AND post_author = $id";
4474 } elseif ( $id == (int) $post_author ) {
4475 $sql .= " OR post_status = 'private'";
4486 * Retrieve the date that the last post was published.
4488 * The server timezone is the default and is the difference between GMT and
4489 * server time. The 'blog' value is the date when the last post was posted. The
4490 * 'gmt' is when the last post was posted in GMT formatted date.
4494 * @uses apply_filters() Calls 'get_lastpostdate' filter
4496 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4497 * @return string The date of the last post.
4499 function get_lastpostdate($timezone = 'server') {
4500 return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
4504 * Retrieve last post modified date depending on timezone.
4506 * The server timezone is the default and is the difference between GMT and
4507 * server time. The 'blog' value is just when the last post was modified. The
4508 * 'gmt' is when the last post was modified in GMT time.
4511 * @uses apply_filters() Calls 'get_lastpostmodified' filter
4513 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4514 * @return string The date the post was last modified.
4516 function get_lastpostmodified($timezone = 'server') {
4517 $lastpostmodified = _get_last_post_time( $timezone, 'modified' );
4519 $lastpostdate = get_lastpostdate($timezone);
4520 if ( $lastpostdate > $lastpostmodified )
4521 $lastpostmodified = $lastpostdate;
4523 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
4527 * Retrieve latest post date data based on timezone.
4532 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4533 * @param string $field Field to check. Can be 'date' or 'modified'.
4534 * @return string The date.
4536 function _get_last_post_time( $timezone, $field ) {
4539 if ( !in_array( $field, array( 'date', 'modified' ) ) )
4542 $timezone = strtolower( $timezone );
4544 $key = "lastpost{$field}:$timezone";
4546 $date = wp_cache_get( $key, 'timeinfo' );
4549 $add_seconds_server = date('Z');
4551 $post_types = get_post_types( array( 'public' => true ) );
4552 array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
4553 $post_types = "'" . implode( "', '", $post_types ) . "'";
4555 switch ( $timezone ) {
4557 $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");
4560 $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");
4563 $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");
4568 wp_cache_set( $key, $date, 'timeinfo' );
4575 * Updates posts in cache.
4577 * @package WordPress
4581 * @param array $posts Array of post objects
4583 function update_post_cache( &$posts ) {
4587 foreach ( $posts as $post )
4588 wp_cache_add( $post->ID, $post, 'posts' );
4592 * Will clean the post in the cache.
4594 * Cleaning means delete from the cache of the post. Will call to clean the term
4595 * object cache associated with the post ID.
4597 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
4598 * wp_suspend_cache_invalidation().
4600 * @package WordPress
4604 * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
4606 * @param int|object $post Post ID or object to remove from the cache
4608 function clean_post_cache( $post ) {
4609 global $_wp_suspend_cache_invalidation, $wpdb;
4611 if ( ! empty( $_wp_suspend_cache_invalidation ) )
4614 $post = get_post( $post );
4615 if ( empty( $post ) )
4618 wp_cache_delete( $post->ID, 'posts' );
4619 wp_cache_delete( $post->ID, 'post_meta' );
4621 clean_object_term_cache( $post->ID, $post->post_type );
4623 wp_cache_delete( 'wp_get_archives', 'general' );
4625 do_action( 'clean_post_cache', $post->ID, $post );
4627 if ( is_post_type_hierarchical( $post->post_type ) )
4628 wp_cache_delete( 'get_pages', 'posts' );
4630 if ( 'page' == $post->post_type ) {
4631 wp_cache_delete( 'all_page_ids', 'posts' );
4632 do_action( 'clean_page_cache', $post->ID );
4635 wp_cache_set( 'last_changed', microtime(), 'posts' );
4639 * Call major cache updating functions for list of Post objects.
4641 * @package WordPress
4646 * @uses update_post_cache()
4647 * @uses update_object_term_cache()
4648 * @uses update_postmeta_cache()
4650 * @param array $posts Array of Post objects
4651 * @param string $post_type The post type of the posts in $posts. Default is 'post'.
4652 * @param bool $update_term_cache Whether to update the term cache. Default is true.
4653 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
4655 function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
4656 // No point in doing all this work if we didn't match any posts.
4660 update_post_cache($posts);
4662 $post_ids = array();
4663 foreach ( $posts as $post )
4664 $post_ids[] = $post->ID;
4669 if ( $update_term_cache ) {
4670 if ( is_array($post_type) ) {
4671 $ptypes = $post_type;
4672 } elseif ( 'any' == $post_type ) {
4673 // Just use the post_types in the supplied posts.
4674 foreach ( $posts as $post )
4675 $ptypes[] = $post->post_type;
4676 $ptypes = array_unique($ptypes);
4678 $ptypes = array($post_type);
4681 if ( ! empty($ptypes) )
4682 update_object_term_cache($post_ids, $ptypes);
4685 if ( $update_meta_cache )
4686 update_postmeta_cache($post_ids);
4690 * Updates metadata cache for list of post IDs.
4692 * Performs SQL query to retrieve the metadata for the post IDs and updates the
4693 * metadata cache for the posts. Therefore, the functions, which call this
4694 * function, do not need to perform SQL queries on their own.
4696 * @package WordPress
4702 * @param array $post_ids List of post IDs.
4703 * @return bool|array Returns false if there is nothing to update or an array of metadata.
4705 function update_postmeta_cache($post_ids) {
4706 return update_meta_cache('post', $post_ids);
4710 * Will clean the attachment in the cache.
4712 * Cleaning means delete from the cache. Optionally will clean the term
4713 * object cache associated with the attachment ID.
4715 * This function will not run if $_wp_suspend_cache_invalidation is not empty. See
4716 * wp_suspend_cache_invalidation().
4718 * @package WordPress
4722 * @uses do_action() Calls 'clean_attachment_cache' on $id.
4724 * @param int $id The attachment ID in the cache to clean
4725 * @param bool $clean_terms optional. Whether to clean terms cache
4727 function clean_attachment_cache($id, $clean_terms = false) {
4728 global $_wp_suspend_cache_invalidation;
4730 if ( !empty($_wp_suspend_cache_invalidation) )
4735 wp_cache_delete($id, 'posts');
4736 wp_cache_delete($id, 'post_meta');
4739 clean_object_term_cache($id, 'attachment');
4741 do_action('clean_attachment_cache', $id);
4749 * Hook for managing future post transitions to published.
4754 * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
4755 * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
4757 * @param string $new_status New post status
4758 * @param string $old_status Previous post status
4759 * @param object $post Object type containing the post information
4761 function _transition_post_status($new_status, $old_status, $post) {
4764 if ( $old_status != 'publish' && $new_status == 'publish' ) {
4765 // Reset GUID if transitioning to publish and it is empty
4766 if ( '' == get_the_guid($post->ID) )
4767 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
4768 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
4771 // If published posts changed clear the lastpostmodified cache
4772 if ( 'publish' == $new_status || 'publish' == $old_status) {
4773 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
4774 wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
4775 wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
4779 // Always clears the hook in case the post status bounced from future to draft.
4780 wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
4784 * Hook used to schedule publication for a post marked for the future.
4786 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
4791 * @param int $deprecated Not used. Can be set to null. Never implemented.
4792 * Not marked as deprecated with _deprecated_argument() as it conflicts with
4793 * wp_transition_post_status() and the default filter for _future_post_hook().
4794 * @param object $post Object type containing the post information
4796 function _future_post_hook( $deprecated, $post ) {
4797 wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
4798 wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
4802 * Hook to schedule pings and enclosures when a post is published.
4806 * @uses XMLRPC_REQUEST and WP_IMPORTING constants.
4807 * @uses do_action() Calls 'xmlrpc_publish_post' on post ID if XMLRPC_REQUEST is defined.
4809 * @param int $post_id The ID in the database table of the post being published
4811 function _publish_post_hook($post_id) {
4812 if ( defined('XMLRPC_REQUEST') )
4813 do_action('xmlrpc_publish_post', $post_id);
4815 if ( defined('WP_IMPORTING') )
4818 if ( get_option('default_pingback_flag') )
4819 add_post_meta( $post_id, '_pingme', '1' );
4820 add_post_meta( $post_id, '_encloseme', '1' );
4822 wp_schedule_single_event(time(), 'do_pings');
4826 * Returns the post's parent's post_ID
4830 * @param int $post_id
4832 * @return int|bool false on error
4834 function wp_get_post_parent_id( $post_ID ) {
4835 $post = get_post( $post_ID );
4836 if ( !$post || is_wp_error( $post ) )
4838 return (int) $post->post_parent;
4842 * Checks the given subset of the post hierarchy for hierarchy loops.
4843 * Prevents loops from forming and breaks those that it finds.
4845 * Attached to the wp_insert_post_parent filter.
4848 * @uses wp_find_hierarchy_loop()
4850 * @param int $post_parent ID of the parent for the post we're checking.
4851 * @param int $post_ID ID of the post we're checking.
4853 * @return int The new post_parent for the post.
4855 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
4856 // Nothing fancy here - bail
4857 if ( !$post_parent )
4860 // New post can't cause a loop
4861 if ( empty( $post_ID ) )
4862 return $post_parent;
4864 // Can't be its own parent
4865 if ( $post_parent == $post_ID )
4868 // Now look for larger loops
4870 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
4871 return $post_parent; // No loop
4873 // Setting $post_parent to the given value causes a loop
4874 if ( isset( $loop[$post_ID] ) )
4877 // There's a loop, but it doesn't contain $post_ID. Break the loop.
4878 foreach ( array_keys( $loop ) as $loop_member )
4879 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
4881 return $post_parent;
4885 * Sets a post thumbnail.
4889 * @param int|object $post Post ID or object where thumbnail should be attached.
4890 * @param int $thumbnail_id Thumbnail to attach.
4891 * @return bool True on success, false on failure.
4893 function set_post_thumbnail( $post, $thumbnail_id ) {
4894 $post = get_post( $post );
4895 $thumbnail_id = absint( $thumbnail_id );
4896 if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
4897 if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
4898 return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
4900 return delete_post_meta( $post->ID, '_thumbnail_id' );
4906 * Removes a post thumbnail.
4910 * @param int|object $post Post ID or object where thumbnail should be removed from.
4911 * @return bool True on success, false on failure.
4913 function delete_post_thumbnail( $post ) {
4914 $post = get_post( $post );
4916 return delete_post_meta( $post->ID, '_thumbnail_id' );
4921 * Deletes auto-drafts for new posts that are > 7 days old
4925 function wp_delete_auto_drafts() {
4928 // Cleanup old auto-drafts more than 7 days old
4929 $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
4930 foreach ( (array) $old_posts as $delete )
4931 wp_delete_post( $delete, true ); // Force delete
4935 * 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.
4938 * @param string $new_status
4939 * @param string $old_status
4940 * @param object $post
4943 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
4944 // Update counts for the post's terms.
4945 foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
4946 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
4947 wp_update_term_count( $tt_ids, $taxonomy );
4952 * Adds any posts from the given ids to the cache that do not already exist in cache
4958 * @param array $post_ids ID list
4959 * @param bool $update_term_cache Whether to update the term cache. Default is true.
4960 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
4962 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
4965 $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
4966 if ( !empty( $non_cached_ids ) ) {
4967 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
4969 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );