3 * Post functions and post utility function.
11 // Post Type Registration
15 * Creates the initial post types when 'init' action is fired.
17 function create_initial_post_types() {
18 register_post_type( 'post', array('exclude_from_search' => false) );
19 register_post_type( 'page', array('exclude_from_search' => false) );
20 register_post_type( 'attachment', array('exclude_from_search' => false) );
21 register_post_type( 'revision', array('exclude_from_search' => true) );
23 add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
26 * Retrieve attached file path based on attachment ID.
28 * You can optionally send it through the 'get_attached_file' filter, but by
29 * default it will just return the file path unfiltered.
31 * The function works by getting the single post meta name, named
32 * '_wp_attached_file' and returning it. This is a convenience function to
33 * prevent looking up the meta name and provide a mechanism for sending the
34 * attached filename through a filter.
37 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
39 * @param int $attachment_id Attachment ID.
40 * @param bool $unfiltered Whether to apply filters or not.
41 * @return string The file path to the attached file.
43 function get_attached_file( $attachment_id, $unfiltered = false ) {
44 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
45 // If the file is relative, prepend upload dir
46 if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
47 $file = $uploads['basedir'] . "/$file";
50 return apply_filters( 'get_attached_file', $file, $attachment_id );
54 * Update attachment file path based on attachment ID.
56 * Used to update the file path of the attachment, which uses post meta name
57 * '_wp_attached_file' to store the path of the attachment.
60 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
62 * @param int $attachment_id Attachment ID
63 * @param string $file File path for the attachment
64 * @return bool False on failure, true on success.
66 function update_attached_file( $attachment_id, $file ) {
67 if ( !get_post( $attachment_id ) )
70 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
71 $file = _wp_relative_upload_path($file);
73 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
77 * Return relative path to an uploaded file.
79 * The path is relative to the current upload dir.
82 * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
84 * @param string $path Full path to the file
85 * @return string relative path on success, unchanged path on failure.
87 function _wp_relative_upload_path( $path ) {
90 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
91 if ( 0 === strpos($new_path, $uploads['basedir']) ) {
92 $new_path = str_replace($uploads['basedir'], '', $new_path);
93 $new_path = ltrim($new_path, '/');
97 return apply_filters( '_wp_relative_upload_path', $new_path, $path );
101 * Retrieve all children of the post parent ID.
103 * Normally, without any enhancements, the children would apply to pages. In the
104 * context of the inner workings of WordPress, pages, posts, and attachments
105 * share the same table, so therefore the functionality could apply to any one
106 * of them. It is then noted that while this function does not work on posts, it
107 * does not mean that it won't work on posts. It is recommended that you know
108 * what context you wish to retrieve the children of.
110 * Attachments may also be made the child of a post, so if that is an accurate
111 * statement (which needs to be verified), it would then be possible to get
112 * all of the attachments for a post. Attachments have since changed since
113 * version 2.5, so this is most likely unaccurate, but serves generally as an
114 * example of what is possible.
116 * The arguments listed as defaults are for this function and also of the
117 * {@link get_posts()} function. The arguments are combined with the
118 * get_children defaults and are then passed to the {@link get_posts()}
119 * function, which accepts additional arguments. You can replace the defaults in
120 * this function, listed below and the additional arguments listed in the
121 * {@link get_posts()} function.
123 * The 'post_parent' is the most important argument and important attention
124 * needs to be paid to the $args parameter. If you pass either an object or an
125 * integer (number), then just the 'post_parent' is grabbed and everything else
126 * is lost. If you don't specify any arguments, then it is assumed that you are
127 * in The Loop and the post parent will be grabbed for from the current post.
129 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
130 * is the amount of posts to retrieve that has a default of '-1', which is
131 * used to get all of the posts. Giving a number higher than 0 will only
132 * retrieve that amount of posts.
134 * The 'post_type' and 'post_status' arguments can be used to choose what
135 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
136 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
137 * argument will accept any post status within the write administration panels.
139 * @see get_posts() Has additional arguments that can be replaced.
140 * @internal Claims made in the long description might be inaccurate.
144 * @param mixed $args Optional. User defined arguments for replacing the defaults.
145 * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
146 * @return array|bool False on failure and the type will be determined by $output parameter.
148 function &get_children($args = '', $output = OBJECT) {
150 if ( empty( $args ) ) {
151 if ( isset( $GLOBALS['post'] ) ) {
152 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
156 } elseif ( is_object( $args ) ) {
157 $args = array('post_parent' => (int) $args->post_parent );
158 } elseif ( is_numeric( $args ) ) {
159 $args = array('post_parent' => (int) $args);
163 'numberposts' => -1, 'post_type' => 'any',
164 'post_status' => 'any', 'post_parent' => 0,
167 $r = wp_parse_args( $args, $defaults );
169 $children = get_posts( $r );
174 update_post_cache($children);
176 foreach ( $children as $key => $child )
177 $kids[$child->ID] =& $children[$key];
179 if ( $output == OBJECT ) {
181 } elseif ( $output == ARRAY_A ) {
182 foreach ( (array) $kids as $kid )
183 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
185 } elseif ( $output == ARRAY_N ) {
186 foreach ( (array) $kids as $kid )
187 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
195 * Get extended entry info (<!--more-->).
197 * There should not be any space after the second dash and before the word
198 * 'more'. There can be text or space(s) after the word 'more', but won't be
201 * The returned array has 'main' and 'extended' keys. Main has the text before
202 * the <code><!--more--></code>. The 'extended' key has the content after the
203 * <code><!--more--></code> comment.
207 * @param string $post Post content.
208 * @return array Post before ('main') and after ('extended').
210 function get_extended($post) {
211 //Match the new style more links
212 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
213 list($main, $extended) = explode($matches[0], $post, 2);
219 // Strip leading and trailing whitespace
220 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
221 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
223 return array('main' => $main, 'extended' => $extended);
227 * Retrieves post data given a post ID or post object.
229 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
230 * $post, must be given as a variable, since it is passed by reference.
234 * @link http://codex.wordpress.org/Function_Reference/get_post
236 * @param int|object $post Post ID or post object.
237 * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
238 * @param string $filter Optional, default is raw.
239 * @return mixed Post data
241 function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
245 if ( empty($post) ) {
246 if ( isset($GLOBALS['post']) )
247 $_post = & $GLOBALS['post'];
250 } elseif ( is_object($post) && empty($post->filter) ) {
251 _get_post_ancestors($post);
252 $_post = sanitize_post($post, 'raw');
253 wp_cache_add($post->ID, $_post, 'posts');
255 if ( is_object($post) )
258 if ( ! $_post = wp_cache_get($post, 'posts') ) {
259 $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post));
262 _get_post_ancestors($_post);
263 $_post = sanitize_post($_post, 'raw');
264 wp_cache_add($_post->ID, $_post, 'posts');
268 if ($filter != 'raw')
269 $_post = sanitize_post($_post, $filter);
271 if ( $output == OBJECT ) {
273 } elseif ( $output == ARRAY_A ) {
274 $__post = get_object_vars($_post);
276 } elseif ( $output == ARRAY_N ) {
277 $__post = array_values(get_object_vars($_post));
285 * Retrieve ancestors of a post.
289 * @param int|object $post Post ID or post object
290 * @return array Ancestor IDs or empty array if none are found.
292 function get_post_ancestors($post) {
293 $post = get_post($post);
295 if ( !empty($post->ancestors) )
296 return $post->ancestors;
302 * Retrieve data from a post field based on Post ID.
304 * Examples of the post field will be, 'post_type', 'post_status', 'content',
305 * etc and based off of the post object property or key names.
307 * The context values are based off of the taxonomy filter functions and
308 * supported values are found within those functions.
311 * @uses sanitize_post_field() See for possible $context values.
313 * @param string $field Post field name
314 * @param id $post Post ID
315 * @param string $context Optional. How to filter the field. Default is display.
316 * @return WP_Error|string Value in post field or WP_Error on failure
318 function get_post_field( $field, $post, $context = 'display' ) {
320 $post = get_post( $post );
322 if ( is_wp_error($post) )
325 if ( !is_object($post) )
328 if ( !isset($post->$field) )
331 return sanitize_post_field($field, $post->$field, $post->ID, $context);
335 * Retrieve the mime type of an attachment based on the ID.
337 * This function can be used with any post type, but it makes more sense with
342 * @param int $ID Optional. Post ID.
343 * @return bool|string False on failure or returns the mime type
345 function get_post_mime_type($ID = '') {
346 $post = & get_post($ID);
348 if ( is_object($post) )
349 return $post->post_mime_type;
355 * Retrieve the post status based on the Post ID.
357 * If the post ID is of an attachment, then the parent post status will be given
362 * @param int $ID Post ID
363 * @return string|bool Post status or false on failure.
365 function get_post_status($ID = '') {
366 $post = get_post($ID);
368 if ( is_object($post) ) {
369 if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
370 return get_post_status($post->post_parent);
372 return $post->post_status;
379 * Retrieve all of the WordPress supported post statuses.
381 * Posts have a limited set of valid status values, this provides the
382 * post_status values and descriptions.
386 * @return array List of post statuses.
388 function get_post_statuses( ) {
390 'draft' => __('Draft'),
391 'pending' => __('Pending Review'),
392 'private' => __('Private'),
393 'publish' => __('Published')
400 * Retrieve all of the WordPress support page statuses.
402 * Pages have a limited set of valid status values, this provides the
403 * post_status values and descriptions.
407 * @return array List of page statuses.
409 function get_page_statuses( ) {
411 'draft' => __('Draft'),
412 'private' => __('Private'),
413 'publish' => __('Published')
420 * Retrieve the post type of the current post or of a given post.
425 * @uses $posts The Loop post global
427 * @param mixed $post Optional. Post object or post ID.
428 * @return bool|string post type or false on failure.
430 function get_post_type($post = false) {
433 if ( false === $post )
435 elseif ( (int) $post )
436 $post = get_post($post, OBJECT);
438 if ( is_object($post) )
439 return $post->post_type;
445 * Get a list of all registered post type objects.
450 * @uses $wp_post_types
451 * @see register_post_type
452 * @see get_post_types
454 * @param array|string $args An array of key => value arguments to match against the post types.
455 * Only post types having attributes that match all arguments are returned.
456 * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
457 * @return array A list of post type names or objects
459 function get_post_types( $args = array(), $output = 'names' ) {
460 global $wp_post_types;
463 if ( 'names' == $output )
466 $post_types = array();
467 foreach ( (array) $wp_post_types as $post_type ) {
468 if ( empty($args) ) {
470 $post_types[] = $post_type->name;
472 $post_types[] = $post_type;
473 } elseif ( array_intersect_assoc((array) $post_type, $args) ) {
475 $post_types[] = $post_type->name;
477 $post_types[] = $post_type;
485 * Register a post type. Do not use before init.
487 * A simple function for creating or modifying a post type based on the
488 * parameters given. The function will accept an array (second optional
489 * parameter), along with a string for the post type name.
492 * Optional $args contents:
494 * exclude_from_search - Whether to exclude posts with this post type from search results. Defaults to true.
499 * @uses $wp_post_types Inserts new post type object into the list
501 * @param string $post_type Name of the post type.
502 * @param array|string $args See above description.
504 function register_post_type($post_type, $args = array()) {
505 global $wp_post_types;
507 if (!is_array($wp_post_types))
508 $wp_post_types = array();
510 $defaults = array('exclude_from_search' => true);
511 $args = wp_parse_args($args, $defaults);
513 $post_type = sanitize_user($post_type, true);
514 $args['name'] = $post_type;
515 $wp_post_types[$post_type] = (object) $args;
519 * Updates the post type for the post ID.
521 * The page or post cache will be cleaned for the post ID.
527 * @param int $post_id Post ID to change post type. Not actually optional.
528 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
530 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
532 function set_post_type( $post_id = 0, $post_type = 'post' ) {
535 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
536 $return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
538 if ( 'page' == $post_type )
539 clean_page_cache($post_id);
541 clean_post_cache($post_id);
547 * Retrieve list of latest posts or posts matching criteria.
549 * The defaults are as follows:
550 * 'numberposts' - Default is 5. Total number of posts to retrieve.
551 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
552 * 'category' - What category to pull the posts from.
553 * 'orderby' - Default is 'post_date'. How to order the posts.
554 * 'order' - Default is 'DESC'. The order to retrieve the posts.
555 * 'include' - See {@link WP_Query::query()} for more.
556 * 'exclude' - See {@link WP_Query::query()} for more.
557 * 'meta_key' - See {@link WP_Query::query()} for more.
558 * 'meta_value' - See {@link WP_Query::query()} for more.
559 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
560 * 'post_parent' - The parent of the post or post type.
561 * 'post_status' - Default is 'published'. Post status to retrieve.
565 * @uses WP_Query::query() See for more default arguments and information.
566 * @link http://codex.wordpress.org/Template_Tags/get_posts
568 * @param array $args Optional. Overrides defaults.
569 * @return array List of posts.
571 function get_posts($args = null) {
573 'numberposts' => 5, 'offset' => 0,
574 'category' => 0, 'orderby' => 'post_date',
575 'order' => 'DESC', 'include' => '',
576 'exclude' => '', 'meta_key' => '',
577 'meta_value' =>'', 'post_type' => 'post',
578 'suppress_filters' => true
581 $r = wp_parse_args( $args, $defaults );
582 if ( empty( $r['post_status'] ) )
583 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
584 if ( ! empty($r['numberposts']) )
585 $r['posts_per_page'] = $r['numberposts'];
586 if ( ! empty($r['category']) )
587 $r['cat'] = $r['category'];
588 if ( ! empty($r['include']) ) {
589 $incposts = preg_split('/[\s,]+/',$r['include']);
590 $r['posts_per_page'] = count($incposts); // only the number of posts included
591 $r['post__in'] = $incposts;
592 } elseif ( ! empty($r['exclude']) )
593 $r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
595 $r['caller_get_posts'] = true;
597 $get_posts = new WP_Query;
598 return $get_posts->query($r);
603 // Post meta functions
607 * Add meta data field to a post.
609 * Post meta data is called "Custom Fields" on the Administration Panels.
613 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
615 * @param int $post_id Post ID.
616 * @param string $key Metadata name.
617 * @param mixed $value Metadata value.
618 * @param bool $unique Optional, default is false. Whether the same key should not be added.
619 * @return bool False for failure. True for success.
621 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
622 // make sure meta is added to the post, not a revision
623 if ( $the_post = wp_is_post_revision($post_id) )
624 $post_id = $the_post;
626 return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
630 * Remove metadata matching criteria from a post.
632 * You can match based on the key, or key and value. Removing based on key and
633 * value, will keep from removing duplicate metadata with the same key. It also
634 * allows removing all metadata matching key, if needed.
638 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
640 * @param int $post_id post ID
641 * @param string $meta_key Metadata name.
642 * @param mixed $meta_value Optional. Metadata value.
643 * @return bool False for failure. True for success.
645 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
646 // make sure meta is added to the post, not a revision
647 if ( $the_post = wp_is_post_revision($post_id) )
648 $post_id = $the_post;
650 return delete_metadata('post', $post_id, $meta_key, $meta_value);
654 * Retrieve post meta field for a post.
658 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
660 * @param int $post_id Post ID.
661 * @param string $key The meta key to retrieve.
662 * @param bool $single Whether to return a single value.
663 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
666 function get_post_meta($post_id, $key, $single = false) {
667 return get_metadata('post', $post_id, $key, $single);
671 * Update post meta field based on post ID.
673 * Use the $prev_value parameter to differentiate between meta fields with the
674 * same key and post ID.
676 * If the meta field for the post does not exist, it will be added.
680 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
682 * @param int $post_id Post ID.
683 * @param string $key Metadata key.
684 * @param mixed $value Metadata value.
685 * @param mixed $prev_value Optional. Previous value to check before removing.
686 * @return bool False on failure, true if success.
688 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
689 // make sure meta is added to the post, not a revision
690 if ( $the_post = wp_is_post_revision($post_id) )
691 $post_id = $the_post;
693 return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
697 * Delete everything from post meta matching meta key.
702 * @param string $post_meta_key Key to search for when deleting.
703 * @return bool Whether the post meta key was deleted from the database
705 function delete_post_meta_by_key($post_meta_key) {
706 if ( !$post_meta_key )
710 $post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
712 $postmetaids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key ) );
713 $in = implode( ',', array_fill(1, count($postmetaids), '%d'));
714 do_action( 'delete_postmeta', $postmetaids );
715 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN($in)", $postmetaids ));
716 do_action( 'deleted_postmeta', $postmetaids );
717 foreach ( $post_ids as $post_id )
718 wp_cache_delete($post_id, 'post_meta');
725 * Retrieve post meta fields, based on post ID.
727 * The post meta fields are retrieved from the cache, so the function is
728 * optimized to be called more than once. It also applies to the functions, that
732 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
734 * @uses $id Current Loop Post ID
736 * @param int $post_id post ID
739 function get_post_custom($post_id = 0) {
743 $post_id = (int) $id;
745 $post_id = (int) $post_id;
747 if ( ! wp_cache_get($post_id, 'post_meta') )
748 update_postmeta_cache($post_id);
750 return wp_cache_get($post_id, 'post_meta');
754 * Retrieve meta field names for a post.
756 * If there are no meta fields, then nothing (null) will be returned.
759 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
761 * @param int $post_id post ID
762 * @return array|null Either array of the keys, or null if keys could not be retrieved.
764 function get_post_custom_keys( $post_id = 0 ) {
765 $custom = get_post_custom( $post_id );
767 if ( !is_array($custom) )
770 if ( $keys = array_keys($custom) )
775 * Retrieve values for a custom post field.
777 * The parameters must not be considered optional. All of the post meta fields
778 * will be retrieved and only the meta field key values returned.
781 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
783 * @param string $key Meta field key.
784 * @param int $post_id Post ID
785 * @return array Meta field values.
787 function get_post_custom_values( $key = '', $post_id = 0 ) {
791 $custom = get_post_custom($post_id);
793 return isset($custom[$key]) ? $custom[$key] : null;
797 * Check if post is sticky.
799 * Sticky posts should remain at the top of The Loop. If the post ID is not
800 * given, then The Loop ID for the current post will be used.
804 * @param int $post_id Optional. Post ID.
805 * @return bool Whether post is sticky (true) or not sticky (false).
807 function is_sticky($post_id = null) {
810 $post_id = absint($post_id);
813 $post_id = absint($id);
815 $stickies = get_option('sticky_posts');
817 if ( !is_array($stickies) )
820 if ( in_array($post_id, $stickies) )
827 * Sanitize every post field.
829 * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
832 * @uses sanitize_post_field() Used to sanitize the fields.
834 * @param object|array $post The Post Object or Array
835 * @param string $context Optional, default is 'display'. How to sanitize post fields.
836 * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
838 function sanitize_post($post, $context = 'display') {
839 if ( is_object($post) ) {
840 // Check if post already filtered for this context
841 if ( isset($post->filter) && $context == $post->filter )
843 if ( !isset($post->ID) )
845 foreach ( array_keys(get_object_vars($post)) as $field )
846 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
847 $post->filter = $context;
849 // Check if post already filtered for this context
850 if ( isset($post['filter']) && $context == $post['filter'] )
852 if ( !isset($post['ID']) )
854 foreach ( array_keys($post) as $field )
855 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
856 $post['filter'] = $context;
863 * Sanitize post field based on context.
865 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
866 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
867 * when calling filters.
870 * @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
871 * $post_id if $context == 'edit' and field name prefix == 'post_'.
873 * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
874 * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
875 * @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
877 * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
878 * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
879 * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
880 * 'edit' and 'db' and field name prefix != 'post_'.
882 * @param string $field The Post Object field name.
883 * @param mixed $value The Post Object value.
884 * @param int $post_id Post ID.
885 * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
886 * 'attribute' and 'js'.
887 * @return mixed Sanitized value.
889 function sanitize_post_field($field, $value, $post_id, $context) {
890 $int_fields = array('ID', 'post_parent', 'menu_order');
891 if ( in_array($field, $int_fields) )
892 $value = (int) $value;
894 if ( 'raw' == $context )
898 if ( false !== strpos($field, 'post_') ) {
900 $field_no_prefix = str_replace('post_', '', $field);
903 if ( 'edit' == $context ) {
904 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
907 $value = apply_filters("edit_$field", $value, $post_id);
909 $value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
911 $value = apply_filters("edit_post_$field", $value, $post_id);
914 if ( in_array($field, $format_to_edit) ) {
915 if ( 'post_content' == $field )
916 $value = format_to_edit($value, user_can_richedit());
918 $value = format_to_edit($value);
920 $value = esc_attr($value);
922 } else if ( 'db' == $context ) {
924 $value = apply_filters("pre_$field", $value);
925 $value = apply_filters("${field_no_prefix}_save_pre", $value);
927 $value = apply_filters("pre_post_$field", $value);
928 $value = apply_filters("${field}_pre", $value);
931 // Use display filters by default.
933 $value = apply_filters($field, $value, $post_id, $context);
935 $value = apply_filters("post_$field", $value, $post_id, $context);
938 if ( 'attribute' == $context )
939 $value = esc_attr($value);
940 else if ( 'js' == $context )
941 $value = esc_js($value);
947 * Make a post sticky.
949 * Sticky posts should be displayed at the top of the front page.
953 * @param int $post_id Post ID.
955 function stick_post($post_id) {
956 $stickies = get_option('sticky_posts');
958 if ( !is_array($stickies) )
959 $stickies = array($post_id);
961 if ( ! in_array($post_id, $stickies) )
962 $stickies[] = $post_id;
964 update_option('sticky_posts', $stickies);
970 * Sticky posts should be displayed at the top of the front page.
974 * @param int $post_id Post ID.
976 function unstick_post($post_id) {
977 $stickies = get_option('sticky_posts');
979 if ( !is_array($stickies) )
982 if ( ! in_array($post_id, $stickies) )
985 $offset = array_search($post_id, $stickies);
986 if ( false === $offset )
989 array_splice($stickies, $offset, 1);
991 update_option('sticky_posts', $stickies);
995 * Count number of posts of a post type and is user has permissions to view.
997 * This function provides an efficient method of finding the amount of post's
998 * type a blog has. Another method is to count the amount of items in
999 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
1000 * when developing for 2.5+, use this function instead.
1002 * The $perm parameter checks for 'readable' value and if the user can read
1003 * private posts, it will display that for the user that is signed in.
1006 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
1008 * @param string $type Optional. Post type to retrieve count
1009 * @param string $perm Optional. 'readable' or empty.
1010 * @return object Number of posts for each status
1012 function wp_count_posts( $type = 'post', $perm = '' ) {
1015 $user = wp_get_current_user();
1019 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
1020 if ( 'readable' == $perm && is_user_logged_in() ) {
1021 if ( !current_user_can("read_private_{$type}s") ) {
1022 $cache_key .= '_' . $perm . '_' . $user->ID;
1023 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
1026 $query .= ' GROUP BY post_status';
1028 $count = wp_cache_get($cache_key, 'counts');
1029 if ( false !== $count )
1032 $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
1034 $stats = array( 'publish' => 0, 'private' => 0, 'draft' => 0, 'pending' => 0, 'future' => 0, 'trash' => 0 );
1035 foreach( (array) $count as $row_num => $row ) {
1036 $stats[$row['post_status']] = $row['num_posts'];
1039 $stats = (object) $stats;
1040 wp_cache_set($cache_key, $stats, 'counts');
1047 * Count number of attachments for the mime type(s).
1049 * If you set the optional mime_type parameter, then an array will still be
1050 * returned, but will only have the item you are looking for. It does not give
1051 * you the number of attachments that are children of a post. You can get that
1052 * by counting the number of children that post has.
1056 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
1057 * @return array Number of posts for each mime type.
1059 function wp_count_attachments( $mime_type = '' ) {
1062 $and = wp_post_mime_type_where( $mime_type );
1063 $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 );
1066 foreach( (array) $count as $row ) {
1067 $stats[$row['post_mime_type']] = $row['num_posts'];
1069 $stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
1071 return (object) $stats;
1075 * Check a MIME-Type against a list.
1077 * If the wildcard_mime_types parameter is a string, it must be comma separated
1078 * list. If the real_mime_types is a string, it is also comma separated to
1083 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
1084 * flash (same as *flash*).
1085 * @param string|array $real_mime_types post_mime_type values
1086 * @return array array(wildcard=>array(real types))
1088 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
1090 if ( is_string($wildcard_mime_types) )
1091 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
1092 if ( is_string($real_mime_types) )
1093 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
1094 $wild = '[-._a-z0-9]*';
1095 foreach ( (array) $wildcard_mime_types as $type ) {
1096 $type = str_replace('*', $wild, $type);
1097 $patternses[1][$type] = "^$type$";
1098 if ( false === strpos($type, '/') ) {
1099 $patternses[2][$type] = "^$type/";
1100 $patternses[3][$type] = $type;
1104 foreach ( $patternses as $patterns )
1105 foreach ( $patterns as $type => $pattern )
1106 foreach ( (array) $real_mime_types as $real )
1107 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
1108 $matches[$type][] = $real;
1113 * Convert MIME types into SQL.
1117 * @param string|array $mime_types List of mime types or comma separated string of mime types.
1118 * @return string The SQL AND clause for mime searching.
1120 function wp_post_mime_type_where($post_mime_types) {
1122 $wildcards = array('', '%', '%/%');
1123 if ( is_string($post_mime_types) )
1124 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
1125 foreach ( (array) $post_mime_types as $mime_type ) {
1126 $mime_type = preg_replace('/\s/', '', $mime_type);
1127 $slashpos = strpos($mime_type, '/');
1128 if ( false !== $slashpos ) {
1129 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
1130 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
1131 if ( empty($mime_subgroup) )
1132 $mime_subgroup = '*';
1134 $mime_subgroup = str_replace('/', '', $mime_subgroup);
1135 $mime_pattern = "$mime_group/$mime_subgroup";
1137 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
1138 if ( false === strpos($mime_pattern, '*') )
1139 $mime_pattern .= '/*';
1142 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
1144 if ( in_array( $mime_type, $wildcards ) )
1147 if ( false !== strpos($mime_pattern, '%') )
1148 $wheres[] = "post_mime_type LIKE '$mime_pattern'";
1150 $wheres[] = "post_mime_type = '$mime_pattern'";
1152 if ( !empty($wheres) )
1153 $where = ' AND (' . join(' OR ', $wheres) . ') ';
1158 * Removes a post, attachment, or page.
1160 * When the post and page goes, everything that is tied to it is deleted also.
1161 * This includes comments, post meta fields, and terms associated with the post.
1164 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
1165 * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
1166 * @uses wp_delete_attachment() if post type is 'attachment'.
1168 * @param int $postid Post ID.
1169 * @param bool $force_delete Whether to bypass trash and force deletion
1170 * @return mixed False on failure
1172 function wp_delete_post( $postid = 0, $force_delete = false ) {
1173 global $wpdb, $wp_rewrite;
1175 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
1178 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS > 0 )
1179 return wp_trash_post($postid);
1181 if ( $post->post_type == 'attachment' )
1182 return wp_delete_attachment( $postid, $force_delete );
1184 do_action('delete_post', $postid);
1186 delete_post_meta($postid,'_wp_trash_meta_status');
1187 delete_post_meta($postid,'_wp_trash_meta_time');
1189 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
1191 $parent_data = array( 'post_parent' => $post->post_parent );
1192 $parent_where = array( 'post_parent' => $postid );
1194 if ( 'page' == $post->post_type) {
1195 // if the page is defined in option page_on_front or post_for_posts,
1196 // adjust the corresponding options
1197 if ( get_option('page_on_front') == $postid ) {
1198 update_option('show_on_front', 'posts');
1199 delete_option('page_on_front');
1201 if ( get_option('page_for_posts') == $postid ) {
1202 delete_option('page_for_posts');
1205 // Point children of this page to its parent, also clean the cache of affected children
1206 $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
1207 $children = $wpdb->get_results($children_query);
1209 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
1211 unstick_post($postid);
1214 // Do raw query. wp_get_post_revisions() is filtered
1215 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
1216 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
1217 foreach ( $revision_ids as $revision_id )
1218 wp_delete_post_revision( $revision_id );
1220 // Point all attachments to this post up one level
1221 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
1223 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
1224 if ( ! empty($comment_ids) ) {
1225 do_action( 'delete_comment', $comment_ids );
1226 $in_comment_ids = "'" . implode("', '", $comment_ids) . "'";
1227 $wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_ID IN($in_comment_ids)" );
1228 do_action( 'deleted_comment', $comment_ids );
1231 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
1232 if ( !empty($post_meta_ids) ) {
1233 do_action( 'delete_postmeta', $post_meta_ids );
1234 $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
1235 $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
1236 do_action( 'deleted_postmeta', $post_meta_ids );
1239 do_action( 'delete_post', $postid );
1240 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
1241 do_action( 'deleted_post', $postid );
1243 if ( 'page' == $post->post_type ) {
1244 clean_page_cache($postid);
1246 foreach ( (array) $children as $child )
1247 clean_page_cache($child->ID);
1249 $wp_rewrite->flush_rules(false);
1251 clean_post_cache($postid);
1254 wp_clear_scheduled_hook('publish_future_post', $postid);
1256 do_action('deleted_post', $postid);
1262 * Moves a post or page to the Trash
1265 * @uses do_action() on 'trash_post' before trashing
1266 * @uses do_action() on 'trashed_post' after trashing
1268 * @param int $postid Post ID.
1269 * @return mixed False on failure
1271 function wp_trash_post($post_id = 0) {
1272 if ( EMPTY_TRASH_DAYS == 0 )
1273 return wp_delete_post($post_id);
1275 if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
1278 if ( $post['post_status'] == 'trash' )
1281 do_action('trash_post', $post_id);
1283 add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
1284 add_post_meta($post_id,'_wp_trash_meta_time', time());
1286 $post['post_status'] = 'trash';
1287 wp_insert_post($post);
1289 wp_trash_post_comments($post_id);
1291 do_action('trashed_post', $post_id);
1297 * Restores a post or page from the Trash
1300 * @uses do_action() on 'untrash_post' before undeletion
1301 * @uses do_action() on 'untrashed_post' after undeletion
1303 * @param int $postid Post ID.
1304 * @return mixed False on failure
1306 function wp_untrash_post($post_id = 0) {
1307 if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
1310 if ( $post['post_status'] != 'trash' )
1313 do_action('untrash_post', $post_id);
1315 $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
1317 $post['post_status'] = $post_status;
1319 delete_post_meta($post_id, '_wp_trash_meta_status');
1320 delete_post_meta($post_id, '_wp_trash_meta_time');
1322 wp_insert_post($post);
1324 wp_untrash_post_comments($post_id);
1326 do_action('untrashed_post', $post_id);
1332 * Moves comments for a post to the trash
1335 * @uses do_action() on 'trash_post_comments' before trashing
1336 * @uses do_action() on 'trashed_post_comments' after trashing
1338 * @param int $post Post ID or object.
1339 * @return mixed False on failure
1341 function wp_trash_post_comments($post = null) {
1344 $post = get_post($post);
1348 $post_id = $post->ID;
1350 do_action('trash_post_comments', $post_id);
1352 $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
1353 if ( empty($comments) )
1356 // Cache current status for each comment
1357 $statuses = array();
1358 foreach ( $comments as $comment )
1359 $statuses[$comment->comment_ID] = $comment->comment_approved;
1360 add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
1362 // Set status for all comments to post-trashed
1363 $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
1365 clean_comment_cache( array_keys($statuses) );
1367 do_action('trashed_post_comments', $post_id, $statuses);
1373 * Restore comments for a post from the trash
1376 * @uses do_action() on 'untrash_post_comments' before trashing
1377 * @uses do_action() on 'untrashed_post_comments' after trashing
1379 * @param int $post Post ID or object.
1380 * @return mixed False on failure
1382 function wp_untrash_post_comments($post = null) {
1385 $post = get_post($post);
1389 $post_id = $post->ID;
1391 $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
1393 if ( empty($statuses) )
1396 do_action('untrash_post_comments', $post_id);
1398 // Restore each comment to its original status
1399 $group_by_status = array();
1400 foreach ( $statuses as $comment_id => $comment_status )
1401 $group_by_status[$comment_status][] = $comment_id;
1403 foreach ( $group_by_status as $status => $comments ) {
1404 // Sanity check. This shouldn't happen.
1405 if ( 'post-trashed' == $status )
1407 $comments_in = implode( "', '", $comments );
1408 $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
1411 clean_comment_cache( array_keys($statuses) );
1413 delete_post_meta($post_id, '_wp_trash_meta_comments_status');
1415 do_action('untrashed_post_comments', $post_id);
1419 * Retrieve the list of categories for a post.
1421 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
1422 * away from the complexity of the taxonomy layer.
1426 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
1428 * @param int $post_id Optional. The Post ID.
1429 * @param array $args Optional. Overwrite the defaults.
1432 function wp_get_post_categories( $post_id = 0, $args = array() ) {
1433 $post_id = (int) $post_id;
1435 $defaults = array('fields' => 'ids');
1436 $args = wp_parse_args( $args, $defaults );
1438 $cats = wp_get_object_terms($post_id, 'category', $args);
1443 * Retrieve the tags for a post.
1445 * There is only one default for this function, called 'fields' and by default
1446 * is set to 'all'. There are other defaults that can be overridden in
1447 * {@link wp_get_object_terms()}.
1449 * @package WordPress
1453 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1455 * @param int $post_id Optional. The Post ID
1456 * @param array $args Optional. Overwrite the defaults
1457 * @return array List of post tags.
1459 function wp_get_post_tags( $post_id = 0, $args = array() ) {
1460 return wp_get_post_terms( $post_id, 'post_tag', $args);
1464 * Retrieve the terms for a post.
1466 * There is only one default for this function, called 'fields' and by default
1467 * is set to 'all'. There are other defaults that can be overridden in
1468 * {@link wp_get_object_terms()}.
1470 * @package WordPress
1474 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1476 * @param int $post_id Optional. The Post ID
1477 * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
1478 * @param array $args Optional. Overwrite the defaults
1479 * @return array List of post tags.
1481 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
1482 $post_id = (int) $post_id;
1484 $defaults = array('fields' => 'all');
1485 $args = wp_parse_args( $args, $defaults );
1487 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
1493 * Retrieve number of recent posts.
1498 * @param int $num Optional, default is 10. Number of posts to get.
1499 * @return array List of posts.
1501 function wp_get_recent_posts($num = 10) {
1504 // Set the limit clause, if we got a limit
1507 $limit = "LIMIT $num";
1510 $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status IN ( 'draft', 'publish', 'future', 'pending', 'private' ) ORDER BY post_date DESC $limit";
1511 $result = $wpdb->get_results($sql, ARRAY_A);
1513 return $result ? $result : array();
1517 * Retrieve a single post, based on post ID.
1519 * Has categories in 'post_category' property or key. Has tags in 'tags_input'
1524 * @param int $postid Post ID.
1525 * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
1526 * @return object|array Post object or array holding post contents and information
1528 function wp_get_single_post($postid = 0, $mode = OBJECT) {
1529 $postid = (int) $postid;
1531 $post = get_post($postid, $mode);
1533 // Set categories and tags
1534 if($mode == OBJECT) {
1535 $post->post_category = wp_get_post_categories($postid);
1536 $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
1539 $post['post_category'] = wp_get_post_categories($postid);
1540 $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
1549 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
1551 * You can set the post date manually, but setting the values for 'post_date'
1552 * and 'post_date_gmt' keys. You can close the comments or open the comments by
1553 * setting the value for 'comment_status' key.
1555 * The defaults for the parameter $postarr are:
1556 * 'post_status' - Default is 'draft'.
1557 * 'post_type' - Default is 'post'.
1558 * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post.
1559 * 'ping_status' - Default is the value in 'default_ping_status' option.
1560 * Whether the attachment can accept pings.
1561 * 'post_parent' - Default is 0. Set this for the post it belongs to, if any.
1562 * 'menu_order' - Default is 0. The order it is displayed.
1563 * 'to_ping' - Whether to ping.
1564 * 'pinged' - Default is empty string.
1565 * 'post_password' - Default is empty string. The password to access the attachment.
1566 * 'guid' - Global Unique ID for referencing the attachment.
1567 * 'post_content_filtered' - Post content filtered.
1568 * 'post_excerpt' - Post excerpt.
1571 * @link http://core.trac.wordpress.org/ticket/9084 Bug report on 'wp_insert_post_data' filter.
1576 * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
1577 * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
1578 * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before
1581 * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database
1583 * @uses wp_transition_post_status()
1585 * @param array $postarr Optional. Overrides defaults.
1586 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
1587 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
1589 function wp_insert_post($postarr = array(), $wp_error = false) {
1590 global $wpdb, $wp_rewrite, $user_ID;
1592 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
1593 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
1594 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
1595 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
1597 $postarr = wp_parse_args($postarr, $defaults);
1598 $postarr = sanitize_post($postarr, 'db');
1600 // export array as variables
1601 extract($postarr, EXTR_SKIP);
1603 // Are we updating or creating?
1605 if ( !empty($ID) ) {
1607 $previous_status = get_post_field('post_status', $ID);
1609 $previous_status = 'new';
1612 if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) && ('attachment' != $post_type) ) {
1614 return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
1619 // Make sure we set a valid category
1620 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
1621 $post_category = array(get_option('default_category'));
1624 //Set the default tag list
1625 if ( !isset($tags_input) )
1626 $tags_input = array();
1628 if ( empty($post_author) )
1629 $post_author = $user_ID;
1631 if ( empty($post_status) )
1632 $post_status = 'draft';
1634 if ( empty($post_type) )
1635 $post_type = 'post';
1639 // Get the post ID and GUID
1641 $post_ID = (int) $ID;
1642 $guid = get_post_field( 'guid', $post_ID );
1645 // Don't allow contributors to set to set the post slug for pending review posts
1646 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
1649 // Create a valid post name. Drafts and pending posts are allowed to have an empty
1651 if ( !isset($post_name) || empty($post_name) ) {
1652 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1653 $post_name = sanitize_title($post_title);
1657 $post_name = sanitize_title($post_name);
1660 // 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
1661 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
1662 $post_date = current_time('mysql');
1664 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
1665 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1666 $post_date_gmt = get_gmt_from_date($post_date);
1668 $post_date_gmt = '0000-00-00 00:00:00';
1671 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
1672 $post_modified = current_time( 'mysql' );
1673 $post_modified_gmt = current_time( 'mysql', 1 );
1675 $post_modified = $post_date;
1676 $post_modified_gmt = $post_date_gmt;
1679 if ( 'publish' == $post_status ) {
1680 $now = gmdate('Y-m-d H:i:59');
1681 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
1682 $post_status = 'future';
1685 if ( empty($comment_status) ) {
1687 $comment_status = 'closed';
1689 $comment_status = get_option('default_comment_status');
1691 if ( empty($ping_status) )
1692 $ping_status = get_option('default_ping_status');
1694 if ( isset($to_ping) )
1695 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
1699 if ( ! isset($pinged) )
1702 if ( isset($post_parent) )
1703 $post_parent = (int) $post_parent;
1707 if ( !empty($post_ID) ) {
1708 if ( $post_parent == $post_ID ) {
1709 // Post can't be its own parent
1711 } elseif ( !empty($post_parent) ) {
1712 $parent_post = get_post($post_parent);
1713 // Check for circular dependency
1714 if ( $parent_post->post_parent == $post_ID )
1719 if ( isset($menu_order) )
1720 $menu_order = (int) $menu_order;
1724 if ( !isset($post_password) || 'private' == $post_status )
1725 $post_password = '';
1727 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
1729 // expected_slashed (everything!)
1730 $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' ) );
1731 $data = apply_filters('wp_insert_post_data', $data, $postarr);
1732 $data = stripslashes_deep( $data );
1733 $where = array( 'ID' => $post_ID );
1736 do_action( 'pre_post_update', $post_ID );
1737 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
1739 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
1744 if ( isset($post_mime_type) )
1745 $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
1746 // If there is a suggested ID, use it if not already present
1747 if ( !empty($import_id) ) {
1748 $import_id = (int) $import_id;
1749 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
1750 $data['ID'] = $import_id;
1753 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
1755 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
1759 $post_ID = (int) $wpdb->insert_id;
1761 // use the newly generated $post_ID
1762 $where = array( 'ID' => $post_ID );
1765 if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending' ) ) ) {
1766 $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
1767 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
1770 wp_set_post_categories( $post_ID, $post_category );
1771 // old-style tags_input
1772 if ( !empty($tags_input) )
1773 wp_set_post_tags( $post_ID, $tags_input );
1774 // new-style support for all tag-like taxonomies
1775 if ( !empty($tax_input) ) {
1776 foreach ( $tax_input as $taxonomy => $tags ) {
1777 wp_set_post_terms( $post_ID, $tags, $taxonomy );
1781 $current_guid = get_post_field( 'guid', $post_ID );
1783 if ( 'page' == $data['post_type'] )
1784 clean_page_cache($post_ID);
1786 clean_post_cache($post_ID);
1789 if ( !$update && '' == $current_guid )
1790 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
1792 $post = get_post($post_ID);
1794 if ( !empty($page_template) && 'page' == $data['post_type'] ) {
1795 $post->page_template = $page_template;
1796 $page_templates = get_page_templates();
1797 if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
1799 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
1803 update_post_meta($post_ID, '_wp_page_template', $page_template);
1806 wp_transition_post_status($data['post_status'], $previous_status, $post);
1809 do_action('edit_post', $post_ID, $post);
1811 do_action('save_post', $post_ID, $post);
1812 do_action('wp_insert_post', $post_ID, $post);
1818 * Update a post with new post data.
1820 * The date does not have to be set for drafts. You can set the date and it will
1821 * not be overridden.
1825 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
1826 * @return int 0 on failure, Post ID on success.
1828 function wp_update_post($postarr = array()) {
1829 if ( is_object($postarr) ) {
1830 // non-escaped post was passed
1831 $postarr = get_object_vars($postarr);
1832 $postarr = add_magic_quotes($postarr);
1835 // First, get all of the original fields
1836 $post = wp_get_single_post($postarr['ID'], ARRAY_A);
1838 // Escape data pulled from DB.
1839 $post = add_magic_quotes($post);
1841 // Passed post category list overwrites existing category list if not empty.
1842 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
1843 && 0 != count($postarr['post_category']) )
1844 $post_cats = $postarr['post_category'];
1846 $post_cats = $post['post_category'];
1848 // Drafts shouldn't be assigned a date unless explicitly done so by the user
1849 if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
1850 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
1853 $clear_date = false;
1855 // Merge old and new fields with new fields overwriting old ones.
1856 $postarr = array_merge($post, $postarr);
1857 $postarr['post_category'] = $post_cats;
1858 if ( $clear_date ) {
1859 $postarr['post_date'] = current_time('mysql');
1860 $postarr['post_date_gmt'] = '';
1863 if ($postarr['post_type'] == 'attachment')
1864 return wp_insert_attachment($postarr);
1866 return wp_insert_post($postarr);
1870 * Publish a post by transitioning the post status.
1874 * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
1876 * @param int $post_id Post ID.
1879 function wp_publish_post($post_id) {
1882 $post = get_post($post_id);
1887 if ( 'publish' == $post->post_status )
1890 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
1892 $old_status = $post->post_status;
1893 $post->post_status = 'publish';
1894 wp_transition_post_status('publish', $old_status, $post);
1896 // Update counts for the post's terms.
1897 foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
1898 $tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
1899 wp_update_term_count($tt_ids, $taxonomy);
1902 do_action('edit_post', $post_id, $post);
1903 do_action('save_post', $post_id, $post);
1904 do_action('wp_insert_post', $post_id, $post);
1908 * Publish future post and make sure post ID has future post status.
1910 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
1911 * from publishing drafts, etc.
1915 * @param int $post_id Post ID.
1916 * @return null Nothing is returned. Which can mean that no action is required or post was published.
1918 function check_and_publish_future_post($post_id) {
1920 $post = get_post($post_id);
1925 if ( 'future' != $post->post_status )
1928 $time = strtotime( $post->post_date_gmt . ' GMT' );
1930 if ( $time > time() ) { // Uh oh, someone jumped the gun!
1931 wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
1932 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
1936 return wp_publish_post($post_id);
1941 * Given the desired slug and some post details computes a unique slug for the post.
1943 * @global wpdb $wpdb
1944 * @global WP_Rewrite $wp_rewrite
1945 * @param string $slug the desired slug (post_name)
1946 * @param integer $post_ID
1947 * @param string $post_status no uniqueness checks are made if the post is still draft or pending
1948 * @param string $post_type
1949 * @param integer $post_parent
1950 * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
1952 function wp_unique_post_slug($slug, $post_ID, $post_status, $post_type, $post_parent) {
1953 if ( in_array( $post_status, array( 'draft', 'pending' ) ) )
1956 global $wpdb, $wp_rewrite;
1958 $feeds = $wp_rewrite->feeds;
1959 if ( !is_array($feeds) )
1962 $hierarchical_post_types = apply_filters('hierarchical_post_types', array('page'));
1963 if ( 'attachment' == $post_type ) {
1964 // Attachment slugs must be unique across all types.
1965 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
1966 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID));
1968 if ( $post_name_check || in_array($slug, $feeds) ) {
1971 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1972 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID));
1974 } while ($post_name_check);
1975 $slug = $alt_post_name;
1977 } elseif ( in_array($post_type, $hierarchical_post_types) ) {
1978 // Page slugs must be unique within their own trees. Pages are in a
1979 // separate namespace than posts so page slugs are allowed to overlap post slugs.
1980 $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";
1981 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID, $post_parent));
1983 if ( $post_name_check || in_array($slug, $feeds) ) {
1986 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1987 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID, $post_parent));
1989 } while ($post_name_check);
1990 $slug = $alt_post_name;
1993 // Post slugs must be unique across all posts.
1994 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
1995 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_type, $post_ID));
1997 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
2000 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
2001 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_type, $post_ID));
2003 } while ($post_name_check);
2004 $slug = $alt_post_name;
2012 * Adds tags to a post.
2014 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
2016 * @package WordPress
2020 * @param int $post_id Post ID
2021 * @param string $tags The tags to set for the post, separated by commas.
2022 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
2024 function wp_add_post_tags($post_id = 0, $tags = '') {
2025 return wp_set_post_tags($post_id, $tags, true);
2030 * Set the tags for a post.
2033 * @uses wp_set_object_terms() Sets the tags for the post.
2035 * @param int $post_id Post ID.
2036 * @param string $tags The tags to set for the post, separated by commas.
2037 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
2038 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
2040 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
2041 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
2045 * Set the terms for a post.
2048 * @uses wp_set_object_terms() Sets the tags for the post.
2050 * @param int $post_id Post ID.
2051 * @param string $tags The tags to set for the post, separated by commas.
2052 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
2053 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
2055 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
2056 $post_id = (int) $post_id;
2064 $tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
2065 wp_set_object_terms($post_id, $tags, $taxonomy, $append);
2069 * Set categories for a post.
2071 * If the post categories parameter is not set, then the default category is
2076 * @param int $post_ID Post ID.
2077 * @param array $post_categories Optional. List of categories.
2078 * @return bool|mixed
2080 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
2081 $post_ID = (int) $post_ID;
2082 // If $post_categories isn't already an array, make it one:
2083 if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
2084 $post_categories = array(get_option('default_category'));
2085 else if ( 1 == count($post_categories) && '' == $post_categories[0] )
2088 $post_categories = array_map('intval', $post_categories);
2089 $post_categories = array_unique($post_categories);
2091 return wp_set_object_terms($post_ID, $post_categories, 'category');
2095 * Transition the post status of a post.
2097 * Calls hooks to transition post status.
2099 * The first is 'transition_post_status' with new status, old status, and post data.
2101 * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
2102 * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
2105 * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
2106 * parameter and POSTTYPE is post_type post data.
2109 * @link http://codex.wordpress.org/Post_Status_Transitions
2111 * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
2112 * $post if there is a status change.
2113 * @uses do_action() Calls '${old_status}_to_$new_status' on $post if there is a status change.
2114 * @uses do_action() Calls '${new_status}_$post->post_type' on post ID and $post.
2116 * @param string $new_status Transition to this post status.
2117 * @param string $old_status Previous post status.
2118 * @param object $post Post data.
2120 function wp_transition_post_status($new_status, $old_status, $post) {
2121 do_action('transition_post_status', $new_status, $old_status, $post);
2122 do_action("${old_status}_to_$new_status", $post);
2123 do_action("${new_status}_$post->post_type", $post->ID, $post);
2127 // Trackback and ping functions
2131 * Add a URL to those already pung.
2136 * @param int $post_id Post ID.
2137 * @param string $uri Ping URI.
2138 * @return int How many rows were updated.
2140 function add_ping($post_id, $uri) {
2142 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
2143 $pung = trim($pung);
2144 $pung = preg_split('/\s/', $pung);
2146 $new = implode("\n", $pung);
2147 $new = apply_filters('add_ping', $new);
2148 // expected_slashed ($new)
2149 $new = stripslashes($new);
2150 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
2154 * Retrieve enclosures already enclosed for a post.
2159 * @param int $post_id Post ID.
2160 * @return array List of enclosures
2162 function get_enclosed($post_id) {
2163 $custom_fields = get_post_custom( $post_id );
2165 if ( !is_array( $custom_fields ) )
2168 foreach ( $custom_fields as $key => $val ) {
2169 if ( 'enclosure' != $key || !is_array( $val ) )
2171 foreach( $val as $enc ) {
2172 $enclosure = split( "\n", $enc );
2173 $pung[] = trim( $enclosure[ 0 ] );
2176 $pung = apply_filters('get_enclosed', $pung);
2181 * Retrieve URLs already pinged for a post.
2186 * @param int $post_id Post ID.
2189 function get_pung($post_id) {
2191 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
2192 $pung = trim($pung);
2193 $pung = preg_split('/\s/', $pung);
2194 $pung = apply_filters('get_pung', $pung);
2199 * Retrieve URLs that need to be pinged.
2204 * @param int $post_id Post ID
2207 function get_to_ping($post_id) {
2209 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
2210 $to_ping = trim($to_ping);
2211 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
2212 $to_ping = apply_filters('get_to_ping', $to_ping);
2217 * Do trackbacks for a list of URLs.
2221 * @param string $tb_list Comma separated list of URLs
2222 * @param int $post_id Post ID
2224 function trackback_url_list($tb_list, $post_id) {
2225 if ( ! empty( $tb_list ) ) {
2227 $postdata = wp_get_single_post($post_id, ARRAY_A);
2229 // import postdata as variables
2230 extract($postdata, EXTR_SKIP);
2233 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
2235 if (strlen($excerpt) > 255) {
2236 $excerpt = substr($excerpt,0,252) . '...';
2239 $trackback_urls = explode(',', $tb_list);
2240 foreach( (array) $trackback_urls as $tb_url) {
2241 $tb_url = trim($tb_url);
2242 trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
2252 * Get a list of page IDs.
2257 * @return array List of page IDs.
2259 function get_all_page_ids() {
2262 if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
2263 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
2264 wp_cache_add('all_page_ids', $page_ids, 'posts');
2271 * Retrieves page data given a page ID or page object.
2275 * @param mixed $page Page object or page ID. Passed by reference.
2276 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
2277 * @param string $filter How the return value should be filtered.
2278 * @return mixed Page data.
2280 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
2281 if ( empty($page) ) {
2282 if ( isset( $GLOBALS['post'] ) && isset( $GLOBALS['post']->ID ) ) {
2283 return get_post($GLOBALS['post'], $output, $filter);
2290 $the_page = get_post($page, $output, $filter);
2295 * Retrieves a page given its path.
2300 * @param string $page_path Page path
2301 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
2302 * @return mixed Null when complete.
2304 function get_page_by_path($page_path, $output = OBJECT) {
2306 $page_path = rawurlencode(urldecode($page_path));
2307 $page_path = str_replace('%2F', '/', $page_path);
2308 $page_path = str_replace('%20', ' ', $page_path);
2309 $page_paths = '/' . trim($page_path, '/');
2310 $leaf_path = sanitize_title(basename($page_paths));
2311 $page_paths = explode('/', $page_paths);
2313 foreach( (array) $page_paths as $pathdir)
2314 $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
2316 $pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = 'page' OR post_type = 'attachment')", $leaf_path ));
2318 if ( empty($pages) )
2321 foreach ($pages as $page) {
2322 $path = '/' . $leaf_path;
2324 while ($curpage->post_parent != 0) {
2325 $curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type='page'", $curpage->post_parent ));
2326 $path = '/' . $curpage->post_name . $path;
2329 if ( $path == $full_path )
2330 return get_page($page->ID, $output);
2337 * Retrieve a page given its title.
2342 * @param string $page_title Page title
2343 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
2346 function get_page_by_title($page_title, $output = OBJECT) {
2348 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
2350 return get_page($page, $output);
2356 * Retrieve child pages from list of pages matching page ID.
2358 * Matches against the pages parameter against the page ID. Also matches all
2359 * children for the same to retrieve all children of a page. Does not make any
2360 * SQL queries to get the children.
2364 * @param int $page_id Page ID.
2365 * @param array $pages List of pages' objects.
2368 function &get_page_children($page_id, $pages) {
2369 $page_list = array();
2370 foreach ( (array) $pages as $page ) {
2371 if ( $page->post_parent == $page_id ) {
2372 $page_list[] = $page;
2373 if ( $children = get_page_children($page->ID, $pages) )
2374 $page_list = array_merge($page_list, $children);
2381 * Order the pages with children under parents in a flat list.
2383 * It uses auxiliary structure to hold parent-children relationships and
2384 * runs in O(N) complexity
2388 * @param array $posts Posts array.
2389 * @param int $parent Parent page ID.
2390 * @return array A list arranged by hierarchy. Children immediately follow their parents.
2392 function &get_page_hierarchy( &$pages, $page_id = 0 ) {
2394 if ( empty( $pages ) ) {
2399 $children = array();
2400 foreach ( (array) $pages as $p ) {
2402 $parent_id = intval( $p->post_parent );
2403 $children[ $parent_id ][] = $p;
2407 _page_traverse_name( $page_id, $children, $result );
2413 * function to traverse and return all the nested children post names of a root page.
2414 * $children contains parent-chilren relations
2417 function _page_traverse_name( $page_id, &$children, &$result ){
2419 if ( isset( $children[ $page_id ] ) ){
2421 foreach( (array)$children[ $page_id ] as $child ) {
2423 $result[ $child->ID ] = $child->post_name;
2424 _page_traverse_name( $child->ID, $children, $result );
2430 * Builds URI for a page.
2432 * Sub pages will be in the "directory" under the parent page post name.
2436 * @param int $page_id Page ID.
2437 * @return string Page URI.
2439 function get_page_uri($page_id) {
2440 $page = get_page($page_id);
2441 $uri = $page->post_name;
2443 // A page cannot be it's own parent.
2444 if ( $page->post_parent == $page->ID )
2447 while ($page->post_parent != 0) {
2448 $page = get_page($page->post_parent);
2449 $uri = $page->post_name . "/" . $uri;
2456 * Retrieve a list of pages.
2458 * The defaults that can be overridden are the following: 'child_of',
2459 * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
2460 * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
2465 * @param mixed $args Optional. Array or string of options that overrides defaults.
2466 * @return array List of pages matching defaults or $args
2468 function &get_pages($args = '') {
2472 'child_of' => 0, 'sort_order' => 'ASC',
2473 'sort_column' => 'post_title', 'hierarchical' => 1,
2474 'exclude' => '', 'include' => '',
2475 'meta_key' => '', 'meta_value' => '',
2476 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
2477 'number' => '', 'offset' => 0
2480 $r = wp_parse_args( $args, $defaults );
2481 extract( $r, EXTR_SKIP );
2482 $number = (int) $number;
2483 $offset = (int) $offset;
2486 $key = md5( serialize( compact(array_keys($defaults)) ) );
2487 if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
2488 if ( is_array($cache) && isset( $cache[ $key ] ) ) {
2489 $pages = apply_filters('get_pages', $cache[ $key ], $r );
2494 if ( !is_array($cache) )
2498 if ( !empty($include) ) {
2499 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
2504 $hierarchical = false;
2505 $incpages = preg_split('/[\s,]+/',$include);
2506 if ( count($incpages) ) {
2507 foreach ( $incpages as $incpage ) {
2508 if (empty($inclusions))
2509 $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
2511 $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
2515 if (!empty($inclusions))
2519 if ( !empty($exclude) ) {
2520 $expages = preg_split('/[\s,]+/',$exclude);
2521 if ( count($expages) ) {
2522 foreach ( $expages as $expage ) {
2523 if (empty($exclusions))
2524 $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
2526 $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
2530 if (!empty($exclusions))
2534 if (!empty($authors)) {
2535 $post_authors = preg_split('/[\s,]+/',$authors);
2537 if ( count($post_authors) ) {
2538 foreach ( $post_authors as $post_author ) {
2539 //Do we have an author id or an author login?
2540 if ( 0 == intval($post_author) ) {
2541 $post_author = get_userdatabylogin($post_author);
2542 if ( empty($post_author) )
2544 if ( empty($post_author->ID) )
2546 $post_author = $post_author->ID;
2549 if ( '' == $author_query )
2550 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
2552 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
2554 if ( '' != $author_query )
2555 $author_query = " AND ($author_query)";
2560 $where = "$exclusions $inclusions ";
2561 if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
2562 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
2564 // meta_key and meta_value might be slashed
2565 $meta_key = stripslashes($meta_key);
2566 $meta_value = stripslashes($meta_value);
2567 if ( ! empty( $meta_key ) )
2568 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
2569 if ( ! empty( $meta_value ) )
2570 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
2575 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
2577 $query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
2578 $query .= $author_query;
2579 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
2581 if ( !empty($number) )
2582 $query .= ' LIMIT ' . $offset . ',' . $number;
2584 $pages = $wpdb->get_results($query);
2586 if ( empty($pages) ) {
2587 $pages = apply_filters('get_pages', array(), $r);
2591 // Sanitize before caching so it'll only get done once
2592 $num_pages = count($pages);
2593 for ($i = 0; $i < $num_pages; $i++) {
2594 $pages[$i] = sanitize_post($pages[$i], 'raw');
2598 update_page_cache($pages);
2600 if ( $child_of || $hierarchical )
2601 $pages = & get_page_children($child_of, $pages);
2603 if ( !empty($exclude_tree) ) {
2604 $exclude = (int) $exclude_tree;
2605 $children = get_page_children($exclude, $pages);
2606 $excludes = array();
2607 foreach ( $children as $child )
2608 $excludes[] = $child->ID;
2609 $excludes[] = $exclude;
2610 $num_pages = count($pages);
2611 for ( $i = 0; $i < $num_pages; $i++ ) {
2612 if ( in_array($pages[$i]->ID, $excludes) )
2617 $cache[ $key ] = $pages;
2618 wp_cache_set( 'get_pages', $cache, 'posts' );
2620 $pages = apply_filters('get_pages', $pages, $r);
2626 // Attachment functions
2630 * Check if the attachment URI is local one and is really an attachment.
2634 * @param string $url URL to check
2635 * @return bool True on success, false on failure.
2637 function is_local_attachment($url) {
2638 if (strpos($url, get_bloginfo('url')) === false)
2640 if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
2642 if ( $id = url_to_postid($url) ) {
2643 $post = & get_post($id);
2644 if ( 'attachment' == $post->post_type )
2651 * Insert an attachment.
2653 * If you set the 'ID' in the $object parameter, it will mean that you are
2654 * updating and attempt to update the attachment. You can also set the
2655 * attachment name or title by setting the key 'post_name' or 'post_title'.
2657 * You can set the dates for the attachment manually by setting the 'post_date'
2658 * and 'post_date_gmt' keys' values.
2660 * By default, the comments will use the default settings for whether the
2661 * comments are allowed. You can close them manually or keep them open by
2662 * setting the value for the 'comment_status' key.
2664 * The $object parameter can have the following:
2665 * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
2666 * 'post_type' - Default is 'post', will be set to attachment. Can not override.
2667 * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
2668 * 'ping_status' - Default is the value in default ping status option. Whether the attachment
2670 * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
2672 * 'menu_order' - Default is 0. The order it is displayed.
2673 * 'to_ping' - Whether to ping.
2674 * 'pinged' - Default is empty string.
2675 * 'post_password' - Default is empty string. The password to access the attachment.
2676 * 'guid' - Global Unique ID for referencing the attachment.
2677 * 'post_content_filtered' - Attachment post content filtered.
2678 * 'post_excerpt' - Attachment excerpt.
2683 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
2684 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
2686 * @param string|array $object Arguments to override defaults.
2687 * @param string $file Optional filename.
2688 * @param int $post_parent Parent post ID.
2689 * @return int Attachment ID.
2691 function wp_insert_attachment($object, $file = false, $parent = 0) {
2692 global $wpdb, $user_ID;
2694 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
2695 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2696 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
2697 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
2699 $object = wp_parse_args($object, $defaults);
2700 if ( !empty($parent) )
2701 $object['post_parent'] = $parent;
2703 $object = sanitize_post($object, 'db');
2705 // export array as variables
2706 extract($object, EXTR_SKIP);
2708 // Make sure we set a valid category
2709 if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
2710 $post_category = array(get_option('default_category'));
2713 if ( empty($post_author) )
2714 $post_author = $user_ID;
2716 $post_type = 'attachment';
2717 $post_status = 'inherit';
2719 // Are we updating or creating?
2720 if ( !empty($ID) ) {
2722 $post_ID = (int) $ID;
2728 // Create a valid post name.
2729 if ( empty($post_name) )
2730 $post_name = sanitize_title($post_title);
2732 $post_name = sanitize_title($post_name);
2734 // expected_slashed ($post_name)
2735 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2737 if ( empty($post_date) )
2738 $post_date = current_time('mysql');
2739 if ( empty($post_date_gmt) )
2740 $post_date_gmt = current_time('mysql', 1);
2742 if ( empty($post_modified) )
2743 $post_modified = $post_date;
2744 if ( empty($post_modified_gmt) )
2745 $post_modified_gmt = $post_date_gmt;
2747 if ( empty($comment_status) ) {
2749 $comment_status = 'closed';
2751 $comment_status = get_option('default_comment_status');
2753 if ( empty($ping_status) )
2754 $ping_status = get_option('default_ping_status');
2756 if ( isset($to_ping) )
2757 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
2761 if ( isset($post_parent) )
2762 $post_parent = (int) $post_parent;
2766 if ( isset($menu_order) )
2767 $menu_order = (int) $menu_order;
2771 if ( !isset($post_password) )
2772 $post_password = '';
2774 if ( ! isset($pinged) )
2777 // expected_slashed (everything!)
2778 $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' ) );
2779 $data = stripslashes_deep( $data );
2782 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
2784 // If there is a suggested ID, use it if not already present
2785 if ( !empty($import_id) ) {
2786 $import_id = (int) $import_id;
2787 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2788 $data['ID'] = $import_id;
2792 $wpdb->insert( $wpdb->posts, $data );
2793 $post_ID = (int) $wpdb->insert_id;
2796 if ( empty($post_name) ) {
2797 $post_name = sanitize_title($post_title, $post_ID);
2798 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
2801 wp_set_post_categories($post_ID, $post_category);
2804 update_attached_file( $post_ID, $file );
2806 clean_post_cache($post_ID);
2808 if ( isset($post_parent) && $post_parent < 0 )
2809 add_post_meta($post_ID, '_wp_attachment_temp_parent', $post_parent, true);
2812 do_action('edit_attachment', $post_ID);
2814 do_action('add_attachment', $post_ID);
2821 * Delete an attachment.
2823 * Will remove the file also, when the attachment is removed. Removes all post
2824 * meta fields, taxonomy, comments, etc associated with the attachment (except
2829 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
2831 * @param int $postid Attachment ID.
2832 * @param bool $force_delete Whether to bypass trash and force deletion
2833 * @return mixed False on failure. Post data on success.
2835 function wp_delete_attachment( $post_id, $force_delete = false ) {
2838 if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
2841 if ( 'attachment' != $post->post_type )
2844 if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
2845 return wp_trash_post( $post_id );
2847 delete_post_meta($post_id, '_wp_trash_meta_status');
2848 delete_post_meta($post_id, '_wp_trash_meta_time');
2850 $meta = wp_get_attachment_metadata( $post_id );
2851 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
2852 $file = get_attached_file( $post_id );
2854 do_action('delete_attachment', $post_id);
2856 wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
2857 wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
2859 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND meta_value = %d", $post_id ));
2861 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
2862 if ( ! empty($comment_ids) ) {
2863 do_action( 'delete_comment', $comment_ids );
2864 $in_comment_ids = "'" . implode("', '", $comment_ids) . "'";
2865 $wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_ID IN($in_comment_ids)" );
2866 do_action( 'deleted_comment', $comment_ids );
2869 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
2870 if ( !empty($post_meta_ids) ) {
2871 do_action( 'delete_postmeta', $post_meta_ids );
2872 $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
2873 $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
2874 do_action( 'deleted_postmeta', $post_meta_ids );
2877 do_action( 'delete_post', $post_id );
2878 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $post_id ));
2879 do_action( 'deleted_post', $post_id );
2881 $uploadpath = wp_upload_dir();
2883 if ( ! empty($meta['thumb']) ) {
2884 // Don't delete the thumb if another attachment uses it
2885 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)) ) {
2886 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
2887 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
2888 @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
2892 // remove intermediate and backup images if there are any
2893 $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
2894 foreach ( $sizes as $size ) {
2895 if ( $intermediate = image_get_intermediate_size($post_id, $size) ) {
2896 $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
2897 @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
2901 if ( is_array($backup_sizes) ) {
2902 foreach ( $backup_sizes as $size ) {
2903 $del_file = path_join( dirname($meta['file']), $size['file'] );
2904 $del_file = apply_filters('wp_delete_file', $del_file);
2905 @ unlink( path_join($uploadpath['basedir'], $del_file) );
2909 $file = apply_filters('wp_delete_file', $file);
2911 if ( ! empty($file) )
2914 clean_post_cache($post_id);
2920 * Retrieve attachment meta field for attachment ID.
2924 * @param int $post_id Attachment ID
2925 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
2926 * @return string|bool Attachment meta field. False on failure.
2928 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
2929 $post_id = (int) $post_id;
2930 if ( !$post =& get_post( $post_id ) )
2933 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
2938 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
2942 * Update metadata for an attachment.
2946 * @param int $post_id Attachment ID.
2947 * @param array $data Attachment data.
2950 function wp_update_attachment_metadata( $post_id, $data ) {
2951 $post_id = (int) $post_id;
2952 if ( !$post =& get_post( $post_id ) )
2955 $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
2957 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
2961 * Retrieve the URL for an attachment.
2965 * @param int $post_id Attachment ID.
2968 function wp_get_attachment_url( $post_id = 0 ) {
2969 $post_id = (int) $post_id;
2970 if ( !$post =& get_post( $post_id ) )
2974 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
2975 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
2976 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
2977 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
2978 elseif ( false !== strpos($file, 'wp-content/uploads') )
2979 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
2981 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
2985 if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this.
2986 $url = get_the_guid( $post->ID );
2988 if ( 'attachment' != $post->post_type || empty($url) )
2991 return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
2995 * Retrieve thumbnail for an attachment.
2999 * @param int $post_id Attachment ID.
3000 * @return mixed False on failure. Thumbnail file path on success.
3002 function wp_get_attachment_thumb_file( $post_id = 0 ) {
3003 $post_id = (int) $post_id;
3004 if ( !$post =& get_post( $post_id ) )
3006 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
3009 $file = get_attached_file( $post->ID );
3011 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
3012 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
3017 * Retrieve URL for an attachment thumbnail.
3021 * @param int $post_id Attachment ID
3022 * @return string|bool False on failure. Thumbnail URL on success.
3024 function wp_get_attachment_thumb_url( $post_id = 0 ) {
3025 $post_id = (int) $post_id;
3026 if ( !$post =& get_post( $post_id ) )
3028 if ( !$url = wp_get_attachment_url( $post->ID ) )
3031 $sized = image_downsize( $post_id, 'thumbnail' );
3035 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
3038 $url = str_replace(basename($url), basename($thumb), $url);
3040 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
3044 * Check if the attachment is an image.
3048 * @param int $post_id Attachment ID
3051 function wp_attachment_is_image( $post_id = 0 ) {
3052 $post_id = (int) $post_id;
3053 if ( !$post =& get_post( $post_id ) )
3056 if ( !$file = get_attached_file( $post->ID ) )
3059 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
3061 $image_exts = array('jpg', 'jpeg', 'gif', 'png');
3063 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
3069 * Retrieve the icon for a MIME type.
3073 * @param string $mime MIME type
3074 * @return string|bool
3076 function wp_mime_type_icon( $mime = 0 ) {
3077 if ( !is_numeric($mime) )
3078 $icon = wp_cache_get("mime_type_icon_$mime");
3079 if ( empty($icon) ) {
3081 $post_mimes = array();
3082 if ( is_numeric($mime) ) {
3083 $mime = (int) $mime;
3084 if ( $post =& get_post( $mime ) ) {
3085 $post_id = (int) $post->ID;
3086 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
3087 if ( !empty($ext) ) {
3088 $post_mimes[] = $ext;
3089 if ( $ext_type = wp_ext2type( $ext ) )
3090 $post_mimes[] = $ext_type;
3092 $mime = $post->post_mime_type;
3097 $post_mimes[] = $mime;
3100 $icon_files = wp_cache_get('icon_files');
3102 if ( !is_array($icon_files) ) {
3103 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
3104 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
3105 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
3106 $icon_files = array();
3108 $dir = array_shift($keys = array_keys($dirs));
3109 $uri = array_shift($dirs);
3110 if ( $dh = opendir($dir) ) {
3111 while ( false !== $file = readdir($dh) ) {
3112 $file = basename($file);
3113 if ( substr($file, 0, 1) == '.' )
3115 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
3116 if ( is_dir("$dir/$file") )
3117 $dirs["$dir/$file"] = "$uri/$file";
3120 $icon_files["$dir/$file"] = "$uri/$file";
3125 wp_cache_set('icon_files', $icon_files, 600);
3128 // Icon basename - extension = MIME wildcard
3129 foreach ( $icon_files as $file => $uri )
3130 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
3132 if ( ! empty($mime) ) {
3133 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
3134 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
3135 $post_mimes[] = str_replace('/', '_', $mime);
3138 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
3139 $matches['default'] = array('default');
3141 foreach ( $matches as $match => $wilds ) {
3142 if ( isset($types[$wilds[0]])) {
3143 $icon = $types[$wilds[0]];
3144 if ( !is_numeric($mime) )
3145 wp_cache_set("mime_type_icon_$mime", $icon);
3151 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
3155 * Checked for changed slugs for published posts and save old slug.
3157 * The function is used along with form POST data. It checks for the wp-old-slug
3158 * POST field. Will only be concerned with published posts and the slug actually
3161 * If the slug was changed and not already part of the old slugs then it will be
3162 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
3165 * The most logically usage of this function is redirecting changed posts, so
3166 * that those that linked to an changed post will be redirected to the new post.
3170 * @param int $post_id Post ID.
3171 * @return int Same as $post_id
3173 function wp_check_for_changed_slugs($post_id) {
3174 if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
3177 $post = &get_post($post_id);
3179 // we're only concerned with published posts
3180 if ( $post->post_status != 'publish' || $post->post_type != 'post' )
3183 // only bother if the slug has changed
3184 if ( $post->post_name == $_POST['wp-old-slug'] )
3187 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
3189 // if we haven't added this old slug before, add it now
3190 if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
3191 add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
3193 // if the new slug was used previously, delete it from the list
3194 if ( in_array($post->post_name, $old_slugs) )
3195 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
3201 * Retrieve the private post SQL based on capability.
3203 * This function provides a standardized way to appropriately select on the
3204 * post_status of posts/pages. The function will return a piece of SQL code that
3205 * can be added to a WHERE clause; this SQL is constructed to allow all
3206 * published posts, and all private posts to which the user has access.
3208 * It also allows plugins that define their own post type to control the cap by
3209 * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
3210 * the capability the user must have to read the private post type.
3215 * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
3217 * @param string $post_type currently only supports 'post' or 'page'.
3218 * @return string SQL code that can be added to a where clause.
3220 function get_private_posts_cap_sql($post_type) {
3225 if ($post_type == 'post') {
3226 $cap = 'read_private_posts';
3228 } elseif ($post_type == 'page') {
3229 $cap = 'read_private_pages';
3230 // Dunno what it is, maybe plugins have their own post type?
3232 $cap = apply_filters('pub_priv_sql_capability', $cap);
3235 // We don't know what it is, filters don't change anything,
3236 // so set the SQL up to return nothing.
3241 $sql = '(post_status = \'publish\'';
3243 if (current_user_can($cap)) {
3244 // Does the user have the capability to view private posts? Guess so.
3245 $sql .= ' OR post_status = \'private\'';
3246 } elseif (is_user_logged_in()) {
3247 // Users can view their own private posts.
3248 $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
3257 * Retrieve the date the the last post was published.
3259 * The server timezone is the default and is the difference between GMT and
3260 * server time. The 'blog' value is the date when the last post was posted. The
3261 * 'gmt' is when the last post was posted in GMT formatted date.
3267 * @uses apply_filters() Calls 'get_lastpostdate' filter
3269 * @global mixed $cache_lastpostdate Stores the last post date
3270 * @global mixed $pagenow The current page being viewed
3272 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
3273 * @return string The date of the last post.
3275 function get_lastpostdate($timezone = 'server') {
3276 global $cache_lastpostdate, $wpdb, $blog_id;
3277 $add_seconds_server = date('Z');
3278 if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
3279 switch(strtolower($timezone)) {
3281 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
3284 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
3287 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
3290 $cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
3292 $lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
3294 return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
3298 * Retrieve last post modified date depending on timezone.
3300 * The server timezone is the default and is the difference between GMT and
3301 * server time. The 'blog' value is just when the last post was modified. The
3302 * 'gmt' is when the last post was modified in GMT time.
3307 * @uses apply_filters() Calls 'get_lastpostmodified' filter
3309 * @global mixed $cache_lastpostmodified Stores the date the last post was modified
3311 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
3312 * @return string The date the post was last modified.
3314 function get_lastpostmodified($timezone = 'server') {
3315 global $cache_lastpostmodified, $wpdb, $blog_id;
3316 $add_seconds_server = date('Z');
3317 if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
3318 switch(strtolower($timezone)) {
3320 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3323 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3326 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3329 $lastpostdate = get_lastpostdate($timezone);
3330 if ( $lastpostdate > $lastpostmodified ) {
3331 $lastpostmodified = $lastpostdate;
3333 $cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
3335 $lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
3337 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
3341 * Updates posts in cache.
3343 * @usedby update_page_cache() Aliased by this function.
3345 * @package WordPress
3349 * @param array $posts Array of post objects
3351 function update_post_cache(&$posts) {
3355 foreach ( $posts as $post )
3356 wp_cache_add($post->ID, $post, 'posts');
3360 * Will clean the post in the cache.
3362 * Cleaning means delete from the cache of the post. Will call to clean the term
3363 * object cache associated with the post ID.
3365 * clean_post_cache() will call itself recursively for each child post.
3367 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
3368 * wp_suspend_cache_invalidation().
3370 * @package WordPress
3374 * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
3376 * @param int $id The Post ID in the cache to clean
3378 function clean_post_cache($id) {
3379 global $_wp_suspend_cache_invalidation, $wpdb;
3381 if ( !empty($_wp_suspend_cache_invalidation) )
3386 wp_cache_delete($id, 'posts');
3387 wp_cache_delete($id, 'post_meta');
3389 clean_object_term_cache($id, 'post');
3391 wp_cache_delete( 'wp_get_archives', 'general' );
3393 do_action('clean_post_cache', $id);
3395 if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
3396 foreach( $children as $cid )
3397 clean_post_cache( $cid );
3402 * Alias of update_post_cache().
3404 * @see update_post_cache() Posts and pages are the same, alias is intentional
3406 * @package WordPress
3410 * @param array $pages list of page objects
3412 function update_page_cache(&$pages) {
3413 update_post_cache($pages);
3417 * Will clean the page in the cache.
3419 * Clean (read: delete) page from cache that matches $id. Will also clean cache
3420 * associated with 'all_page_ids' and 'get_pages'.
3422 * @package WordPress
3426 * @uses do_action() Will call the 'clean_page_cache' hook action.
3428 * @param int $id Page ID to clean
3430 function clean_page_cache($id) {
3431 clean_post_cache($id);
3433 wp_cache_delete( 'all_page_ids', 'posts' );
3434 wp_cache_delete( 'get_pages', 'posts' );
3436 do_action('clean_page_cache', $id);
3440 * Call major cache updating functions for list of Post objects.
3442 * @package WordPress
3447 * @uses update_post_cache()
3448 * @uses update_object_term_cache()
3449 * @uses update_postmeta_cache()
3451 * @param array $posts Array of Post objects
3453 function update_post_caches(&$posts) {
3454 // No point in doing all this work if we didn't match any posts.
3458 update_post_cache($posts);
3460 $post_ids = array();
3462 for ($i = 0; $i < count($posts); $i++)
3463 $post_ids[] = $posts[$i]->ID;
3465 update_object_term_cache($post_ids, 'post');
3467 update_postmeta_cache($post_ids);
3471 * Updates metadata cache for list of post IDs.
3473 * Performs SQL query to retrieve the metadata for the post IDs and updates the
3474 * metadata cache for the posts. Therefore, the functions, which call this
3475 * function, do not need to perform SQL queries on their own.
3477 * @package WordPress
3483 * @param array $post_ids List of post IDs.
3484 * @return bool|array Returns false if there is nothing to update or an array of metadata.
3486 function update_postmeta_cache($post_ids) {
3487 return update_meta_cache('post', $post_ids);
3495 * Hook for managing future post transitions to published.
3500 * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
3501 * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
3503 * @param string $new_status New post status
3504 * @param string $old_status Previous post status
3505 * @param object $post Object type containing the post information
3507 function _transition_post_status($new_status, $old_status, $post) {
3510 if ( $old_status != 'publish' && $new_status == 'publish' ) {
3511 // Reset GUID if transitioning to publish and it is empty
3512 if ( '' == get_the_guid($post->ID) )
3513 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
3514 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
3517 // Always clears the hook in case the post status bounced from future to draft.
3518 wp_clear_scheduled_hook('publish_future_post', $post->ID);
3522 * Hook used to schedule publication for a post marked for the future.
3524 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
3529 * @param int $deprecated Not Used. Can be set to null.
3530 * @param object $post Object type containing the post information
3532 function _future_post_hook($deprecated = '', $post) {
3533 wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
3534 wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
3538 * Hook to schedule pings and enclosures when a post is published.
3543 * @uses XMLRPC_REQUEST and APP_REQUEST constants.
3544 * @uses do_action() Calls 'xmlprc_publish_post' on post ID if XMLRPC_REQUEST is defined.
3545 * @uses do_action() Calls 'app_publish_post' on post ID if APP_REQUEST is defined.
3547 * @param int $post_id The ID in the database table of the post being published
3549 function _publish_post_hook($post_id) {
3552 if ( defined('XMLRPC_REQUEST') )
3553 do_action('xmlrpc_publish_post', $post_id);
3554 if ( defined('APP_REQUEST') )
3555 do_action('app_publish_post', $post_id);
3557 if ( defined('WP_IMPORTING') )
3560 $data = array( 'post_id' => $post_id, 'meta_value' => '1' );
3561 if ( get_option('default_pingback_flag') ) {
3562 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
3563 do_action( 'added_postmeta', $wpdb->insert_id, $post_id, '_pingme', 1 );
3565 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
3566 do_action( 'added_postmeta', $wpdb->insert_id, $post_id, '_encloseme', 1 );
3568 wp_schedule_single_event(time(), 'do_pings');
3572 * Hook used to prevent page/post cache and rewrite rules from staying dirty.
3574 * Does two things. If the post is a page and has a template then it will
3575 * update/add that template to the meta. For both pages and posts, it will clean
3576 * the post cache to make sure that the cache updates to the changes done
3577 * recently. For pages, the rewrite rules of WordPress are flushed to allow for
3580 * The $post parameter, only uses 'post_type' property and 'page_template'
3585 * @uses $wp_rewrite Flushes Rewrite Rules.
3587 * @param int $post_id The ID in the database table for the $post
3588 * @param object $post Object type containing the post information
3590 function _save_post_hook($post_id, $post) {
3591 if ( $post->post_type == 'page' ) {
3592 clean_page_cache($post_id);
3593 // Avoid flushing rules for every post during import.
3594 if ( !defined('WP_IMPORTING') ) {
3596 $wp_rewrite->flush_rules(false);
3599 clean_post_cache($post_id);
3604 * Retrieve post ancestors and append to post ancestors property.
3606 * Will only retrieve ancestors once, if property is already set, then nothing
3607 * will be done. If there is not a parent post, or post ID and post parent ID
3608 * are the same then nothing will be done.
3610 * The parameter is passed by reference, so nothing needs to be returned. The
3611 * property will be updated and can be referenced after the function is
3612 * complete. The post parent will be an ancestor and the parent of the post
3613 * parent will be an ancestor. There will only be two ancestors at the most.
3619 * @param object $_post Post data.
3620 * @return null When nothing needs to be done.
3622 function _get_post_ancestors(&$_post) {
3625 if ( isset($_post->ancestors) )
3628 $_post->ancestors = array();
3630 if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
3633 $id = $_post->ancestors[] = $_post->post_parent;
3634 while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
3635 if ( $id == $ancestor )
3637 $id = $_post->ancestors[] = $ancestor;
3642 * Determines which fields of posts are to be saved in revisions.
3644 * Does two things. If passed a post *array*, it will return a post array ready
3645 * to be insterted into the posts table as a post revision. Otherwise, returns
3646 * an array whose keys are the post fields to be saved for post revisions.
3648 * @package WordPress
3649 * @subpackage Post_Revisions
3652 * @uses apply_filters() Calls '_wp_post_revision_fields' on 'title', 'content' and 'excerpt' fields.
3654 * @param array $post Optional a post array to be processed for insertion as a post revision.
3655 * @param bool $autosave optional Is the revision an autosave?
3656 * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
3658 function _wp_post_revision_fields( $post = null, $autosave = false ) {
3659 static $fields = false;
3662 // Allow these to be versioned
3664 'post_title' => __( 'Title' ),
3665 'post_content' => __( 'Content' ),
3666 'post_excerpt' => __( 'Excerpt' ),
3670 $fields = apply_filters( '_wp_post_revision_fields', $fields );
3672 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
3673 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
3674 unset( $fields[$protect] );
3677 if ( !is_array($post) )
3681 foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
3682 $return[$field] = $post[$field];
3684 $return['post_parent'] = $post['ID'];
3685 $return['post_status'] = 'inherit';
3686 $return['post_type'] = 'revision';
3687 $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
3688 $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
3689 $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
3695 * Saves an already existing post as a post revision.
3697 * Typically used immediately prior to post updates.
3699 * @package WordPress
3700 * @subpackage Post_Revisions
3703 * @uses _wp_put_post_revision()
3705 * @param int $post_id The ID of the post to save as a revision.
3706 * @return mixed Null or 0 if error, new revision ID, if success.
3708 function wp_save_post_revision( $post_id ) {
3709 // We do autosaves manually with wp_create_post_autosave()
3710 if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
3713 // WP_POST_REVISIONS = 0, false
3714 if ( !constant('WP_POST_REVISIONS') )
3717 if ( !$post = get_post( $post_id, ARRAY_A ) )
3720 if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
3723 $return = _wp_put_post_revision( $post );
3725 // WP_POST_REVISIONS = true (default), -1
3726 if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
3729 // all revisions and (possibly) one autosave
3730 $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
3732 // WP_POST_REVISIONS = (int) (# of autasaves to save)
3733 $delete = count($revisions) - WP_POST_REVISIONS;
3738 $revisions = array_slice( $revisions, 0, $delete );
3740 for ( $i = 0; isset($revisions[$i]); $i++ ) {
3741 if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
3743 wp_delete_post_revision( $revisions[$i]->ID );
3750 * Retrieve the autosaved data of the specified post.
3752 * Returns a post object containing the information that was autosaved for the
3755 * @package WordPress
3756 * @subpackage Post_Revisions
3759 * @param int $post_id The post ID.
3760 * @return object|bool The autosaved data or false on failure or when no autosave exists.
3762 function wp_get_post_autosave( $post_id ) {
3764 if ( !$post = get_post( $post_id ) )
3768 'name' => "{$post->ID}-autosave",
3769 'post_parent' => $post->ID,
3770 'post_type' => 'revision',
3771 'post_status' => 'inherit'
3774 // Use WP_Query so that the result gets cached
3775 $autosave_query = new WP_Query;
3777 add_action( 'parse_query', '_wp_get_post_autosave_hack' );
3778 $autosave = $autosave_query->query( $q );
3779 remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
3781 if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
3782 return $autosave[0];
3788 * Internally used to hack WP_Query into submission.
3790 * @package WordPress
3791 * @subpackage Post_Revisions
3794 * @param object $query WP_Query object
3796 function _wp_get_post_autosave_hack( $query ) {
3797 $query->is_single = false;
3801 * Determines if the specified post is a revision.
3803 * @package WordPress
3804 * @subpackage Post_Revisions
3807 * @param int|object $post Post ID or post object.
3808 * @return bool|int False if not a revision, ID of revision's parent otherwise.
3810 function wp_is_post_revision( $post ) {
3811 if ( !$post = wp_get_post_revision( $post ) )
3813 return (int) $post->post_parent;
3817 * Determines if the specified post is an autosave.
3819 * @package WordPress
3820 * @subpackage Post_Revisions
3823 * @param int|object $post Post ID or post object.
3824 * @return bool|int False if not a revision, ID of autosave's parent otherwise
3826 function wp_is_post_autosave( $post ) {
3827 if ( !$post = wp_get_post_revision( $post ) )
3829 if ( "{$post->post_parent}-autosave" !== $post->post_name )
3831 return (int) $post->post_parent;
3835 * Inserts post data into the posts table as a post revision.
3837 * @package WordPress
3838 * @subpackage Post_Revisions
3841 * @uses wp_insert_post()
3843 * @param int|object|array $post Post ID, post object OR post array.
3844 * @param bool $autosave Optional. Is the revision an autosave?
3845 * @return mixed Null or 0 if error, new revision ID if success.
3847 function _wp_put_post_revision( $post = null, $autosave = false ) {
3848 if ( is_object($post) )
3849 $post = get_object_vars( $post );
3850 elseif ( !is_array($post) )
3851 $post = get_post($post, ARRAY_A);
3852 if ( !$post || empty($post['ID']) )
3855 if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
3856 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
3858 $post = _wp_post_revision_fields( $post, $autosave );
3859 $post = add_magic_quotes($post); //since data is from db
3861 $revision_id = wp_insert_post( $post );
3862 if ( is_wp_error($revision_id) )
3863 return $revision_id;
3866 do_action( '_wp_put_post_revision', $revision_id );
3867 return $revision_id;
3871 * Gets a post revision.
3873 * @package WordPress
3874 * @subpackage Post_Revisions
3879 * @param int|object $post Post ID or post object
3880 * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
3881 * @param string $filter Optional sanitation filter. @see sanitize_post()
3882 * @return mixed Null if error or post object if success
3884 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
3886 if ( !$revision = get_post( $post, OBJECT, $filter ) )
3888 if ( 'revision' !== $revision->post_type )
3891 if ( $output == OBJECT ) {
3893 } elseif ( $output == ARRAY_A ) {
3894 $_revision = get_object_vars($revision);
3896 } elseif ( $output == ARRAY_N ) {
3897 $_revision = array_values(get_object_vars($revision));
3905 * Restores a post to the specified revision.
3907 * Can restore a past revision using all fields of the post revision, or only selected fields.
3909 * @package WordPress
3910 * @subpackage Post_Revisions
3913 * @uses wp_get_post_revision()
3914 * @uses wp_update_post()
3915 * @uses do_action() Calls 'wp_restore_post_revision' on post ID and revision ID if wp_update_post()
3918 * @param int|object $revision_id Revision ID or revision object.
3919 * @param array $fields Optional. What fields to restore from. Defaults to all.
3920 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3922 function wp_restore_post_revision( $revision_id, $fields = null ) {
3923 if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
3926 if ( !is_array( $fields ) )
3927 $fields = array_keys( _wp_post_revision_fields() );
3930 foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
3931 $update[$field] = $revision[$field];
3936 $update['ID'] = $revision['post_parent'];
3938 $update = add_magic_quotes( $update ); //since data is from db
3940 $post_id = wp_update_post( $update );
3941 if ( is_wp_error( $post_id ) )
3945 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
3951 * Deletes a revision.
3953 * Deletes the row from the posts table corresponding to the specified revision.
3955 * @package WordPress
3956 * @subpackage Post_Revisions
3959 * @uses wp_get_post_revision()
3960 * @uses wp_delete_post()
3962 * @param int|object $revision_id Revision ID or revision object.
3963 * @param array $fields Optional. What fields to restore from. Defaults to all.
3964 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3966 function wp_delete_post_revision( $revision_id ) {
3967 if ( !$revision = wp_get_post_revision( $revision_id ) )
3970 $delete = wp_delete_post( $revision->ID );
3971 if ( is_wp_error( $delete ) )
3975 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
3981 * Returns all revisions of specified post.
3983 * @package WordPress
3984 * @subpackage Post_Revisions
3987 * @uses get_children()
3989 * @param int|object $post_id Post ID or post object
3990 * @return array empty if no revisions
3992 function wp_get_post_revisions( $post_id = 0, $args = null ) {
3993 if ( !constant('WP_POST_REVISIONS') )
3995 if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
3998 $defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
3999 $args = wp_parse_args( $args, $defaults );
4000 $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
4002 if ( !$revisions = get_children( $args ) )
4007 function _set_preview($post) {
4009 if ( ! is_object($post) )
4012 $preview = wp_get_post_autosave($post->ID);
4014 if ( ! is_object($preview) )
4017 $preview = sanitize_post($preview);
4019 $post->post_content = $preview->post_content;
4020 $post->post_title = $preview->post_title;
4021 $post->post_excerpt = $preview->post_excerpt;
4026 function _show_post_preview() {
4028 if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
4029 $id = (int) $_GET['preview_id'];
4031 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
4032 wp_die( __('You do not have permission to preview drafts.') );
4034 add_filter('the_preview', '_set_preview');