3 * Post functions and post utility function.
11 * Retrieve attached file path based on attachment ID.
13 * You can optionally send it through the 'get_attached_file' filter, but by
14 * default it will just return the file path unfiltered.
16 * The function works by getting the single post meta name, named
17 * '_wp_attached_file' and returning it. This is a convenience function to
18 * prevent looking up the meta name and provide a mechanism for sending the
19 * attached filename through a filter.
22 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
24 * @param int $attachment_id Attachment ID.
25 * @param bool $unfiltered Whether to apply filters or not.
26 * @return string The file path to the attached file.
28 function get_attached_file( $attachment_id, $unfiltered = false ) {
29 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
30 // If the file is relative, prepend upload dir
31 if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
32 $file = $uploads['basedir'] . "/$file";
35 return apply_filters( 'get_attached_file', $file, $attachment_id );
39 * Update attachment file path based on attachment ID.
41 * Used to update the file path of the attachment, which uses post meta name
42 * '_wp_attached_file' to store the path of the attachment.
45 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
47 * @param int $attachment_id Attachment ID
48 * @param string $file File path for the attachment
49 * @return bool False on failure, true on success.
51 function update_attached_file( $attachment_id, $file ) {
52 if ( !get_post( $attachment_id ) )
55 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
57 // Make the file path relative to the upload dir
58 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { // Get upload directory
59 if ( 0 === strpos($file, $uploads['basedir']) ) {// Check that the upload base exists in the file path
60 $file = str_replace($uploads['basedir'], '', $file); // Remove upload dir from the file path
61 $file = ltrim($file, '/');
65 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
69 * Retrieve all children of the post parent ID.
71 * Normally, without any enhancements, the children would apply to pages. In the
72 * context of the inner workings of WordPress, pages, posts, and attachments
73 * share the same table, so therefore the functionality could apply to any one
74 * of them. It is then noted that while this function does not work on posts, it
75 * does not mean that it won't work on posts. It is recommended that you know
76 * what context you wish to retrieve the children of.
78 * Attachments may also be made the child of a post, so if that is an accurate
79 * statement (which needs to be verified), it would then be possible to get
80 * all of the attachments for a post. Attachments have since changed since
81 * version 2.5, so this is most likely unaccurate, but serves generally as an
82 * example of what is possible.
84 * The arguments listed as defaults are for this function and also of the
85 * {@link get_posts()} function. The arguments are combined with the
86 * get_children defaults and are then passed to the {@link get_posts()}
87 * function, which accepts additional arguments. You can replace the defaults in
88 * this function, listed below and the additional arguments listed in the
89 * {@link get_posts()} function.
91 * The 'post_parent' is the most important argument and important attention
92 * needs to be paid to the $args parameter. If you pass either an object or an
93 * integer (number), then just the 'post_parent' is grabbed and everything else
94 * is lost. If you don't specify any arguments, then it is assumed that you are
95 * in The Loop and the post parent will be grabbed for from the current post.
97 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
98 * is the amount of posts to retrieve that has a default of '-1', which is
99 * used to get all of the posts. Giving a number higher than 0 will only
100 * retrieve that amount of posts.
102 * The 'post_type' and 'post_status' arguments can be used to choose what
103 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
104 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
105 * argument will accept any post status within the write administration panels.
107 * @see get_posts() Has additional arguments that can be replaced.
108 * @internal Claims made in the long description might be inaccurate.
112 * @param mixed $args Optional. User defined arguments for replacing the defaults.
113 * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
114 * @return array|bool False on failure and the type will be determined by $output parameter.
116 function &get_children($args = '', $output = OBJECT) {
117 if ( empty( $args ) ) {
118 if ( isset( $GLOBALS['post'] ) ) {
119 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
123 } elseif ( is_object( $args ) ) {
124 $args = array('post_parent' => (int) $args->post_parent );
125 } elseif ( is_numeric( $args ) ) {
126 $args = array('post_parent' => (int) $args);
130 'numberposts' => -1, 'post_type' => 'any',
131 'post_status' => 'any', 'post_parent' => 0,
134 $r = wp_parse_args( $args, $defaults );
136 $children = get_posts( $r );
142 update_post_cache($children);
144 foreach ( $children as $key => $child )
145 $kids[$child->ID] =& $children[$key];
147 if ( $output == OBJECT ) {
149 } elseif ( $output == ARRAY_A ) {
150 foreach ( (array) $kids as $kid )
151 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
153 } elseif ( $output == ARRAY_N ) {
154 foreach ( (array) $kids as $kid )
155 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
163 * Get extended entry info (<!--more-->).
165 * There should not be any space after the second dash and before the word
166 * 'more'. There can be text or space(s) after the word 'more', but won't be
169 * The returned array has 'main' and 'extended' keys. Main has the text before
170 * the <code><!--more--></code>. The 'extended' key has the content after the
171 * <code><!--more--></code> comment.
175 * @param string $post Post content.
176 * @return array Post before ('main') and after ('extended').
178 function get_extended($post) {
179 //Match the new style more links
180 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
181 list($main, $extended) = explode($matches[0], $post, 2);
187 // Strip leading and trailing whitespace
188 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
189 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
191 return array('main' => $main, 'extended' => $extended);
195 * Retrieves post data given a post ID or post object.
197 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
198 * $post, must be given as a variable, since it is passed by reference.
202 * @link http://codex.wordpress.org/Function_Reference/get_post
204 * @param int|object $post Post ID or post object.
205 * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
206 * @param string $filter Optional, default is raw.
207 * @return mixed Post data
209 function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
213 if ( empty($post) ) {
214 if ( isset($GLOBALS['post']) )
215 $_post = & $GLOBALS['post'];
218 } elseif ( is_object($post) && empty($post->filter) ) {
219 _get_post_ancestors($post);
220 wp_cache_add($post->ID, $post, 'posts');
223 if ( is_object($post) )
226 if ( ! $_post = wp_cache_get($post, 'posts') ) {
227 $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post));
230 _get_post_ancestors($_post);
231 wp_cache_add($_post->ID, $_post, 'posts');
235 $_post = sanitize_post($_post, $filter);
237 if ( $output == OBJECT ) {
239 } elseif ( $output == ARRAY_A ) {
240 $__post = get_object_vars($_post);
242 } elseif ( $output == ARRAY_N ) {
243 $__post = array_values(get_object_vars($_post));
251 * Retrieve ancestors of a post.
255 * @param int|object $post Post ID or post object
256 * @return array Ancestor IDs or empty array if none are found.
258 function get_post_ancestors($post) {
259 $post = get_post($post);
261 if ( !empty($post->ancestors) )
262 return $post->ancestors;
268 * Retrieve data from a post field based on Post ID.
270 * Examples of the post field will be, 'post_type', 'post_status', 'content',
271 * etc and based off of the post object property or key names.
273 * The context values are based off of the taxonomy filter functions and
274 * supported values are found within those functions.
277 * @uses sanitize_post_field() See for possible $context values.
279 * @param string $field Post field name
280 * @param id $post Post ID
281 * @param string $context Optional. How to filter the field. Default is display.
282 * @return WP_Error|string Value in post field or WP_Error on failure
284 function get_post_field( $field, $post, $context = 'display' ) {
286 $post = get_post( $post );
288 if ( is_wp_error($post) )
291 if ( !is_object($post) )
294 if ( !isset($post->$field) )
297 return sanitize_post_field($field, $post->$field, $post->ID, $context);
301 * Retrieve the mime type of an attachment based on the ID.
303 * This function can be used with any post type, but it makes more sense with
308 * @param int $ID Optional. Post ID.
309 * @return bool|string False on failure or returns the mime type
311 function get_post_mime_type($ID = '') {
312 $post = & get_post($ID);
314 if ( is_object($post) )
315 return $post->post_mime_type;
321 * Retrieve the post status based on the Post ID.
323 * If the post ID is of an attachment, then the parent post status will be given
328 * @param int $ID Post ID
329 * @return string|bool Post status or false on failure.
331 function get_post_status($ID = '') {
332 $post = get_post($ID);
334 if ( is_object($post) ) {
335 if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
336 return get_post_status($post->post_parent);
338 return $post->post_status;
345 * Retrieve all of the WordPress supported post statuses.
347 * Posts have a limited set of valid status values, this provides the
348 * post_status values and descriptions.
352 * @return array List of post statuses.
354 function get_post_statuses( ) {
356 'draft' => __('Draft'),
357 'pending' => __('Pending Review'),
358 'private' => __('Private'),
359 'publish' => __('Published')
366 * Retrieve all of the WordPress support page statuses.
368 * Pages have a limited set of valid status values, this provides the
369 * post_status values and descriptions.
373 * @return array List of page statuses.
375 function get_page_statuses( ) {
377 'draft' => __('Draft'),
378 'private' => __('Private'),
379 'publish' => __('Published')
386 * Retrieve the post type of the current post or of a given post.
391 * @uses $posts The Loop post global
393 * @param mixed $post Optional. Post object or post ID.
394 * @return bool|string post type or false on failure.
396 function get_post_type($post = false) {
399 if ( false === $post )
401 elseif ( (int) $post )
402 $post = get_post($post, OBJECT);
404 if ( is_object($post) )
405 return $post->post_type;
411 * Updates the post type for the post ID.
413 * The page or post cache will be cleaned for the post ID.
419 * @param int $post_id Post ID to change post type. Not actually optional.
420 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to name a few.
421 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
423 function set_post_type( $post_id = 0, $post_type = 'post' ) {
426 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
427 $return = $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_type = %s WHERE ID = %d", $post_type, $post_id) );
429 if ( 'page' == $post_type )
430 clean_page_cache($post_id);
432 clean_post_cache($post_id);
438 * Retrieve list of latest posts or posts matching criteria.
440 * The defaults are as follows:
441 * 'numberposts' - Default is 5. Total number of posts to retrieve.
442 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
443 * 'category' - What category to pull the posts from.
444 * 'orderby' - Default is 'post_date'. How to order the posts.
445 * 'order' - Default is 'DESC'. The order to retrieve the posts.
446 * 'include' - See {@link WP_Query::query()} for more.
447 * 'exclude' - See {@link WP_Query::query()} for more.
448 * 'meta_key' - See {@link WP_Query::query()} for more.
449 * 'meta_value' - See {@link WP_Query::query()} for more.
450 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
451 * 'post_parent' - The parent of the post or post type.
452 * 'post_status' - Default is 'published'. Post status to retrieve.
456 * @uses WP_Query::query() See for more default arguments and information.
457 * @link http://codex.wordpress.org/Template_Tags/get_posts
459 * @param array $args Optional. Override defaults.
460 * @return array List of posts.
462 function get_posts($args = null) {
464 'numberposts' => 5, 'offset' => 0,
465 'category' => 0, 'orderby' => 'post_date',
466 'order' => 'DESC', 'include' => '',
467 'exclude' => '', 'meta_key' => '',
468 'meta_value' =>'', 'post_type' => 'post',
469 'suppress_filters' => true
472 $r = wp_parse_args( $args, $defaults );
473 if ( empty( $r['post_status'] ) )
474 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
475 if ( ! empty($r['numberposts']) )
476 $r['posts_per_page'] = $r['numberposts'];
477 if ( ! empty($r['category']) )
478 $r['cat'] = $r['category'];
479 if ( ! empty($r['include']) ) {
480 $incposts = preg_split('/[\s,]+/',$r['include']);
481 $r['posts_per_page'] = count($incposts); // only the number of posts included
482 $r['post__in'] = $incposts;
483 } elseif ( ! empty($r['exclude']) )
484 $r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
486 $r['caller_get_posts'] = true;
488 $get_posts = new WP_Query;
489 return $get_posts->query($r);
494 // Post meta functions
498 * Add meta data field to a post.
500 * Post meta data is called "Custom Fields" on the Administration Panels.
504 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
506 * @param int $post_id Post ID.
507 * @param string $key Metadata name.
508 * @param mixed $value Metadata value.
509 * @param bool $unique Optional, default is false. Whether the same key should not be added.
510 * @return bool False for failure. True for success.
512 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
515 // make sure meta is added to the post, not a revision
516 if ( $the_post = wp_is_post_revision($post_id) )
517 $post_id = $the_post;
519 // expected_slashed ($meta_key)
520 $meta_key = stripslashes($meta_key);
522 if ( $unique && $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) )
525 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
527 $wpdb->insert( $wpdb->postmeta, compact( 'post_id', 'meta_key', 'meta_value' ) );
529 wp_cache_delete($post_id, 'post_meta');
535 * Remove metadata matching criteria from a post.
537 * You can match based on the key, or key and value. Removing based on key and
538 * value, will keep from removing duplicate metadata with the same key. It also
539 * allows removing all metadata matching key, if needed.
543 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
545 * @param int $post_id post ID
546 * @param string $meta_key Metadata name.
547 * @param mixed $meta_value Optional. Metadata value.
548 * @return bool False for failure. True for success.
550 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
553 // make sure meta is added to the post, not a revision
554 if ( $the_post = wp_is_post_revision($post_id) )
555 $post_id = $the_post;
557 // expected_slashed ($meta_key, $meta_value)
558 $meta_key = stripslashes( $meta_key );
559 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
561 if ( empty( $meta_value ) )
562 $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
564 $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) );
569 if ( empty( $meta_value ) )
570 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
572 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) );
574 wp_cache_delete($post_id, 'post_meta');
580 * Retrieve post meta field for a post.
584 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
586 * @param int $post_id Post ID.
587 * @param string $key The meta key to retrieve.
588 * @param bool $single Whether to return a single value.
589 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true.
591 function get_post_meta($post_id, $key, $single = false) {
592 $post_id = (int) $post_id;
594 $meta_cache = wp_cache_get($post_id, 'post_meta');
596 if ( !$meta_cache ) {
597 update_postmeta_cache($post_id);
598 $meta_cache = wp_cache_get($post_id, 'post_meta');
601 if ( isset($meta_cache[$key]) ) {
603 return maybe_unserialize( $meta_cache[$key][0] );
605 return array_map('maybe_unserialize', $meta_cache[$key]);
613 * Update post meta field based on post ID.
615 * Use the $prev_value parameter to differentiate between meta fields with the
616 * same key and post ID.
618 * If the meta field for the post does not exist, it will be added.
622 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
624 * @param int $post_id Post ID.
625 * @param string $key Metadata key.
626 * @param mixed $value Metadata value.
627 * @param mixed $prev_value Optional. Previous value to check before removing.
628 * @return bool False on failure, true if success.
630 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
633 // make sure meta is added to the post, not a revision
634 if ( $the_post = wp_is_post_revision($post_id) )
635 $post_id = $the_post;
637 // expected_slashed ($meta_key)
638 $meta_key = stripslashes($meta_key);
640 if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) {
641 return add_post_meta($post_id, $meta_key, $meta_value);
644 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
646 $data = compact( 'meta_value' );
647 $where = compact( 'meta_key', 'post_id' );
649 if ( !empty( $prev_value ) ) {
650 $prev_value = maybe_serialize($prev_value);
651 $where['meta_value'] = $prev_value;
654 $wpdb->update( $wpdb->postmeta, $data, $where );
655 wp_cache_delete($post_id, 'post_meta');
660 * Delete everything from post meta matching meta key.
665 * @param string $post_meta_key Key to search for when deleting.
666 * @return bool Whether the post meta key was deleted from the database
668 function delete_post_meta_by_key($post_meta_key) {
670 if ( $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key)) ) {
671 /** @todo Get post_ids and delete cache */
672 // wp_cache_delete($post_id, 'post_meta');
679 * Retrieve post meta fields, based on post ID.
681 * The post meta fields are retrieved from the cache, so the function is
682 * optimized to be called more than once. It also applies to the functions, that
686 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
688 * @uses $id Current Loop Post ID
690 * @param int $post_id post ID
693 function get_post_custom($post_id = 0) {
697 $post_id = (int) $id;
699 $post_id = (int) $post_id;
701 if ( ! wp_cache_get($post_id, 'post_meta') )
702 update_postmeta_cache($post_id);
704 return wp_cache_get($post_id, 'post_meta');
708 * Retrieve meta field names for a post.
710 * If there are no meta fields, then nothing (null) will be returned.
713 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
715 * @param int $post_id post ID
716 * @return array|null Either array of the keys, or null if keys could not be retrieved.
718 function get_post_custom_keys( $post_id = 0 ) {
719 $custom = get_post_custom( $post_id );
721 if ( !is_array($custom) )
724 if ( $keys = array_keys($custom) )
729 * Retrieve values for a custom post field.
731 * The parameters must not be considered optional. All of the post meta fields
732 * will be retrieved and only the meta field key values returned.
735 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
737 * @param string $key Meta field key.
738 * @param int $post_id Post ID
739 * @return array Meta field values.
741 function get_post_custom_values( $key = '', $post_id = 0 ) {
742 $custom = get_post_custom($post_id);
744 return isset($custom[$key]) ? $custom[$key] : null;
748 * Check if post is sticky.
750 * Sticky posts should remain at the top of The Loop. If the post ID is not
751 * given, then The Loop ID for the current post will be used.
755 * @param int $post_id Optional. Post ID.
756 * @return bool Whether post is sticky (true) or not sticky (false).
758 function is_sticky($post_id = null) {
761 $post_id = absint($post_id);
764 $post_id = absint($id);
766 $stickies = get_option('sticky_posts');
768 if ( !is_array($stickies) )
771 if ( in_array($post_id, $stickies) )
778 * Sanitize every post field.
780 * If the context is 'raw', then the post object or array will just be returned.
783 * @uses sanitize_post_field() Used to sanitize the fields.
785 * @param object|array $post The Post Object or Array
786 * @param string $context Optional, default is 'display'. How to sanitize post fields.
787 * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
789 function sanitize_post($post, $context = 'display') {
790 if ( 'raw' == $context )
792 if ( is_object($post) ) {
793 if ( !isset($post->ID) )
795 foreach ( array_keys(get_object_vars($post)) as $field )
796 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
797 $post->filter = $context;
799 if ( !isset($post['ID']) )
801 foreach ( array_keys($post) as $field )
802 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
803 $post['filter'] = $context;
810 * Sanitize post field based on context.
812 * Possible context values are: raw, edit, db, attribute, js, and display. The
813 * display context is used by default.
817 * @param string $field The Post Object field name.
818 * @param mixed $value The Post Object value.
819 * @param int $post_id Post ID.
820 * @param string $context How to sanitize post fields.
821 * @return mixed Sanitized value.
823 function sanitize_post_field($field, $value, $post_id, $context) {
824 $int_fields = array('ID', 'post_parent', 'menu_order');
825 if ( in_array($field, $int_fields) )
826 $value = (int) $value;
828 if ( 'raw' == $context )
832 if ( false !== strpos($field, 'post_') ) {
834 $field_no_prefix = str_replace('post_', '', $field);
837 if ( 'edit' == $context ) {
838 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
841 $value = apply_filters("edit_$field", $value, $post_id);
843 $value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
845 $value = apply_filters("edit_post_$field", $value, $post_id);
848 if ( in_array($field, $format_to_edit) ) {
849 if ( 'post_content' == $field )
850 $value = format_to_edit($value, user_can_richedit());
852 $value = format_to_edit($value);
854 $value = attribute_escape($value);
856 } else if ( 'db' == $context ) {
858 $value = apply_filters("pre_$field", $value);
859 $value = apply_filters("${field_no_prefix}_save_pre", $value);
861 $value = apply_filters("pre_post_$field", $value);
862 $value = apply_filters("${field}_pre", $value);
865 // Use display filters by default.
867 $value = apply_filters($field, $value, $post_id, $context);
869 $value = apply_filters("post_$field", $value, $post_id, $context);
872 if ( 'attribute' == $context )
873 $value = attribute_escape($value);
874 else if ( 'js' == $context )
875 $value = js_escape($value);
881 * Make a post sticky.
883 * Sticky posts should be displayed at the top of the front page.
887 * @param int $post_id Post ID.
889 function stick_post($post_id) {
890 $stickies = get_option('sticky_posts');
892 if ( !is_array($stickies) )
893 $stickies = array($post_id);
895 if ( ! in_array($post_id, $stickies) )
896 $stickies[] = $post_id;
898 update_option('sticky_posts', $stickies);
904 * Sticky posts should be displayed at the top of the front page.
908 * @param int $post_id Post ID.
910 function unstick_post($post_id) {
911 $stickies = get_option('sticky_posts');
913 if ( !is_array($stickies) )
916 if ( ! in_array($post_id, $stickies) )
919 $offset = array_search($post_id, $stickies);
920 if ( false === $offset )
923 array_splice($stickies, $offset, 1);
925 update_option('sticky_posts', $stickies);
929 * Count number of posts of a post type and is user has permissions to view.
931 * This function provides an efficient method of finding the amount of post's
932 * type a blog has. Another method is to count the amount of items in
933 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
934 * when developing for 2.5+, use this function instead.
936 * The $perm parameter checks for 'readable' value and if the user can read
937 * private posts, it will display that for the user that is signed in.
940 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
942 * @param string $type Optional. Post type to retrieve count
943 * @param string $perm Optional. 'readable' or empty.
944 * @return object Number of posts for each status
946 function wp_count_posts( $type = 'post', $perm = '' ) {
949 $user = wp_get_current_user();
953 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
954 if ( 'readable' == $perm && is_user_logged_in() ) {
955 if ( !current_user_can("read_private_{$type}s") ) {
956 $cache_key .= '_' . $perm . '_' . $user->ID;
957 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
960 $query .= ' GROUP BY post_status';
962 $count = wp_cache_get($cache_key, 'counts');
963 if ( false !== $count )
966 $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
969 foreach( (array) $count as $row_num => $row ) {
970 $stats[$row['post_status']] = $row['num_posts'];
973 $stats = (object) $stats;
974 wp_cache_set($cache_key, $stats, 'counts');
981 * Count number of attachments for the mime type(s).
983 * If you set the optional mime_type parameter, then an array will still be
984 * returned, but will only have the item you are looking for. It does not give
985 * you the number of attachments that are children of a post. You can get that
986 * by counting the number of children that post has.
990 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
991 * @return array Number of posts for each mime type.
993 function wp_count_attachments( $mime_type = '' ) {
996 $and = wp_post_mime_type_where( $mime_type );
997 $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' $and GROUP BY post_mime_type", ARRAY_A );
1000 foreach( (array) $count as $row ) {
1001 $stats[$row['post_mime_type']] = $row['num_posts'];
1004 return (object) $stats;
1008 * Check a MIME-Type against a list.
1010 * If the wildcard_mime_types parameter is a string, it must be comma separated
1011 * list. If the real_mime_types is a string, it is also comma separated to
1016 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or flash (same as *flash*)
1017 * @param string|array $real_mime_types post_mime_type values
1018 * @return array array(wildcard=>array(real types))
1020 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
1022 if ( is_string($wildcard_mime_types) )
1023 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
1024 if ( is_string($real_mime_types) )
1025 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
1026 $wild = '[-._a-z0-9]*';
1027 foreach ( (array) $wildcard_mime_types as $type ) {
1028 $type = str_replace('*', $wild, $type);
1029 $patternses[1][$type] = "^$type$";
1030 if ( false === strpos($type, '/') ) {
1031 $patternses[2][$type] = "^$type/";
1032 $patternses[3][$type] = $type;
1036 foreach ( $patternses as $patterns )
1037 foreach ( $patterns as $type => $pattern )
1038 foreach ( (array) $real_mime_types as $real )
1039 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
1040 $matches[$type][] = $real;
1045 * Convert MIME types into SQL.
1049 * @param string|array $mime_types List of mime types or comma separated string of mime types.
1050 * @return string The SQL AND clause for mime searching.
1052 function wp_post_mime_type_where($post_mime_types) {
1054 $wildcards = array('', '%', '%/%');
1055 if ( is_string($post_mime_types) )
1056 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
1057 foreach ( (array) $post_mime_types as $mime_type ) {
1058 $mime_type = preg_replace('/\s/', '', $mime_type);
1059 $slashpos = strpos($mime_type, '/');
1060 if ( false !== $slashpos ) {
1061 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
1062 $mime_subgroup = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
1063 if ( empty($mime_subgroup) )
1064 $mime_subgroup = '*';
1066 $mime_subgroup = str_replace('/', '', $mime_subgroup);
1067 $mime_pattern = "$mime_group/$mime_subgroup";
1069 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
1070 if ( false === strpos($mime_pattern, '*') )
1071 $mime_pattern .= '/*';
1074 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
1076 if ( in_array( $mime_type, $wildcards ) )
1079 if ( false !== strpos($mime_pattern, '%') )
1080 $wheres[] = "post_mime_type LIKE '$mime_pattern'";
1082 $wheres[] = "post_mime_type = '$mime_pattern'";
1084 if ( !empty($wheres) )
1085 $where = ' AND (' . join(' OR ', $wheres) . ') ';
1090 * Removes a post, attachment, or page.
1092 * When the post and page goes, everything that is tied to it is deleted also.
1093 * This includes comments, post meta fields, and terms associated with the post.
1096 * @uses do_action() Calls 'deleted_post' hook on post ID.
1098 * @param int $postid Post ID.
1101 function wp_delete_post($postid = 0) {
1102 global $wpdb, $wp_rewrite;
1104 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
1107 if ( 'attachment' == $post->post_type )
1108 return wp_delete_attachment($postid);
1110 do_action('delete_post', $postid);
1112 /** @todo delete for pluggable post taxonomies too */
1113 wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
1115 $parent_data = array( 'post_parent' => $post->post_parent );
1116 $parent_where = array( 'post_parent' => $postid );
1118 if ( 'page' == $post->post_type) {
1119 // if the page is defined in option page_on_front or post_for_posts,
1120 // adjust the corresponding options
1121 if ( get_option('page_on_front') == $postid ) {
1122 update_option('show_on_front', 'posts');
1123 delete_option('page_on_front');
1125 if ( get_option('page_for_posts') == $postid ) {
1126 delete_option('page_for_posts');
1129 // Point children of this page to its parent, also clean the cache of affected children
1130 $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
1131 $children = $wpdb->get_results($children_query);
1133 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
1136 // Do raw query. wp_get_post_revisions() is filtered
1137 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
1138 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
1139 foreach ( $revision_ids as $revision_id )
1140 wp_delete_post_revision( $revision_id );
1142 // Point all attachments to this post up one level
1143 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
1145 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
1147 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
1149 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d", $postid ));
1151 if ( 'page' == $post->post_type ) {
1152 clean_page_cache($postid);
1154 foreach ( (array) $children as $child )
1155 clean_page_cache($child->ID);
1157 $wp_rewrite->flush_rules();
1159 clean_post_cache($postid);
1162 do_action('deleted_post', $postid);
1168 * Retrieve the list of categories for a post.
1170 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
1171 * away from the complexity of the taxonomy layer.
1175 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
1177 * @param int $post_id Optional. The Post ID.
1178 * @param array $args Optional. Overwrite the defaults.
1181 function wp_get_post_categories( $post_id = 0, $args = array() ) {
1182 $post_id = (int) $post_id;
1184 $defaults = array('fields' => 'ids');
1185 $args = wp_parse_args( $args, $defaults );
1187 $cats = wp_get_object_terms($post_id, 'category', $args);
1192 * Retrieve the tags for a post.
1194 * There is only one default for this function, called 'fields' and by default
1195 * is set to 'all'. There are other defaults that can be override in
1196 * {@link wp_get_object_terms()}.
1198 * @package WordPress
1202 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1204 * @param int $post_id Optional. The Post ID
1205 * @param array $args Optional. Overwrite the defaults
1206 * @return array List of post tags.
1208 function wp_get_post_tags( $post_id = 0, $args = array() ) {
1209 $post_id = (int) $post_id;
1211 $defaults = array('fields' => 'all');
1212 $args = wp_parse_args( $args, $defaults );
1214 $tags = wp_get_object_terms($post_id, 'post_tag', $args);
1220 * Retrieve number of recent posts.
1225 * @param int $num Optional, default is 10. Number of posts to get.
1226 * @return array List of posts.
1228 function wp_get_recent_posts($num = 10) {
1231 // Set the limit clause, if we got a limit
1234 $limit = "LIMIT $num";
1237 $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit";
1238 $result = $wpdb->get_results($sql,ARRAY_A);
1240 return $result ? $result : array();
1244 * Retrieve a single post, based on post ID.
1246 * Has categories in 'post_category' property or key. Has tags in 'tags_input'
1251 * @param int $postid Post ID.
1252 * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
1253 * @return object|array Post object or array holding post contents and information
1255 function wp_get_single_post($postid = 0, $mode = OBJECT) {
1256 $postid = (int) $postid;
1258 $post = get_post($postid, $mode);
1260 // Set categories and tags
1261 if($mode == OBJECT) {
1262 $post->post_category = wp_get_post_categories($postid);
1263 $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
1266 $post['post_category'] = wp_get_post_categories($postid);
1267 $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
1276 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
1278 * You can set the post date manually, but setting the values for 'post_date'
1279 * and 'post_date_gmt' keys. You can close the comments or open the comments by
1280 * setting the value for 'comment_status' key.
1282 * The defaults for the parameter $postarr are:
1283 * 'post_status' - Default is 'draft'.
1284 * 'post_type' - Default is 'post'.
1285 * 'post_author' - Default is current user ID. The ID of the user, who added
1287 * 'ping_status' - Default is the value in default ping status option.
1288 * Whether the attachment can accept pings.
1289 * 'post_parent' - Default is 0. Set this for the post it belongs to, if
1291 * 'menu_order' - Default is 0. The order it is displayed.
1292 * 'to_ping' - Whether to ping.
1293 * 'pinged' - Default is empty string.
1294 * 'post_password' - Default is empty string. The password to access the
1296 * 'guid' - Global Unique ID for referencing the attachment.
1297 * 'post_content_filtered' - Post content filtered.
1298 * 'post_excerpt' - Post excerpt.
1305 * @param array $postarr Optional. Override defaults.
1306 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
1307 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
1309 function wp_insert_post($postarr = array(), $wp_error = false) {
1310 global $wpdb, $wp_rewrite, $user_ID;
1312 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
1313 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
1314 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
1315 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
1317 $postarr = wp_parse_args($postarr, $defaults);
1318 $postarr = sanitize_post($postarr, 'db');
1320 // export array as variables
1321 extract($postarr, EXTR_SKIP);
1323 // Are we updating or creating?
1325 if ( !empty($ID) ) {
1327 $previous_status = get_post_field('post_status', $ID);
1329 $previous_status = 'new';
1332 if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) ) {
1334 return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
1339 // Make sure we set a valid category
1340 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
1341 $post_category = array(get_option('default_category'));
1344 //Set the default tag list
1345 if ( !isset($tags_input) )
1346 $tags_input = array();
1348 if ( empty($post_author) )
1349 $post_author = $user_ID;
1351 if ( empty($post_status) )
1352 $post_status = 'draft';
1354 if ( empty($post_type) )
1355 $post_type = 'post';
1359 // Get the post ID and GUID
1361 $post_ID = (int) $ID;
1362 $guid = get_post_field( 'guid', $post_ID );
1365 // Don't allow contributors to set to set the post slug for pending review posts
1366 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
1369 // Create a valid post name. Drafts and pending posts are allowed to have an empty
1371 if ( empty($post_name) ) {
1372 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1373 $post_name = sanitize_title($post_title);
1375 $post_name = sanitize_title($post_name);
1378 // 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
1379 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
1380 $post_date = current_time('mysql');
1382 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
1383 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1384 $post_date_gmt = get_gmt_from_date($post_date);
1386 $post_date_gmt = '0000-00-00 00:00:00';
1389 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
1390 $post_modified = current_time( 'mysql' );
1391 $post_modified_gmt = current_time( 'mysql', 1 );
1393 $post_modified = $post_date;
1394 $post_modified_gmt = $post_date_gmt;
1397 if ( 'publish' == $post_status ) {
1398 $now = gmdate('Y-m-d H:i:59');
1399 if ( mysql2date('U', $post_date_gmt) > mysql2date('U', $now) )
1400 $post_status = 'future';
1403 if ( empty($comment_status) ) {
1405 $comment_status = 'closed';
1407 $comment_status = get_option('default_comment_status');
1409 if ( empty($ping_status) )
1410 $ping_status = get_option('default_ping_status');
1412 if ( isset($to_ping) )
1413 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
1417 if ( ! isset($pinged) )
1420 if ( isset($post_parent) )
1421 $post_parent = (int) $post_parent;
1425 if ( !empty($post_ID) ) {
1426 if ( $post_parent == $post_ID ) {
1427 // Post can't be its own parent
1429 } elseif ( !empty($post_parent) ) {
1430 $parent_post = get_post($post_parent);
1431 // Check for circular dependency
1432 if ( $parent_post->post_parent == $post_ID )
1437 if ( isset($menu_order) )
1438 $menu_order = (int) $menu_order;
1442 if ( !isset($post_password) || 'private' == $post_status )
1443 $post_password = '';
1445 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) ) {
1446 $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d AND post_parent = %d LIMIT 1", $post_name, $post_type, $post_ID, $post_parent));
1448 if ($post_name_check || in_array($post_name, $wp_rewrite->feeds) ) {
1451 $alt_post_name = substr($post_name, 0, 200-(strlen($suffix)+1)). "-$suffix";
1452 $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d AND post_parent = %d LIMIT 1", $alt_post_name, $post_type, $post_ID, $post_parent));
1454 } while ($post_name_check);
1455 $post_name = $alt_post_name;
1459 // expected_slashed (everything!)
1460 $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' ) );
1461 $data = apply_filters('wp_insert_post_data', $data, $postarr);
1462 $data = stripslashes_deep( $data );
1463 $where = array( 'ID' => $post_ID );
1466 do_action( 'pre_post_update', $post_ID );
1467 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
1469 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
1474 if ( isset($post_mime_type) )
1475 $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
1476 // If there is a suggested ID, use it if not already present
1477 if ( !empty($import_id) ) {
1478 $import_id = (int) $import_id;
1479 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
1480 $data['ID'] = $import_id;
1483 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
1485 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
1489 $post_ID = (int) $wpdb->insert_id;
1491 // use the newly generated $post_ID
1492 $where = array( 'ID' => $post_ID );
1495 if ( empty($post_name) && !in_array( $post_status, array( 'draft', 'pending' ) ) ) {
1496 $post_name = sanitize_title($post_title, $post_ID);
1497 $wpdb->update( $wpdb->posts, compact( 'post_name' ), $where );
1500 wp_set_post_categories( $post_ID, $post_category );
1501 wp_set_post_tags( $post_ID, $tags_input );
1503 $current_guid = get_post_field( 'guid', $post_ID );
1505 if ( 'page' == $post_type )
1506 clean_page_cache($post_ID);
1508 clean_post_cache($post_ID);
1511 if ( !$update && '' == $current_guid )
1512 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
1514 $post = get_post($post_ID);
1516 if ( !empty($page_template) && 'page' == $post_type ) {
1517 $post->page_template = $page_template;
1518 $page_templates = get_page_templates();
1519 if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
1521 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
1525 update_post_meta($post_ID, '_wp_page_template', $page_template);
1528 wp_transition_post_status($post_status, $previous_status, $post);
1531 do_action('edit_post', $post_ID, $post);
1533 do_action('save_post', $post_ID, $post);
1534 do_action('wp_insert_post', $post_ID, $post);
1540 * Update a post with new post data.
1542 * The date does not have to be set for drafts. You can set the date and it will
1543 * not be overridden.
1547 * @param array|object $postarr Post data.
1548 * @return int 0 on failure, Post ID on success.
1550 function wp_update_post($postarr = array()) {
1551 if ( is_object($postarr) )
1552 $postarr = get_object_vars($postarr);
1554 // First, get all of the original fields
1555 $post = wp_get_single_post($postarr['ID'], ARRAY_A);
1557 // Escape data pulled from DB.
1558 $post = add_magic_quotes($post);
1560 // Passed post category list overwrites existing category list if not empty.
1561 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
1562 && 0 != count($postarr['post_category']) )
1563 $post_cats = $postarr['post_category'];
1565 $post_cats = $post['post_category'];
1567 // Drafts shouldn't be assigned a date unless explicitly done so by the user
1568 if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
1569 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
1572 $clear_date = false;
1574 // Merge old and new fields with new fields overwriting old ones.
1575 $postarr = array_merge($post, $postarr);
1576 $postarr['post_category'] = $post_cats;
1577 if ( $clear_date ) {
1578 $postarr['post_date'] = current_time('mysql');
1579 $postarr['post_date_gmt'] = '';
1582 if ($postarr['post_type'] == 'attachment')
1583 return wp_insert_attachment($postarr);
1585 return wp_insert_post($postarr);
1589 * Publish a post by transitioning the post status.
1593 * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
1595 * @param int $post_id Post ID.
1598 function wp_publish_post($post_id) {
1601 $post = get_post($post_id);
1606 if ( 'publish' == $post->post_status )
1609 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
1611 $old_status = $post->post_status;
1612 $post->post_status = 'publish';
1613 wp_transition_post_status('publish', $old_status, $post);
1615 // Update counts for the post's terms.
1616 foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
1617 $tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
1618 wp_update_term_count($tt_ids, $taxonomy);
1621 do_action('edit_post', $post_id, $post);
1622 do_action('save_post', $post_id, $post);
1623 do_action('wp_insert_post', $post_id, $post);
1627 * Publish future post and make sure post ID has future post status.
1629 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
1630 * from publishing drafts, etc.
1634 * @param int $post_id Post ID.
1635 * @return null Nothing is returned. Which can mean that no action is required or post was published.
1637 function check_and_publish_future_post($post_id) {
1639 $post = get_post($post_id);
1644 if ( 'future' != $post->post_status )
1647 $time = strtotime( $post->post_date_gmt . ' GMT' );
1649 if ( $time > time() ) { // Uh oh, someone jumped the gun!
1650 wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
1651 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
1655 return wp_publish_post($post_id);
1659 * Adds tags to a post.
1661 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
1663 * @package WordPress
1667 * @param int $post_id Post ID
1668 * @param string $tags The tags to set for the post, separated by commas.
1669 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1671 function wp_add_post_tags($post_id = 0, $tags = '') {
1672 return wp_set_post_tags($post_id, $tags, true);
1677 * Set the tags for a post.
1680 * @uses wp_set_object_terms() Sets the tags for the post.
1682 * @param int $post_id Post ID.
1683 * @param string $tags The tags to set for the post, separated by commas.
1684 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
1685 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1687 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
1689 $post_id = (int) $post_id;
1696 $tags = (is_array($tags)) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
1697 wp_set_object_terms($post_id, $tags, 'post_tag', $append);
1701 * Set categories for a post.
1703 * If the post categories parameter is not set, then the default category is
1708 * @param int $post_ID Post ID.
1709 * @param array $post_categories Optional. List of categories.
1710 * @return bool|mixed
1712 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
1713 $post_ID = (int) $post_ID;
1714 // If $post_categories isn't already an array, make it one:
1715 if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
1716 $post_categories = array(get_option('default_category'));
1717 else if ( 1 == count($post_categories) && '' == $post_categories[0] )
1720 $post_categories = array_map('intval', $post_categories);
1721 $post_categories = array_unique($post_categories);
1723 return wp_set_object_terms($post_ID, $post_categories, 'category');
1727 * Transition the post status of a post.
1729 * Calls hooks to transition post status. If the new post status is not the same
1730 * as the previous post status, then two hooks will be ran, the first is
1731 * 'transition_post_status' with new status, old status, and post data. The
1732 * next action called is 'OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
1733 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
1736 * The final action will run whether or not the post statuses are the same. The
1737 * action is named 'NEWSTATUS_POSTTYPE', NEWSTATUS is from the $new_status
1738 * parameter and POSTTYPE is post_type post data.
1742 * @param string $new_status Transition to this post status.
1743 * @param string $old_status Previous post status.
1744 * @param object $post Post data.
1746 function wp_transition_post_status($new_status, $old_status, $post) {
1747 if ( $new_status != $old_status ) {
1748 do_action('transition_post_status', $new_status, $old_status, $post);
1749 do_action("${old_status}_to_$new_status", $post);
1751 do_action("${new_status}_$post->post_type", $post->ID, $post);
1755 // Trackback and ping functions
1759 * Add a URL to those already pung.
1764 * @param int $post_id Post ID.
1765 * @param string $uri Ping URI.
1766 * @return int How many rows were updated.
1768 function add_ping($post_id, $uri) {
1770 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
1771 $pung = trim($pung);
1772 $pung = preg_split('/\s/', $pung);
1774 $new = implode("\n", $pung);
1775 $new = apply_filters('add_ping', $new);
1776 // expected_slashed ($new)
1777 $new = stripslashes($new);
1778 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
1782 * Retrieve enclosures already enclosed for a post.
1787 * @param int $post_id Post ID.
1788 * @return array List of enclosures
1790 function get_enclosed($post_id) {
1791 $custom_fields = get_post_custom( $post_id );
1793 if ( !is_array( $custom_fields ) )
1796 foreach ( $custom_fields as $key => $val ) {
1797 if ( 'enclosure' != $key || !is_array( $val ) )
1799 foreach( $val as $enc ) {
1800 $enclosure = split( "\n", $enc );
1801 $pung[] = trim( $enclosure[ 0 ] );
1804 $pung = apply_filters('get_enclosed', $pung);
1809 * Retrieve URLs already pinged for a post.
1814 * @param int $post_id Post ID.
1817 function get_pung($post_id) {
1819 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
1820 $pung = trim($pung);
1821 $pung = preg_split('/\s/', $pung);
1822 $pung = apply_filters('get_pung', $pung);
1827 * Retrieve URLs that need to be pinged.
1832 * @param int $post_id Post ID
1835 function get_to_ping($post_id) {
1837 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
1838 $to_ping = trim($to_ping);
1839 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
1840 $to_ping = apply_filters('get_to_ping', $to_ping);
1845 * Do trackbacks for a list of URLs.
1849 * @param string $tb_list Comma separated list of URLs
1850 * @param int $post_id Post ID
1852 function trackback_url_list($tb_list, $post_id) {
1853 if ( ! empty( $tb_list ) ) {
1855 $postdata = wp_get_single_post($post_id, ARRAY_A);
1857 // import postdata as variables
1858 extract($postdata, EXTR_SKIP);
1861 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
1863 if (strlen($excerpt) > 255) {
1864 $excerpt = substr($excerpt,0,252) . '...';
1867 $trackback_urls = explode(',', $tb_list);
1868 foreach( (array) $trackback_urls as $tb_url) {
1869 $tb_url = trim($tb_url);
1870 trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
1880 * Get a list of page IDs.
1885 * @return array List of page IDs.
1887 function get_all_page_ids() {
1890 if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
1891 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
1892 wp_cache_add('all_page_ids', $page_ids, 'posts');
1899 * Retrieves page data given a page ID or page object.
1903 * @param mixed $page Page object or page ID. Passed by reference.
1904 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
1905 * @param string $filter How the return value should be filtered.
1906 * @return mixed Page data.
1908 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
1909 if ( empty($page) ) {
1910 if ( isset( $GLOBALS['page'] ) && isset( $GLOBALS['page']->ID ) ) {
1911 return get_post($GLOBALS['page'], $output, $filter);
1918 $the_page = get_post($page, $output, $filter);
1923 * Retrieves a page given its path.
1928 * @param string $page_path Page path
1929 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
1930 * @return mixed Null when complete.
1932 function get_page_by_path($page_path, $output = OBJECT) {
1934 $page_path = rawurlencode(urldecode($page_path));
1935 $page_path = str_replace('%2F', '/', $page_path);
1936 $page_path = str_replace('%20', ' ', $page_path);
1937 $page_paths = '/' . trim($page_path, '/');
1938 $leaf_path = sanitize_title(basename($page_paths));
1939 $page_paths = explode('/', $page_paths);
1941 foreach( (array) $page_paths as $pathdir)
1942 $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
1944 $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 ));
1946 if ( empty($pages) )
1949 foreach ($pages as $page) {
1950 $path = '/' . $leaf_path;
1952 while ($curpage->post_parent != 0) {
1953 $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 ));
1954 $path = '/' . $curpage->post_name . $path;
1957 if ( $path == $full_path )
1958 return get_page($page->ID, $output);
1965 * Retrieve a page given its title.
1970 * @param string $page_title Page title
1971 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
1974 function get_page_by_title($page_title, $output = OBJECT) {
1976 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
1978 return get_page($page, $output);
1984 * Retrieve child pages from list of pages matching page ID.
1986 * Matches against the pages parameter against the page ID. Also matches all
1987 * children for the same to retrieve all children of a page. Does not make any
1988 * SQL queries to get the children.
1992 * @param int $page_id Page ID.
1993 * @param array $pages List of pages' objects.
1996 function &get_page_children($page_id, $pages) {
1997 $page_list = array();
1998 foreach ( (array) $pages as $page ) {
1999 if ( $page->post_parent == $page_id ) {
2000 $page_list[] = $page;
2001 if ( $children = get_page_children($page->ID, $pages) )
2002 $page_list = array_merge($page_list, $children);
2009 * Order the pages with children under parents in a flat list.
2011 * Fetches the pages returned as a FLAT list, but arranged in order of their
2012 * hierarchy, i.e., child parents immediately follow their parents.
2016 * @param array $posts Posts array.
2017 * @param int $parent Parent page ID.
2020 function get_page_hierarchy($posts, $parent = 0) {
2021 $result = array ( );
2022 if ($posts) { foreach ( (array) $posts as $post) {
2023 if ($post->post_parent == $parent) {
2024 $result[$post->ID] = $post->post_name;
2025 $children = get_page_hierarchy($posts, $post->ID);
2026 $result += $children; //append $children to $result
2033 * Builds URI for a page.
2035 * Sub pages will be in the "directory" under the parent page post name.
2039 * @param int $page_id Page ID.
2040 * @return string Page URI.
2042 function get_page_uri($page_id) {
2043 $page = get_page($page_id);
2044 $uri = $page->post_name;
2046 // A page cannot be it's own parent.
2047 if ( $page->post_parent == $page->ID )
2050 while ($page->post_parent != 0) {
2051 $page = get_page($page->post_parent);
2052 $uri = $page->post_name . "/" . $uri;
2059 * Retrieve a list of pages.
2061 * The defaults that can be overridden are the following: 'child_of',
2062 * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
2063 * 'include', 'meta_key', 'meta_value', and 'authors'.
2068 * @param mixed $args Optional. Array or string of options that overrides defaults.
2069 * @return array List of pages matching defaults or $args
2071 function &get_pages($args = '') {
2075 'child_of' => 0, 'sort_order' => 'ASC',
2076 'sort_column' => 'post_title', 'hierarchical' => 1,
2077 'exclude' => '', 'include' => '',
2078 'meta_key' => '', 'meta_value' => '',
2079 'authors' => '', 'parent' => -1, 'exclude_tree' => ''
2082 $r = wp_parse_args( $args, $defaults );
2083 extract( $r, EXTR_SKIP );
2085 $key = md5( serialize( compact(array_keys($defaults)) ) );
2086 if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
2087 if ( isset( $cache[ $key ] ) ) {
2088 $pages = apply_filters('get_pages', $cache[ $key ], $r );
2094 if ( !empty($include) ) {
2095 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
2100 $hierarchical = false;
2101 $incpages = preg_split('/[\s,]+/',$include);
2102 if ( count($incpages) ) {
2103 foreach ( $incpages as $incpage ) {
2104 if (empty($inclusions))
2105 $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
2107 $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
2111 if (!empty($inclusions))
2115 if ( !empty($exclude) ) {
2116 $expages = preg_split('/[\s,]+/',$exclude);
2117 if ( count($expages) ) {
2118 foreach ( $expages as $expage ) {
2119 if (empty($exclusions))
2120 $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
2122 $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
2126 if (!empty($exclusions))
2130 if (!empty($authors)) {
2131 $post_authors = preg_split('/[\s,]+/',$authors);
2133 if ( count($post_authors) ) {
2134 foreach ( $post_authors as $post_author ) {
2135 //Do we have an author id or an author login?
2136 if ( 0 == intval($post_author) ) {
2137 $post_author = get_userdatabylogin($post_author);
2138 if ( empty($post_author) )
2140 if ( empty($post_author->ID) )
2142 $post_author = $post_author->ID;
2145 if ( '' == $author_query )
2146 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
2148 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
2150 if ( '' != $author_query )
2151 $author_query = " AND ($author_query)";
2156 $where = "$exclusions $inclusions ";
2157 if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
2158 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
2160 // meta_key and meta_value might be slashed
2161 $meta_key = stripslashes($meta_key);
2162 $meta_value = stripslashes($meta_value);
2163 if ( ! empty( $meta_key ) )
2164 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
2165 if ( ! empty( $meta_value ) )
2166 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
2171 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
2173 $query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
2174 $query .= $author_query;
2175 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
2177 $pages = $wpdb->get_results($query);
2179 if ( empty($pages) ) {
2180 $pages = apply_filters('get_pages', array(), $r);
2185 update_page_cache($pages);
2187 if ( $child_of || $hierarchical )
2188 $pages = & get_page_children($child_of, $pages);
2190 if ( !empty($exclude_tree) ) {
2193 $exclude = (int) $exclude_tree;
2194 $children = get_page_children($exclude, $pages);
2195 $excludes = array();
2196 foreach ( $children as $child )
2197 $excludes[] = $child->ID;
2198 $excludes[] = $exclude;
2199 $total = count($pages);
2200 for ( $i = 0; $i < $total; $i++ ) {
2201 if ( in_array($pages[$i]->ID, $excludes) )
2206 $cache[ $key ] = $pages;
2207 wp_cache_set( 'get_pages', $cache, 'posts' );
2209 $pages = apply_filters('get_pages', $pages, $r);
2215 // Attachment functions
2219 * Check if the attachment URI is local one and is really an attachment.
2223 * @param string $url URL to check
2224 * @return bool True on success, false on failure.
2226 function is_local_attachment($url) {
2227 if (strpos($url, get_bloginfo('url')) === false)
2229 if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
2231 if ( $id = url_to_postid($url) ) {
2232 $post = & get_post($id);
2233 if ( 'attachment' == $post->post_type )
2240 * Insert an attachment.
2242 * If you set the 'ID' in the $object parameter, it will mean that you are
2243 * updating and attempt to update the attachment. You can also set the
2244 * attachment name or title by setting the key 'post_name' or 'post_title'.
2246 * You can set the dates for the attachment manually by setting the 'post_date'
2247 * and 'post_date_gmt' keys' values.
2249 * By default, the comments will use the default settings for whether the
2250 * comments are allowed. You can close them manually or keep them open by
2251 * setting the value for the 'comment_status' key.
2253 * The $object parameter can have the following:
2254 * 'post_status' - Default is 'draft'. Can not be override, set the same as
2256 * 'post_type' - Default is 'post', will be set to attachment. Can not
2258 * 'post_author' - Default is current user ID. The ID of the user, who added
2260 * 'ping_status' - Default is the value in default ping status option.
2261 * Whether the attachment can accept pings.
2262 * 'post_parent' - Default is 0. Can use $parent parameter or set this for
2263 * the post it belongs to, if any.
2264 * 'menu_order' - Default is 0. The order it is displayed.
2265 * 'to_ping' - Whether to ping.
2266 * 'pinged' - Default is empty string.
2267 * 'post_password' - Default is empty string. The password to access the
2269 * 'guid' - Global Unique ID for referencing the attachment.
2270 * 'post_content_filtered' - Attachment post content filtered.
2271 * 'post_excerpt' - Attachment excerpt.
2277 * @param string|array $object Arguments to override defaults.
2278 * @param string $file Optional filename.
2279 * @param int $post_parent Parent post ID.
2280 * @return int Attachment ID.
2282 function wp_insert_attachment($object, $file = false, $parent = 0) {
2283 global $wpdb, $user_ID;
2285 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
2286 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2287 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
2288 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
2290 $object = wp_parse_args($object, $defaults);
2291 if ( !empty($parent) )
2292 $object['post_parent'] = $parent;
2294 $object = sanitize_post($object, 'db');
2296 // export array as variables
2297 extract($object, EXTR_SKIP);
2299 // Make sure we set a valid category
2300 if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
2301 $post_category = array(get_option('default_category'));
2304 if ( empty($post_author) )
2305 $post_author = $user_ID;
2307 $post_type = 'attachment';
2308 $post_status = 'inherit';
2310 // Are we updating or creating?
2311 if ( !empty($ID) ) {
2313 $post_ID = (int) $ID;
2319 // Create a valid post name.
2320 if ( empty($post_name) )
2321 $post_name = sanitize_title($post_title);
2323 $post_name = sanitize_title($post_name);
2325 // expected_slashed ($post_name)
2326 $post_name_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_status = 'inherit' AND ID != %d LIMIT 1", $post_name, $post_ID));
2328 if ($post_name_check) {
2330 while ($post_name_check) {
2331 $alt_post_name = $post_name . "-$suffix";
2332 // expected_slashed ($alt_post_name, $post_name)
2333 $post_name_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_status = 'inherit' AND ID != %d AND post_parent = %d LIMIT 1", $alt_post_name, $post_ID, $post_parent));
2336 $post_name = $alt_post_name;
2339 if ( empty($post_date) )
2340 $post_date = current_time('mysql');
2341 if ( empty($post_date_gmt) )
2342 $post_date_gmt = current_time('mysql', 1);
2344 if ( empty($post_modified) )
2345 $post_modified = $post_date;
2346 if ( empty($post_modified_gmt) )
2347 $post_modified_gmt = $post_date_gmt;
2349 if ( empty($comment_status) ) {
2351 $comment_status = 'closed';
2353 $comment_status = get_option('default_comment_status');
2355 if ( empty($ping_status) )
2356 $ping_status = get_option('default_ping_status');
2358 if ( isset($to_ping) )
2359 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
2363 if ( isset($post_parent) )
2364 $post_parent = (int) $post_parent;
2368 if ( isset($menu_order) )
2369 $menu_order = (int) $menu_order;
2373 if ( !isset($post_password) )
2374 $post_password = '';
2376 if ( ! isset($pinged) )
2379 // expected_slashed (everything!)
2380 $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' ) );
2381 $data = stripslashes_deep( $data );
2384 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
2386 // If there is a suggested ID, use it if not already present
2387 if ( !empty($import_id) ) {
2388 $import_id = (int) $import_id;
2389 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2390 $data['ID'] = $import_id;
2394 $wpdb->insert( $wpdb->posts, $data );
2395 $post_ID = (int) $wpdb->insert_id;
2398 if ( empty($post_name) ) {
2399 $post_name = sanitize_title($post_title, $post_ID);
2400 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
2403 wp_set_post_categories($post_ID, $post_category);
2406 update_attached_file( $post_ID, $file );
2408 clean_post_cache($post_ID);
2411 do_action('edit_attachment', $post_ID);
2413 do_action('add_attachment', $post_ID);
2420 * Delete an attachment.
2422 * Will remove the file also, when the attachment is removed. Removes all post
2423 * meta fields, taxonomy, comments, etc associated with the attachment (except
2428 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
2430 * @param int $postid Attachment ID.
2431 * @return mixed False on failure. Post data on success.
2433 function wp_delete_attachment($postid) {
2436 if ( !$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2439 if ( 'attachment' != $post->post_type )
2442 $meta = wp_get_attachment_metadata( $postid );
2443 $file = get_attached_file( $postid );
2445 /** @todo Delete for pluggable post taxonomies too */
2446 wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
2448 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
2450 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2452 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2454 $uploadPath = wp_upload_dir();
2456 if ( ! empty($meta['thumb']) ) {
2457 // Don't delete the thumb if another attachment uses it
2458 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'].'%', $postid)) ) {
2459 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
2460 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
2461 @ unlink( path_join($uploadPath['basedir'], $thumbfile) );
2465 // remove intermediate images if there are any
2466 $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
2467 foreach ( $sizes as $size ) {
2468 if ( $intermediate = image_get_intermediate_size($postid, $size) ) {
2469 $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
2470 @ unlink( path_join($uploadPath['basedir'], $intermediate_file) );
2474 $file = apply_filters('wp_delete_file', $file);
2476 if ( ! empty($file) )
2479 clean_post_cache($postid);
2481 do_action('delete_attachment', $postid);
2487 * Retrieve attachment meta field for attachment ID.
2491 * @param int $post_id Attachment ID
2492 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
2493 * @return string|bool Attachment meta field. False on failure.
2495 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
2496 $post_id = (int) $post_id;
2497 if ( !$post =& get_post( $post_id ) )
2500 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
2503 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
2507 * Update metadata for an attachment.
2511 * @param int $post_id Attachment ID.
2512 * @param array $data Attachment data.
2515 function wp_update_attachment_metadata( $post_id, $data ) {
2516 $post_id = (int) $post_id;
2517 if ( !$post =& get_post( $post_id ) )
2520 $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
2522 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
2526 * Retrieve the URL for an attachment.
2530 * @param int $post_id Attachment ID.
2533 function wp_get_attachment_url( $post_id = 0 ) {
2534 $post_id = (int) $post_id;
2535 if ( !$post =& get_post( $post_id ) )
2539 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
2540 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
2541 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
2542 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
2543 elseif ( false !== strpos($file, 'wp-content/uploads') )
2544 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
2546 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
2550 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.
2551 $url = get_the_guid( $post->ID );
2553 if ( 'attachment' != $post->post_type || empty($url) )
2556 return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
2560 * Retrieve thumbnail for an attachment.
2564 * @param int $post_id Attachment ID.
2565 * @return mixed False on failure. Thumbnail file path on success.
2567 function wp_get_attachment_thumb_file( $post_id = 0 ) {
2568 $post_id = (int) $post_id;
2569 if ( !$post =& get_post( $post_id ) )
2571 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
2574 $file = get_attached_file( $post->ID );
2576 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
2577 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
2582 * Retrieve URL for an attachment thumbnail.
2586 * @param int $post_id Attachment ID
2587 * @return string|bool False on failure. Thumbnail URL on success.
2589 function wp_get_attachment_thumb_url( $post_id = 0 ) {
2590 $post_id = (int) $post_id;
2591 if ( !$post =& get_post( $post_id ) )
2593 if ( !$url = wp_get_attachment_url( $post->ID ) )
2596 $sized = image_downsize( $post_id, 'thumbnail' );
2600 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
2603 $url = str_replace(basename($url), basename($thumb), $url);
2605 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
2609 * Check if the attachment is an image.
2613 * @param int $post_id Attachment ID
2616 function wp_attachment_is_image( $post_id = 0 ) {
2617 $post_id = (int) $post_id;
2618 if ( !$post =& get_post( $post_id ) )
2621 if ( !$file = get_attached_file( $post->ID ) )
2624 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
2626 $image_exts = array('jpg', 'jpeg', 'gif', 'png');
2628 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
2634 * Retrieve the icon for a MIME type.
2638 * @param string $mime MIME type
2639 * @return string|bool
2641 function wp_mime_type_icon( $mime = 0 ) {
2642 if ( !is_numeric($mime) )
2643 $icon = wp_cache_get("mime_type_icon_$mime");
2644 if ( empty($icon) ) {
2646 $post_mimes = array();
2647 if ( is_numeric($mime) ) {
2648 $mime = (int) $mime;
2649 if ( $post =& get_post( $mime ) ) {
2650 $post_id = (int) $post->ID;
2651 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
2652 if ( !empty($ext) ) {
2653 $post_mimes[] = $ext;
2654 if ( $ext_type = wp_ext2type( $ext ) )
2655 $post_mimes[] = $ext_type;
2657 $mime = $post->post_mime_type;
2662 $post_mimes[] = $mime;
2665 $icon_files = wp_cache_get('icon_files');
2667 if ( !is_array($icon_files) ) {
2668 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
2669 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
2670 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
2671 $icon_files = array();
2673 $dir = array_shift($keys = array_keys($dirs));
2674 $uri = array_shift($dirs);
2675 if ( $dh = opendir($dir) ) {
2676 while ( false !== $file = readdir($dh) ) {
2677 $file = basename($file);
2678 if ( substr($file, 0, 1) == '.' )
2680 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
2681 if ( is_dir("$dir/$file") )
2682 $dirs["$dir/$file"] = "$uri/$file";
2685 $icon_files["$dir/$file"] = "$uri/$file";
2690 wp_cache_set('icon_files', $icon_files, 600);
2693 // Icon basename - extension = MIME wildcard
2694 foreach ( $icon_files as $file => $uri )
2695 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
2697 if ( ! empty($mime) ) {
2698 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
2699 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
2700 $post_mimes[] = str_replace('/', '_', $mime);
2703 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
2704 $matches['default'] = array('default');
2706 foreach ( $matches as $match => $wilds ) {
2707 if ( isset($types[$wilds[0]])) {
2708 $icon = $types[$wilds[0]];
2709 if ( !is_numeric($mime) )
2710 wp_cache_set("mime_type_icon_$mime", $icon);
2716 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
2720 * Checked for changed slugs for published posts and save old slug.
2722 * The function is used along with form POST data. It checks for the wp-old-slug
2723 * POST field. Will only be concerned with published posts and the slug actually
2726 * If the slug was changed and not already part of the old slugs then it will be
2727 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
2730 * The most logically usage of this function is redirecting changed posts, so
2731 * that those that linked to an changed post will be redirected to the new post.
2735 * @param int $post_id Post ID.
2736 * @return int Same as $post_id
2738 function wp_check_for_changed_slugs($post_id) {
2739 if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
2742 $post = &get_post($post_id);
2744 // we're only concerned with published posts
2745 if ( $post->post_status != 'publish' || $post->post_type != 'post' )
2748 // only bother if the slug has changed
2749 if ( $post->post_name == $_POST['wp-old-slug'] )
2752 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
2754 // if we haven't added this old slug before, add it now
2755 if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
2756 add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
2758 // if the new slug was used previously, delete it from the list
2759 if ( in_array($post->post_name, $old_slugs) )
2760 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
2766 * Retrieve the private post SQL based on capability.
2768 * This function provides a standardized way to appropriately select on the
2769 * post_status of posts/pages. The function will return a piece of SQL code that
2770 * can be added to a WHERE clause; this SQL is constructed to allow all
2771 * published posts, and all private posts to which the user has access.
2773 * It also allows plugins that define their own post type to control the cap by
2774 * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
2775 * the capability the user must have to read the private post type.
2780 * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
2782 * @param string $post_type currently only supports 'post' or 'page'.
2783 * @return string SQL code that can be added to a where clause.
2785 function get_private_posts_cap_sql($post_type) {
2790 if ($post_type == 'post') {
2791 $cap = 'read_private_posts';
2793 } elseif ($post_type == 'page') {
2794 $cap = 'read_private_pages';
2795 // Dunno what it is, maybe plugins have their own post type?
2797 $cap = apply_filters('pub_priv_sql_capability', $cap);
2800 // We don't know what it is, filters don't change anything,
2801 // so set the SQL up to return nothing.
2806 $sql = '(post_status = \'publish\'';
2808 if (current_user_can($cap)) {
2809 // Does the user have the capability to view private posts? Guess so.
2810 $sql .= ' OR post_status = \'private\'';
2811 } elseif (is_user_logged_in()) {
2812 // Users can view their own private posts.
2813 $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
2822 * Retrieve the date the the last post was published.
2824 * The server timezone is the default and is the difference between GMT and
2825 * server time. The 'blog' value is the date when the last post was posted. The
2826 * 'gmt' is when the last post was posted in GMT formatted date.
2832 * @uses apply_filters() Calls 'get_lastpostdate' filter
2834 * @global mixed $cache_lastpostdate Stores the last post date
2835 * @global mixed $pagenow The current page being viewed
2837 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
2838 * @return string The date of the last post.
2840 function get_lastpostdate($timezone = 'server') {
2841 global $cache_lastpostdate, $wpdb, $blog_id;
2842 $add_seconds_server = date('Z');
2843 if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
2844 switch(strtolower($timezone)) {
2846 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
2849 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
2852 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
2855 $cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
2857 $lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
2859 return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
2863 * Retrieve last post modified date depending on timezone.
2865 * The server timezone is the default and is the difference between GMT and
2866 * server time. The 'blog' value is just when the last post was modified. The
2867 * 'gmt' is when the last post was modified in GMT time.
2872 * @uses apply_filters() Calls 'get_lastpostmodified' filter
2874 * @global mixed $cache_lastpostmodified Stores the date the last post was modified
2876 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
2877 * @return string The date the post was last modified.
2879 function get_lastpostmodified($timezone = 'server') {
2880 global $cache_lastpostmodified, $wpdb, $blog_id;
2881 $add_seconds_server = date('Z');
2882 if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
2883 switch(strtolower($timezone)) {
2885 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
2888 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
2891 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
2894 $lastpostdate = get_lastpostdate($timezone);
2895 if ( $lastpostdate > $lastpostmodified ) {
2896 $lastpostmodified = $lastpostdate;
2898 $cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
2900 $lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
2902 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
2906 * Updates posts in cache.
2908 * @usedby update_page_cache() Aliased by this function.
2910 * @package WordPress
2914 * @param array $posts Array of post objects
2916 function update_post_cache(&$posts) {
2920 foreach ( $posts as $post )
2921 wp_cache_add($post->ID, $post, 'posts');
2925 * Will clean the post in the cache.
2927 * Cleaning means delete from the cache of the post. Will call to clean the term
2928 * object cache associated with the post ID.
2930 * @package WordPress
2934 * @uses do_action() Will call the 'clean_post_cache' hook action.
2936 * @param int $id The Post ID in the cache to clean
2938 function clean_post_cache($id) {
2939 global $_wp_suspend_cache_invalidation, $wpdb;
2941 if ( !empty($_wp_suspend_cache_invalidation) )
2946 wp_cache_delete($id, 'posts');
2947 wp_cache_delete($id, 'post_meta');
2949 clean_object_term_cache($id, 'post');
2951 wp_cache_delete( 'wp_get_archives', 'general' );
2953 do_action('clean_post_cache', $id);
2955 if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
2956 foreach( $children as $cid )
2957 clean_post_cache( $cid );
2962 * Alias of update_post_cache().
2964 * @see update_post_cache() Posts and pages are the same, alias is intentional
2966 * @package WordPress
2970 * @param array $pages list of page objects
2972 function update_page_cache(&$pages) {
2973 update_post_cache($pages);
2977 * Will clean the page in the cache.
2979 * Clean (read: delete) page from cache that matches $id. Will also clean cache
2980 * associated with 'all_page_ids' and 'get_pages'.
2982 * @package WordPress
2986 * @uses do_action() Will call the 'clean_page_cache' hook action.
2988 * @param int $id Page ID to clean
2990 function clean_page_cache($id) {
2991 clean_post_cache($id);
2993 wp_cache_delete( 'all_page_ids', 'posts' );
2994 wp_cache_delete( 'get_pages', 'posts' );
2996 do_action('clean_page_cache', $id);
3000 * Call major cache updating functions for list of Post objects.
3002 * @package WordPress
3007 * @uses update_post_cache()
3008 * @uses update_object_term_cache()
3009 * @uses update_postmeta_cache()
3011 * @param array $posts Array of Post objects
3013 function update_post_caches(&$posts) {
3014 // No point in doing all this work if we didn't match any posts.
3018 update_post_cache($posts);
3020 $post_ids = array();
3022 for ($i = 0; $i < count($posts); $i++)
3023 $post_ids[] = $posts[$i]->ID;
3025 update_object_term_cache($post_ids, 'post');
3027 update_postmeta_cache($post_ids);
3031 * Updates metadata cache for list of post IDs.
3033 * Performs SQL query to retrieve the metadata for the post IDs and updates the
3034 * metadata cache for the posts. Therefore, the functions, which call this
3035 * function, do not need to perform SQL queries on their own.
3037 * @package WordPress
3043 * @param array $post_ids List of post IDs.
3044 * @return bool|array Returns false if there is nothing to update or an array of metadata.
3046 function update_postmeta_cache($post_ids) {
3049 if ( empty( $post_ids ) )
3052 if ( !is_array($post_ids) ) {
3053 $post_ids = preg_replace('|[^0-9,]|', '', $post_ids);
3054 $post_ids = explode(',', $post_ids);
3057 $post_ids = array_map('intval', $post_ids);
3060 foreach ( (array) $post_ids as $id ) {
3061 if ( false === wp_cache_get($id, 'post_meta') )
3065 if ( empty( $ids ) )
3068 // Get post-meta info
3069 $id_list = join(',', $ids);
3071 if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN ($id_list)", ARRAY_A) ) {
3072 foreach ( (array) $meta_list as $metarow) {
3073 $mpid = (int) $metarow['post_id'];
3074 $mkey = $metarow['meta_key'];
3075 $mval = $metarow['meta_value'];
3077 // Force subkeys to be array type:
3078 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
3079 $cache[$mpid] = array();
3080 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
3081 $cache[$mpid][$mkey] = array();
3083 // Add a value to the current pid/key:
3084 $cache[$mpid][$mkey][] = $mval;
3088 foreach ( (array) $ids as $id ) {
3089 if ( ! isset($cache[$id]) )
3090 $cache[$id] = array();
3093 foreach ( (array) array_keys($cache) as $post)
3094 wp_cache_set($post, $cache[$post], 'post_meta');
3104 * Hook for managing future post transitions to published.
3110 * @param string $new_status New post status
3111 * @param string $old_status Previous post status
3112 * @param object $post Object type containing the post information
3114 function _transition_post_status($new_status, $old_status, $post) {
3117 if ( $old_status != 'publish' && $new_status == 'publish' ) {
3118 // Reset GUID if transitioning to publish and it is empty
3119 if ( '' == get_the_guid($post->ID) )
3120 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
3121 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
3124 // Always clears the hook in case the post status bounced from future to draft.
3125 wp_clear_scheduled_hook('publish_future_post', $post->ID);
3129 * Hook used to schedule publication for a post marked for the future.
3131 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
3135 * @param int $deprecated Not Used. Can be set to null.
3136 * @param object $post Object type containing the post information
3138 function _future_post_hook($deprecated = '', $post) {
3139 wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
3140 wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
3144 * Hook to schedule pings and enclosures when a post is published.
3148 * @uses XMLRPC_REQUEST
3150 * @uses do_action Calls 'xmlprc_publish_post' action if XMLRPC_REQUEST is defined. Calls 'app_publish_post'
3151 * action if APP_REQUEST is defined.
3153 * @param int $post_id The ID in the database table of the post being published
3155 function _publish_post_hook($post_id) {
3158 if ( defined('XMLRPC_REQUEST') )
3159 do_action('xmlrpc_publish_post', $post_id);
3160 if ( defined('APP_REQUEST') )
3161 do_action('app_publish_post', $post_id);
3163 if ( defined('WP_IMPORTING') )
3166 $data = array( 'post_id' => $post_id, 'meta_value' => '1' );
3167 if ( get_option('default_pingback_flag') )
3168 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
3169 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
3170 wp_schedule_single_event(time(), 'do_pings');
3174 * Hook used to prevent page/post cache and rewrite rules from staying dirty.
3176 * Does two things. If the post is a page and has a template then it will
3177 * update/add that template to the meta. For both pages and posts, it will clean
3178 * the post cache to make sure that the cache updates to the changes done
3179 * recently. For pages, the rewrite rules of WordPress are flushed to allow for
3182 * The $post parameter, only uses 'post_type' property and 'page_template'
3186 * @uses $wp_rewrite Flushes Rewrite Rules.
3188 * @param int $post_id The ID in the database table for the $post
3189 * @param object $post Object type containing the post information
3191 function _save_post_hook($post_id, $post) {
3192 if ( $post->post_type == 'page' ) {
3193 clean_page_cache($post_id);
3194 // Avoid flushing rules for every post during import.
3195 if ( !defined('WP_IMPORTING') ) {
3197 $wp_rewrite->flush_rules();
3200 clean_post_cache($post_id);
3205 * Retrieve post ancestors and append to post ancestors property.
3207 * Will only retrieve ancestors once, if property is already set, then nothing
3208 * will be done. If there is not a parent post, or post ID and post parent ID
3209 * are the same then nothing will be done.
3211 * The parameter is passed by reference, so nothing needs to be returned. The
3212 * property will be updated and can be referenced after the function is
3213 * complete. The post parent will be an ancestor and the parent of the post
3214 * parent will be an ancestor. There will only be two ancestors at the most.
3220 * @param object $_post Post data.
3221 * @return null When nothing needs to be done.
3223 function _get_post_ancestors(&$_post) {
3226 if ( isset($_post->ancestors) )
3229 $_post->ancestors = array();
3231 if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
3234 $id = $_post->ancestors[] = $_post->post_parent;
3235 while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
3236 if ( $id == $ancestor )
3238 $id = $_post->ancestors[] = $ancestor;
3243 * Determines which fields of posts are to be saved in revisions.
3245 * Does two things. If passed a post *array*, it will return a post array ready
3246 * to be insterted into the posts table as a post revision. Otherwise, returns
3247 * an array whose keys are the post fields to be saved for post revisions.
3249 * @package WordPress
3250 * @subpackage Post_Revisions
3254 * @param array $post Optional a post array to be processed for insertion as a post revision.
3255 * @param bool $autosave optional Is the revision an autosave?
3256 * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
3258 function _wp_post_revision_fields( $post = null, $autosave = false ) {
3259 static $fields = false;
3262 // Allow these to be versioned
3264 'post_title' => __( 'Title' ),
3265 'post_content' => __( 'Content' ),
3266 'post_excerpt' => __( 'Excerpt' ),
3270 $fields = apply_filters( '_wp_post_revision_fields', $fields );
3272 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
3273 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
3274 unset( $fields[$protect] );
3277 if ( !is_array($post) )
3281 foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
3282 $return[$field] = $post[$field];
3284 $return['post_parent'] = $post['ID'];
3285 $return['post_status'] = 'inherit';
3286 $return['post_type'] = 'revision';
3287 $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
3288 $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
3289 $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
3295 * Saves an already existing post as a post revision.
3297 * Typically used immediately prior to post updates.
3299 * @package WordPress
3300 * @subpackage Post_Revisions
3303 * @uses _wp_put_post_revision()
3305 * @param int $post_id The ID of the post to save as a revision.
3306 * @return mixed Null or 0 if error, new revision ID, if success.
3308 function wp_save_post_revision( $post_id ) {
3309 // We do autosaves manually with wp_create_post_autosave()
3310 if ( @constant( 'DOING_AUTOSAVE' ) )
3313 // WP_POST_REVISIONS = 0, false
3314 if ( !constant('WP_POST_REVISIONS') )
3317 if ( !$post = get_post( $post_id, ARRAY_A ) )
3320 if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
3323 $return = _wp_put_post_revision( $post );
3325 // WP_POST_REVISIONS = true (default), -1
3326 if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
3329 // all revisions and (possibly) one autosave
3330 $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
3332 // WP_POST_REVISIONS = (int) (# of autasaves to save)
3333 $delete = count($revisions) - WP_POST_REVISIONS;
3338 $revisions = array_slice( $revisions, 0, $delete );
3340 for ( $i = 0; isset($revisions[$i]); $i++ ) {
3341 if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
3343 wp_delete_post_revision( $revisions[$i]->ID );
3350 * Retrieve the autosaved data of the specified post.
3352 * Returns a post object containing the information that was autosaved for the
3355 * @package WordPress
3356 * @subpackage Post_Revisions
3359 * @param int $post_id The post ID.
3360 * @return object|bool The autosaved data or false on failure or when no autosave exists.
3362 function wp_get_post_autosave( $post_id ) {
3364 if ( !$post = get_post( $post_id ) )
3368 'name' => "{$post->ID}-autosave",
3369 'post_parent' => $post->ID,
3370 'post_type' => 'revision',
3371 'post_status' => 'inherit'
3374 // Use WP_Query so that the result gets cached
3375 $autosave_query = new WP_Query;
3377 add_action( 'parse_query', '_wp_get_post_autosave_hack' );
3378 $autosave = $autosave_query->query( $q );
3379 remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
3381 if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
3382 return $autosave[0];
3388 * Internally used to hack WP_Query into submission.
3390 * @package WordPress
3391 * @subpackage Post_Revisions
3394 * @param object $query WP_Query object
3396 function _wp_get_post_autosave_hack( $query ) {
3397 $query->is_single = false;
3401 * Determines if the specified post is a revision.
3403 * @package WordPress
3404 * @subpackage Post_Revisions
3407 * @param int|object $post Post ID or post object.
3408 * @return bool|int False if not a revision, ID of revision's parent otherwise.
3410 function wp_is_post_revision( $post ) {
3411 if ( !$post = wp_get_post_revision( $post ) )
3413 return (int) $post->post_parent;
3417 * Determines if the specified post is an autosave.
3419 * @package WordPress
3420 * @subpackage Post_Revisions
3423 * @param int|object $post Post ID or post object.
3424 * @return bool|int False if not a revision, ID of autosave's parent otherwise
3426 function wp_is_post_autosave( $post ) {
3427 if ( !$post = wp_get_post_revision( $post ) )
3429 if ( "{$post->post_parent}-autosave" !== $post->post_name )
3431 return (int) $post->post_parent;
3435 * Inserts post data into the posts table as a post revision.
3437 * @package WordPress
3438 * @subpackage Post_Revisions
3441 * @uses wp_insert_post()
3443 * @param int|object|array $post Post ID, post object OR post array.
3444 * @param bool $autosave Optional. Is the revision an autosave?
3445 * @return mixed Null or 0 if error, new revision ID if success.
3447 function _wp_put_post_revision( $post = null, $autosave = false ) {
3448 if ( is_object($post) )
3449 $post = get_object_vars( $post );
3450 elseif ( !is_array($post) )
3451 $post = get_post($post, ARRAY_A);
3452 if ( !$post || empty($post['ID']) )
3455 if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
3456 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
3458 $post = _wp_post_revision_fields( $post, $autosave );
3460 $revision_id = wp_insert_post( $post );
3461 if ( is_wp_error($revision_id) )
3462 return $revision_id;
3465 do_action( '_wp_put_post_revision', $revision_id );
3466 return $revision_id;
3470 * Gets a post revision.
3472 * @package WordPress
3473 * @subpackage Post_Revisions
3478 * @param int|object $post Post ID or post object
3479 * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
3480 * @param string $filter Optional sanitation filter. @see sanitize_post()
3481 * @return mixed Null if error or post object if success
3483 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
3485 if ( !$revision = get_post( $post, OBJECT, $filter ) )
3487 if ( 'revision' !== $revision->post_type )
3490 if ( $output == OBJECT ) {
3492 } elseif ( $output == ARRAY_A ) {
3493 $_revision = get_object_vars($revision);
3495 } elseif ( $output == ARRAY_N ) {
3496 $_revision = array_values(get_object_vars($revision));
3504 * Restores a post to the specified revision.
3506 * Can restore a past using all fields of the post revision, or only selected
3509 * @package WordPress
3510 * @subpackage Post_Revisions
3513 * @uses wp_get_post_revision()
3514 * @uses wp_update_post()
3516 * @param int|object $revision_id Revision ID or revision object.
3517 * @param array $fields Optional. What fields to restore from. Defaults to all.
3518 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3520 function wp_restore_post_revision( $revision_id, $fields = null ) {
3521 if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
3524 if ( !is_array( $fields ) )
3525 $fields = array_keys( _wp_post_revision_fields() );
3528 foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
3529 $update[$field] = $revision[$field];
3534 $update['ID'] = $revision['post_parent'];
3536 $post_id = wp_update_post( $update );
3537 if ( is_wp_error( $post_id ) )
3541 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
3547 * Deletes a revision.
3549 * Deletes the row from the posts table corresponding to the specified revision.
3551 * @package WordPress
3552 * @subpackage Post_Revisions
3555 * @uses wp_get_post_revision()
3556 * @uses wp_delete_post()
3558 * @param int|object $revision_id Revision ID or revision object.
3559 * @param array $fields Optional. What fields to restore from. Defaults to all.
3560 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3562 function wp_delete_post_revision( $revision_id ) {
3563 if ( !$revision = wp_get_post_revision( $revision_id ) )
3566 $delete = wp_delete_post( $revision->ID );
3567 if ( is_wp_error( $delete ) )
3571 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
3577 * Returns all revisions of specified post.
3579 * @package WordPress
3580 * @subpackage Post_Revisions
3583 * @uses get_children()
3585 * @param int|object $post_id Post ID or post object
3586 * @return array empty if no revisions
3588 function wp_get_post_revisions( $post_id = 0, $args = null ) {
3589 if ( !constant('WP_POST_REVISIONS') )
3591 if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
3594 $defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
3595 $args = wp_parse_args( $args, $defaults );
3596 $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
3598 if ( !$revisions = get_children( $args ) )
3603 function _set_preview($post) {
3605 if ( ! is_object($post) )
3608 $preview = wp_get_post_autosave($post->ID);
3610 if ( ! is_object($preview) )
3613 $preview = sanitize_post($preview);
3615 $post->post_content = $preview->post_content;
3616 $post->post_title = $preview->post_title;
3617 $post->post_excerpt = $preview->post_excerpt;
3622 function _show_post_preview() {
3624 if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
3625 $id = (int) $_GET['preview_id'];
3627 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
3628 wp_die( __('You do not have permission to preview drafts.') );
3630 add_filter('the_preview', '_set_preview');