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
422 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
424 function set_post_type( $post_id = 0, $post_type = 'post' ) {
427 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
428 $return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
430 if ( 'page' == $post_type )
431 clean_page_cache($post_id);
433 clean_post_cache($post_id);
439 * Retrieve list of latest posts or posts matching criteria.
441 * The defaults are as follows:
442 * 'numberposts' - Default is 5. Total number of posts to retrieve.
443 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
444 * 'category' - What category to pull the posts from.
445 * 'orderby' - Default is 'post_date'. How to order the posts.
446 * 'order' - Default is 'DESC'. The order to retrieve the posts.
447 * 'include' - See {@link WP_Query::query()} for more.
448 * 'exclude' - See {@link WP_Query::query()} for more.
449 * 'meta_key' - See {@link WP_Query::query()} for more.
450 * 'meta_value' - See {@link WP_Query::query()} for more.
451 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
452 * 'post_parent' - The parent of the post or post type.
453 * 'post_status' - Default is 'published'. Post status to retrieve.
457 * @uses WP_Query::query() See for more default arguments and information.
458 * @link http://codex.wordpress.org/Template_Tags/get_posts
460 * @param array $args Optional. Overrides defaults.
461 * @return array List of posts.
463 function get_posts($args = null) {
465 'numberposts' => 5, 'offset' => 0,
466 'category' => 0, 'orderby' => 'post_date',
467 'order' => 'DESC', 'include' => '',
468 'exclude' => '', 'meta_key' => '',
469 'meta_value' =>'', 'post_type' => 'post',
470 'suppress_filters' => true
473 $r = wp_parse_args( $args, $defaults );
474 if ( empty( $r['post_status'] ) )
475 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
476 if ( ! empty($r['numberposts']) )
477 $r['posts_per_page'] = $r['numberposts'];
478 if ( ! empty($r['category']) )
479 $r['cat'] = $r['category'];
480 if ( ! empty($r['include']) ) {
481 $incposts = preg_split('/[\s,]+/',$r['include']);
482 $r['posts_per_page'] = count($incposts); // only the number of posts included
483 $r['post__in'] = $incposts;
484 } elseif ( ! empty($r['exclude']) )
485 $r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
487 $r['caller_get_posts'] = true;
489 $get_posts = new WP_Query;
490 return $get_posts->query($r);
495 // Post meta functions
499 * Add meta data field to a post.
501 * Post meta data is called "Custom Fields" on the Administration Panels.
505 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
507 * @param int $post_id Post ID.
508 * @param string $key Metadata name.
509 * @param mixed $value Metadata value.
510 * @param bool $unique Optional, default is false. Whether the same key should not be added.
511 * @return bool False for failure. True for success.
513 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
519 // make sure meta is added to the post, not a revision
520 if ( $the_post = wp_is_post_revision($post_id) )
521 $post_id = $the_post;
523 // expected_slashed ($meta_key)
524 $meta_key = stripslashes($meta_key);
526 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 ) ) )
529 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
531 $wpdb->insert( $wpdb->postmeta, compact( 'post_id', 'meta_key', 'meta_value' ) );
533 wp_cache_delete($post_id, 'post_meta');
539 * Remove metadata matching criteria from a post.
541 * You can match based on the key, or key and value. Removing based on key and
542 * value, will keep from removing duplicate metadata with the same key. It also
543 * allows removing all metadata matching key, if needed.
547 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
549 * @param int $post_id post ID
550 * @param string $meta_key Metadata name.
551 * @param mixed $meta_value Optional. Metadata value.
552 * @return bool False for failure. True for success.
554 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
557 // make sure meta is added to the post, not a revision
558 if ( $the_post = wp_is_post_revision($post_id) )
559 $post_id = $the_post;
561 // expected_slashed ($meta_key, $meta_value)
562 $meta_key = stripslashes( $meta_key );
563 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
568 if ( empty( $meta_value ) )
569 $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 ) );
571 $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 ) );
576 if ( empty( $meta_value ) )
577 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
579 $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 ) );
581 wp_cache_delete($post_id, 'post_meta');
587 * Retrieve post meta field for a post.
591 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
593 * @param int $post_id Post ID.
594 * @param string $key The meta key to retrieve.
595 * @param bool $single Whether to return a single value.
596 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
599 function get_post_meta($post_id, $key, $single = false) {
603 $post_id = (int) $post_id;
605 $meta_cache = wp_cache_get($post_id, 'post_meta');
607 if ( !$meta_cache ) {
608 update_postmeta_cache($post_id);
609 $meta_cache = wp_cache_get($post_id, 'post_meta');
612 if ( isset($meta_cache[$key]) ) {
614 return maybe_unserialize( $meta_cache[$key][0] );
616 return array_map('maybe_unserialize', $meta_cache[$key]);
624 * Update post meta field based on post ID.
626 * Use the $prev_value parameter to differentiate between meta fields with the
627 * same key and post ID.
629 * If the meta field for the post does not exist, it will be added.
633 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
635 * @param int $post_id Post ID.
636 * @param string $key Metadata key.
637 * @param mixed $value Metadata value.
638 * @param mixed $prev_value Optional. Previous value to check before removing.
639 * @return bool False on failure, true if success.
641 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
644 // make sure meta is added to the post, not a revision
645 if ( $the_post = wp_is_post_revision($post_id) )
646 $post_id = $the_post;
648 // expected_slashed ($meta_key)
649 $meta_key = stripslashes($meta_key);
654 if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) {
655 return add_post_meta($post_id, $meta_key, $meta_value);
658 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
660 $data = compact( 'meta_value' );
661 $where = compact( 'meta_key', 'post_id' );
663 if ( !empty( $prev_value ) ) {
664 $prev_value = maybe_serialize($prev_value);
665 $where['meta_value'] = $prev_value;
668 $wpdb->update( $wpdb->postmeta, $data, $where );
669 wp_cache_delete($post_id, 'post_meta');
674 * Delete everything from post meta matching meta key.
679 * @param string $post_meta_key Key to search for when deleting.
680 * @return bool Whether the post meta key was deleted from the database
682 function delete_post_meta_by_key($post_meta_key) {
683 if ( !$post_meta_key )
687 $post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
689 $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
690 foreach ( $post_ids as $post_id )
691 wp_cache_delete($post_id, 'post_meta');
698 * Retrieve post meta fields, based on post ID.
700 * The post meta fields are retrieved from the cache, so the function is
701 * optimized to be called more than once. It also applies to the functions, that
705 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
707 * @uses $id Current Loop Post ID
709 * @param int $post_id post ID
712 function get_post_custom($post_id = 0) {
716 $post_id = (int) $id;
718 $post_id = (int) $post_id;
720 if ( ! wp_cache_get($post_id, 'post_meta') )
721 update_postmeta_cache($post_id);
723 return wp_cache_get($post_id, 'post_meta');
727 * Retrieve meta field names for a post.
729 * If there are no meta fields, then nothing (null) will be returned.
732 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
734 * @param int $post_id post ID
735 * @return array|null Either array of the keys, or null if keys could not be retrieved.
737 function get_post_custom_keys( $post_id = 0 ) {
738 $custom = get_post_custom( $post_id );
740 if ( !is_array($custom) )
743 if ( $keys = array_keys($custom) )
748 * Retrieve values for a custom post field.
750 * The parameters must not be considered optional. All of the post meta fields
751 * will be retrieved and only the meta field key values returned.
754 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
756 * @param string $key Meta field key.
757 * @param int $post_id Post ID
758 * @return array Meta field values.
760 function get_post_custom_values( $key = '', $post_id = 0 ) {
764 $custom = get_post_custom($post_id);
766 return isset($custom[$key]) ? $custom[$key] : null;
770 * Check if post is sticky.
772 * Sticky posts should remain at the top of The Loop. If the post ID is not
773 * given, then The Loop ID for the current post will be used.
777 * @param int $post_id Optional. Post ID.
778 * @return bool Whether post is sticky (true) or not sticky (false).
780 function is_sticky($post_id = null) {
783 $post_id = absint($post_id);
786 $post_id = absint($id);
788 $stickies = get_option('sticky_posts');
790 if ( !is_array($stickies) )
793 if ( in_array($post_id, $stickies) )
800 * Sanitize every post field.
802 * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
805 * @uses sanitize_post_field() Used to sanitize the fields.
807 * @param object|array $post The Post Object or Array
808 * @param string $context Optional, default is 'display'. How to sanitize post fields.
809 * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
811 function sanitize_post($post, $context = 'display') {
812 if ( is_object($post) ) {
813 if ( !isset($post->ID) )
815 foreach ( array_keys(get_object_vars($post)) as $field )
816 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
817 $post->filter = $context;
819 if ( !isset($post['ID']) )
821 foreach ( array_keys($post) as $field )
822 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
823 $post['filter'] = $context;
830 * Sanitize post field based on context.
832 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
833 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
834 * when calling filters.
837 * @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
838 * $post_id if $context == 'edit' and field name prefix == 'post_'.
840 * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
841 * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
842 * @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
844 * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
845 * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
846 * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
847 * 'edit' and 'db' and field name prefix != 'post_'.
849 * @param string $field The Post Object field name.
850 * @param mixed $value The Post Object value.
851 * @param int $post_id Post ID.
852 * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
853 * 'attribute' and 'js'.
854 * @return mixed Sanitized value.
856 function sanitize_post_field($field, $value, $post_id, $context) {
857 $int_fields = array('ID', 'post_parent', 'menu_order');
858 if ( in_array($field, $int_fields) )
859 $value = (int) $value;
861 if ( 'raw' == $context )
865 if ( false !== strpos($field, 'post_') ) {
867 $field_no_prefix = str_replace('post_', '', $field);
870 if ( 'edit' == $context ) {
871 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
874 $value = apply_filters("edit_$field", $value, $post_id);
876 $value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
878 $value = apply_filters("edit_post_$field", $value, $post_id);
881 if ( in_array($field, $format_to_edit) ) {
882 if ( 'post_content' == $field )
883 $value = format_to_edit($value, user_can_richedit());
885 $value = format_to_edit($value);
887 $value = esc_attr($value);
889 } else if ( 'db' == $context ) {
891 $value = apply_filters("pre_$field", $value);
892 $value = apply_filters("${field_no_prefix}_save_pre", $value);
894 $value = apply_filters("pre_post_$field", $value);
895 $value = apply_filters("${field}_pre", $value);
898 // Use display filters by default.
900 $value = apply_filters($field, $value, $post_id, $context);
902 $value = apply_filters("post_$field", $value, $post_id, $context);
905 if ( 'attribute' == $context )
906 $value = esc_attr($value);
907 else if ( 'js' == $context )
908 $value = esc_js($value);
914 * Make a post sticky.
916 * Sticky posts should be displayed at the top of the front page.
920 * @param int $post_id Post ID.
922 function stick_post($post_id) {
923 $stickies = get_option('sticky_posts');
925 if ( !is_array($stickies) )
926 $stickies = array($post_id);
928 if ( ! in_array($post_id, $stickies) )
929 $stickies[] = $post_id;
931 update_option('sticky_posts', $stickies);
937 * Sticky posts should be displayed at the top of the front page.
941 * @param int $post_id Post ID.
943 function unstick_post($post_id) {
944 $stickies = get_option('sticky_posts');
946 if ( !is_array($stickies) )
949 if ( ! in_array($post_id, $stickies) )
952 $offset = array_search($post_id, $stickies);
953 if ( false === $offset )
956 array_splice($stickies, $offset, 1);
958 update_option('sticky_posts', $stickies);
962 * Count number of posts of a post type and is user has permissions to view.
964 * This function provides an efficient method of finding the amount of post's
965 * type a blog has. Another method is to count the amount of items in
966 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
967 * when developing for 2.5+, use this function instead.
969 * The $perm parameter checks for 'readable' value and if the user can read
970 * private posts, it will display that for the user that is signed in.
973 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
975 * @param string $type Optional. Post type to retrieve count
976 * @param string $perm Optional. 'readable' or empty.
977 * @return object Number of posts for each status
979 function wp_count_posts( $type = 'post', $perm = '' ) {
982 $user = wp_get_current_user();
986 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
987 if ( 'readable' == $perm && is_user_logged_in() ) {
988 if ( !current_user_can("read_private_{$type}s") ) {
989 $cache_key .= '_' . $perm . '_' . $user->ID;
990 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
993 $query .= ' GROUP BY post_status';
995 $count = wp_cache_get($cache_key, 'counts');
996 if ( false !== $count )
999 $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
1001 $stats = array( 'publish' => 0, 'private' => 0, 'draft' => 0, 'pending' => 0, 'future' => 0 );
1002 foreach( (array) $count as $row_num => $row ) {
1003 $stats[$row['post_status']] = $row['num_posts'];
1006 $stats = (object) $stats;
1007 wp_cache_set($cache_key, $stats, 'counts');
1014 * Count number of attachments for the mime type(s).
1016 * If you set the optional mime_type parameter, then an array will still be
1017 * returned, but will only have the item you are looking for. It does not give
1018 * you the number of attachments that are children of a post. You can get that
1019 * by counting the number of children that post has.
1023 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
1024 * @return array Number of posts for each mime type.
1026 function wp_count_attachments( $mime_type = '' ) {
1029 $and = wp_post_mime_type_where( $mime_type );
1030 $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 );
1033 foreach( (array) $count as $row ) {
1034 $stats[$row['post_mime_type']] = $row['num_posts'];
1037 return (object) $stats;
1041 * Check a MIME-Type against a list.
1043 * If the wildcard_mime_types parameter is a string, it must be comma separated
1044 * list. If the real_mime_types is a string, it is also comma separated to
1049 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
1050 * flash (same as *flash*).
1051 * @param string|array $real_mime_types post_mime_type values
1052 * @return array array(wildcard=>array(real types))
1054 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
1056 if ( is_string($wildcard_mime_types) )
1057 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
1058 if ( is_string($real_mime_types) )
1059 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
1060 $wild = '[-._a-z0-9]*';
1061 foreach ( (array) $wildcard_mime_types as $type ) {
1062 $type = str_replace('*', $wild, $type);
1063 $patternses[1][$type] = "^$type$";
1064 if ( false === strpos($type, '/') ) {
1065 $patternses[2][$type] = "^$type/";
1066 $patternses[3][$type] = $type;
1070 foreach ( $patternses as $patterns )
1071 foreach ( $patterns as $type => $pattern )
1072 foreach ( (array) $real_mime_types as $real )
1073 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
1074 $matches[$type][] = $real;
1079 * Convert MIME types into SQL.
1083 * @param string|array $mime_types List of mime types or comma separated string of mime types.
1084 * @return string The SQL AND clause for mime searching.
1086 function wp_post_mime_type_where($post_mime_types) {
1088 $wildcards = array('', '%', '%/%');
1089 if ( is_string($post_mime_types) )
1090 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
1091 foreach ( (array) $post_mime_types as $mime_type ) {
1092 $mime_type = preg_replace('/\s/', '', $mime_type);
1093 $slashpos = strpos($mime_type, '/');
1094 if ( false !== $slashpos ) {
1095 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
1096 $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
1097 if ( empty($mime_subgroup) )
1098 $mime_subgroup = '*';
1100 $mime_subgroup = str_replace('/', '', $mime_subgroup);
1101 $mime_pattern = "$mime_group/$mime_subgroup";
1103 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
1104 if ( false === strpos($mime_pattern, '*') )
1105 $mime_pattern .= '/*';
1108 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
1110 if ( in_array( $mime_type, $wildcards ) )
1113 if ( false !== strpos($mime_pattern, '%') )
1114 $wheres[] = "post_mime_type LIKE '$mime_pattern'";
1116 $wheres[] = "post_mime_type = '$mime_pattern'";
1118 if ( !empty($wheres) )
1119 $where = ' AND (' . join(' OR ', $wheres) . ') ';
1124 * Removes a post, attachment, or page.
1126 * When the post and page goes, everything that is tied to it is deleted also.
1127 * This includes comments, post meta fields, and terms associated with the post.
1130 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
1131 * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
1132 * @uses wp_delete_attachment() if post type is 'attachment'.
1134 * @param int $postid Post ID.
1135 * @return mixed False on failure
1137 function wp_delete_post($postid = 0) {
1138 global $wpdb, $wp_rewrite;
1140 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
1143 if ( 'attachment' == $post->post_type )
1144 return wp_delete_attachment($postid);
1146 do_action('delete_post', $postid);
1148 /** @todo delete for pluggable post taxonomies too */
1149 wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
1151 $parent_data = array( 'post_parent' => $post->post_parent );
1152 $parent_where = array( 'post_parent' => $postid );
1154 if ( 'page' == $post->post_type) {
1155 // if the page is defined in option page_on_front or post_for_posts,
1156 // adjust the corresponding options
1157 if ( get_option('page_on_front') == $postid ) {
1158 update_option('show_on_front', 'posts');
1159 delete_option('page_on_front');
1161 if ( get_option('page_for_posts') == $postid ) {
1162 delete_option('page_for_posts');
1165 // Point children of this page to its parent, also clean the cache of affected children
1166 $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
1167 $children = $wpdb->get_results($children_query);
1169 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
1171 unstick_post($postid);
1174 // Do raw query. wp_get_post_revisions() is filtered
1175 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
1176 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
1177 foreach ( $revision_ids as $revision_id )
1178 wp_delete_post_revision( $revision_id );
1180 // Point all attachments to this post up one level
1181 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
1183 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
1185 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d", $postid ));
1187 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
1189 if ( 'page' == $post->post_type ) {
1190 clean_page_cache($postid);
1192 foreach ( (array) $children as $child )
1193 clean_page_cache($child->ID);
1195 $wp_rewrite->flush_rules(false);
1197 clean_post_cache($postid);
1200 wp_clear_scheduled_hook('publish_future_post', $postid);
1202 do_action('deleted_post', $postid);
1208 * Retrieve the list of categories for a post.
1210 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
1211 * away from the complexity of the taxonomy layer.
1215 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
1217 * @param int $post_id Optional. The Post ID.
1218 * @param array $args Optional. Overwrite the defaults.
1221 function wp_get_post_categories( $post_id = 0, $args = array() ) {
1222 $post_id = (int) $post_id;
1224 $defaults = array('fields' => 'ids');
1225 $args = wp_parse_args( $args, $defaults );
1227 $cats = wp_get_object_terms($post_id, 'category', $args);
1232 * Retrieve the tags for a post.
1234 * There is only one default for this function, called 'fields' and by default
1235 * is set to 'all'. There are other defaults that can be overridden in
1236 * {@link wp_get_object_terms()}.
1238 * @package WordPress
1242 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1244 * @param int $post_id Optional. The Post ID
1245 * @param array $args Optional. Overwrite the defaults
1246 * @return array List of post tags.
1248 function wp_get_post_tags( $post_id = 0, $args = array() ) {
1249 return wp_get_post_terms( $post_id, 'post_tag', $args);
1253 * Retrieve the terms for a post.
1255 * There is only one default for this function, called 'fields' and by default
1256 * is set to 'all'. There are other defaults that can be overridden in
1257 * {@link wp_get_object_terms()}.
1259 * @package WordPress
1263 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1265 * @param int $post_id Optional. The Post ID
1266 * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
1267 * @param array $args Optional. Overwrite the defaults
1268 * @return array List of post tags.
1270 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
1271 $post_id = (int) $post_id;
1273 $defaults = array('fields' => 'all');
1274 $args = wp_parse_args( $args, $defaults );
1276 $tags = wp_get_object_terms($post_id, $taxonomy, $args);
1282 * Retrieve number of recent posts.
1287 * @param int $num Optional, default is 10. Number of posts to get.
1288 * @return array List of posts.
1290 function wp_get_recent_posts($num = 10) {
1293 // Set the limit clause, if we got a limit
1296 $limit = "LIMIT $num";
1299 $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit";
1300 $result = $wpdb->get_results($sql,ARRAY_A);
1302 return $result ? $result : array();
1306 * Retrieve a single post, based on post ID.
1308 * Has categories in 'post_category' property or key. Has tags in 'tags_input'
1313 * @param int $postid Post ID.
1314 * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
1315 * @return object|array Post object or array holding post contents and information
1317 function wp_get_single_post($postid = 0, $mode = OBJECT) {
1318 $postid = (int) $postid;
1320 $post = get_post($postid, $mode);
1322 // Set categories and tags
1323 if($mode == OBJECT) {
1324 $post->post_category = wp_get_post_categories($postid);
1325 $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
1328 $post['post_category'] = wp_get_post_categories($postid);
1329 $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
1338 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
1340 * You can set the post date manually, but setting the values for 'post_date'
1341 * and 'post_date_gmt' keys. You can close the comments or open the comments by
1342 * setting the value for 'comment_status' key.
1344 * The defaults for the parameter $postarr are:
1345 * 'post_status' - Default is 'draft'.
1346 * 'post_type' - Default is 'post'.
1347 * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post.
1348 * 'ping_status' - Default is the value in 'default_ping_status' option.
1349 * Whether the attachment can accept pings.
1350 * 'post_parent' - Default is 0. Set this for the post it belongs to, if any.
1351 * 'menu_order' - Default is 0. The order it is displayed.
1352 * 'to_ping' - Whether to ping.
1353 * 'pinged' - Default is empty string.
1354 * 'post_password' - Default is empty string. The password to access the attachment.
1355 * 'guid' - Global Unique ID for referencing the attachment.
1356 * 'post_content_filtered' - Post content filtered.
1357 * 'post_excerpt' - Post excerpt.
1360 * @link http://core.trac.wordpress.org/ticket/9084 Bug report on 'wp_insert_post_data' filter.
1365 * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
1366 * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
1367 * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before
1370 * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database
1372 * @uses wp_transition_post_status()
1374 * @param array $postarr Optional. Overrides defaults.
1375 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
1376 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
1378 function wp_insert_post($postarr = array(), $wp_error = false) {
1379 global $wpdb, $wp_rewrite, $user_ID;
1381 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
1382 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
1383 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
1384 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
1386 $postarr = wp_parse_args($postarr, $defaults);
1387 $postarr = sanitize_post($postarr, 'db');
1389 // export array as variables
1390 extract($postarr, EXTR_SKIP);
1392 // Are we updating or creating?
1394 if ( !empty($ID) ) {
1396 $previous_status = get_post_field('post_status', $ID);
1398 $previous_status = 'new';
1401 if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) ) {
1403 return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
1408 // Make sure we set a valid category
1409 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
1410 $post_category = array(get_option('default_category'));
1413 //Set the default tag list
1414 if ( !isset($tags_input) )
1415 $tags_input = array();
1417 if ( empty($post_author) )
1418 $post_author = $user_ID;
1420 if ( empty($post_status) )
1421 $post_status = 'draft';
1423 if ( empty($post_type) )
1424 $post_type = 'post';
1428 // Get the post ID and GUID
1430 $post_ID = (int) $ID;
1431 $guid = get_post_field( 'guid', $post_ID );
1434 // Don't allow contributors to set to set the post slug for pending review posts
1435 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
1438 // Create a valid post name. Drafts and pending posts are allowed to have an empty
1440 if ( !isset($post_name) || empty($post_name) ) {
1441 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1442 $post_name = sanitize_title($post_title);
1446 $post_name = sanitize_title($post_name);
1449 // 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
1450 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
1451 $post_date = current_time('mysql');
1453 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
1454 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1455 $post_date_gmt = get_gmt_from_date($post_date);
1457 $post_date_gmt = '0000-00-00 00:00:00';
1460 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
1461 $post_modified = current_time( 'mysql' );
1462 $post_modified_gmt = current_time( 'mysql', 1 );
1464 $post_modified = $post_date;
1465 $post_modified_gmt = $post_date_gmt;
1468 if ( 'publish' == $post_status ) {
1469 $now = gmdate('Y-m-d H:i:59');
1470 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
1471 $post_status = 'future';
1474 if ( empty($comment_status) ) {
1476 $comment_status = 'closed';
1478 $comment_status = get_option('default_comment_status');
1480 if ( empty($ping_status) )
1481 $ping_status = get_option('default_ping_status');
1483 if ( isset($to_ping) )
1484 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
1488 if ( ! isset($pinged) )
1491 if ( isset($post_parent) )
1492 $post_parent = (int) $post_parent;
1496 if ( !empty($post_ID) ) {
1497 if ( $post_parent == $post_ID ) {
1498 // Post can't be its own parent
1500 } elseif ( !empty($post_parent) ) {
1501 $parent_post = get_post($post_parent);
1502 // Check for circular dependency
1503 if ( $parent_post->post_parent == $post_ID )
1508 if ( isset($menu_order) )
1509 $menu_order = (int) $menu_order;
1513 if ( !isset($post_password) || 'private' == $post_status )
1514 $post_password = '';
1516 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
1518 // expected_slashed (everything!)
1519 $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' ) );
1520 $data = apply_filters('wp_insert_post_data', $data, $postarr);
1521 $data = stripslashes_deep( $data );
1522 $where = array( 'ID' => $post_ID );
1525 do_action( 'pre_post_update', $post_ID );
1526 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
1528 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
1533 if ( isset($post_mime_type) )
1534 $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
1535 // If there is a suggested ID, use it if not already present
1536 if ( !empty($import_id) ) {
1537 $import_id = (int) $import_id;
1538 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
1539 $data['ID'] = $import_id;
1542 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
1544 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
1548 $post_ID = (int) $wpdb->insert_id;
1550 // use the newly generated $post_ID
1551 $where = array( 'ID' => $post_ID );
1554 if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending' ) ) ) {
1555 $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
1556 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
1559 wp_set_post_categories( $post_ID, $post_category );
1560 // old-style tags_input
1561 if ( !empty($tags_input) )
1562 wp_set_post_tags( $post_ID, $tags_input );
1563 // new-style support for all tag-like taxonomies
1564 if ( !empty($tax_input) ) {
1565 foreach ( $tax_input as $taxonomy => $tags ) {
1566 wp_set_post_terms( $post_ID, $tags, $taxonomy );
1570 $current_guid = get_post_field( 'guid', $post_ID );
1572 if ( 'page' == $data['post_type'] )
1573 clean_page_cache($post_ID);
1575 clean_post_cache($post_ID);
1578 if ( !$update && '' == $current_guid )
1579 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
1581 $post = get_post($post_ID);
1583 if ( !empty($page_template) && 'page' == $data['post_type'] ) {
1584 $post->page_template = $page_template;
1585 $page_templates = get_page_templates();
1586 if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
1588 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
1592 update_post_meta($post_ID, '_wp_page_template', $page_template);
1595 wp_transition_post_status($data['post_status'], $previous_status, $post);
1598 do_action('edit_post', $post_ID, $post);
1600 do_action('save_post', $post_ID, $post);
1601 do_action('wp_insert_post', $post_ID, $post);
1607 * Update a post with new post data.
1609 * The date does not have to be set for drafts. You can set the date and it will
1610 * not be overridden.
1614 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
1615 * @return int 0 on failure, Post ID on success.
1617 function wp_update_post($postarr = array()) {
1618 if ( is_object($postarr) ) {
1619 // non-escaped post was passed
1620 $postarr = get_object_vars($postarr);
1621 $postarr = add_magic_quotes($postarr);
1624 // First, get all of the original fields
1625 $post = wp_get_single_post($postarr['ID'], ARRAY_A);
1627 // Escape data pulled from DB.
1628 $post = add_magic_quotes($post);
1630 // Passed post category list overwrites existing category list if not empty.
1631 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
1632 && 0 != count($postarr['post_category']) )
1633 $post_cats = $postarr['post_category'];
1635 $post_cats = $post['post_category'];
1637 // Drafts shouldn't be assigned a date unless explicitly done so by the user
1638 if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
1639 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
1642 $clear_date = false;
1644 // Merge old and new fields with new fields overwriting old ones.
1645 $postarr = array_merge($post, $postarr);
1646 $postarr['post_category'] = $post_cats;
1647 if ( $clear_date ) {
1648 $postarr['post_date'] = current_time('mysql');
1649 $postarr['post_date_gmt'] = '';
1652 if ($postarr['post_type'] == 'attachment')
1653 return wp_insert_attachment($postarr);
1655 return wp_insert_post($postarr);
1659 * Publish a post by transitioning the post status.
1663 * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
1665 * @param int $post_id Post ID.
1668 function wp_publish_post($post_id) {
1671 $post = get_post($post_id);
1676 if ( 'publish' == $post->post_status )
1679 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
1681 $old_status = $post->post_status;
1682 $post->post_status = 'publish';
1683 wp_transition_post_status('publish', $old_status, $post);
1685 // Update counts for the post's terms.
1686 foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
1687 $tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
1688 wp_update_term_count($tt_ids, $taxonomy);
1691 do_action('edit_post', $post_id, $post);
1692 do_action('save_post', $post_id, $post);
1693 do_action('wp_insert_post', $post_id, $post);
1697 * Publish future post and make sure post ID has future post status.
1699 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
1700 * from publishing drafts, etc.
1704 * @param int $post_id Post ID.
1705 * @return null Nothing is returned. Which can mean that no action is required or post was published.
1707 function check_and_publish_future_post($post_id) {
1709 $post = get_post($post_id);
1714 if ( 'future' != $post->post_status )
1717 $time = strtotime( $post->post_date_gmt . ' GMT' );
1719 if ( $time > time() ) { // Uh oh, someone jumped the gun!
1720 wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
1721 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
1725 return wp_publish_post($post_id);
1730 * Given the desired slug and some post details computes a unique slug for the post.
1732 * @param string $slug the desired slug (post_name)
1733 * @param integer $post_ID
1734 * @param string $post_status no uniqueness checks are made if the post is still draft or pending
1735 * @param string $post_type
1736 * @param integer $post_parent
1737 * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
1739 function wp_unique_post_slug($slug, $post_ID, $post_status, $post_type, $post_parent) {
1740 if ( in_array( $post_status, array( 'draft', 'pending' ) ) )
1743 global $wpdb, $wp_rewrite;
1744 $hierarchical_post_types = apply_filters('hierarchical_post_types', array('page'));
1745 if ( 'attachment' == $post_type ) {
1746 // Attachment slugs must be unique across all types.
1747 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
1748 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID));
1750 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
1753 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1754 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID));
1756 } while ($post_name_check);
1757 $slug = $alt_post_name;
1759 } elseif ( in_array($post_type, $hierarchical_post_types) ) {
1760 // Page slugs must be unique within their own trees. Pages are in a
1761 // separate namespace than posts so page slugs are allowed to overlap post slugs.
1762 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode("', '", $wpdb->escape($hierarchical_post_types)) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
1763 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID, $post_parent));
1765 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
1768 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1769 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID, $post_parent));
1771 } while ($post_name_check);
1772 $slug = $alt_post_name;
1775 // Post slugs must be unique across all posts.
1776 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
1777 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_type, $post_ID));
1779 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
1782 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1783 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_type, $post_ID));
1785 } while ($post_name_check);
1786 $slug = $alt_post_name;
1794 * Adds tags to a post.
1796 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
1798 * @package WordPress
1802 * @param int $post_id Post ID
1803 * @param string $tags The tags to set for the post, separated by commas.
1804 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1806 function wp_add_post_tags($post_id = 0, $tags = '') {
1807 return wp_set_post_tags($post_id, $tags, true);
1812 * Set the tags for a post.
1815 * @uses wp_set_object_terms() Sets the tags for the post.
1817 * @param int $post_id Post ID.
1818 * @param string $tags The tags to set for the post, separated by commas.
1819 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
1820 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1822 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
1823 return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
1827 * Set the terms for a post.
1830 * @uses wp_set_object_terms() Sets the tags for the post.
1832 * @param int $post_id Post ID.
1833 * @param string $tags The tags to set for the post, separated by commas.
1834 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
1835 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1837 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
1838 $post_id = (int) $post_id;
1846 $tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
1847 wp_set_object_terms($post_id, $tags, $taxonomy, $append);
1851 * Set categories for a post.
1853 * If the post categories parameter is not set, then the default category is
1858 * @param int $post_ID Post ID.
1859 * @param array $post_categories Optional. List of categories.
1860 * @return bool|mixed
1862 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
1863 $post_ID = (int) $post_ID;
1864 // If $post_categories isn't already an array, make it one:
1865 if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
1866 $post_categories = array(get_option('default_category'));
1867 else if ( 1 == count($post_categories) && '' == $post_categories[0] )
1870 $post_categories = array_map('intval', $post_categories);
1871 $post_categories = array_unique($post_categories);
1873 return wp_set_object_terms($post_ID, $post_categories, 'category');
1877 * Transition the post status of a post.
1879 * Calls hooks to transition post status.
1881 * The first is 'transition_post_status' with new status, old status, and post data.
1883 * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
1884 * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
1887 * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
1888 * parameter and POSTTYPE is post_type post data.
1891 * @link http://codex.wordpress.org/Post_Status_Transitions
1893 * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
1894 * $post if there is a status change.
1895 * @uses do_action() Calls '${old_status}_to_$new_status' on $post if there is a status change.
1896 * @uses do_action() Calls '${new_status}_$post->post_type' on post ID and $post.
1898 * @param string $new_status Transition to this post status.
1899 * @param string $old_status Previous post status.
1900 * @param object $post Post data.
1902 function wp_transition_post_status($new_status, $old_status, $post) {
1903 do_action('transition_post_status', $new_status, $old_status, $post);
1904 do_action("${old_status}_to_$new_status", $post);
1905 do_action("${new_status}_$post->post_type", $post->ID, $post);
1909 // Trackback and ping functions
1913 * Add a URL to those already pung.
1918 * @param int $post_id Post ID.
1919 * @param string $uri Ping URI.
1920 * @return int How many rows were updated.
1922 function add_ping($post_id, $uri) {
1924 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
1925 $pung = trim($pung);
1926 $pung = preg_split('/\s/', $pung);
1928 $new = implode("\n", $pung);
1929 $new = apply_filters('add_ping', $new);
1930 // expected_slashed ($new)
1931 $new = stripslashes($new);
1932 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
1936 * Retrieve enclosures already enclosed for a post.
1941 * @param int $post_id Post ID.
1942 * @return array List of enclosures
1944 function get_enclosed($post_id) {
1945 $custom_fields = get_post_custom( $post_id );
1947 if ( !is_array( $custom_fields ) )
1950 foreach ( $custom_fields as $key => $val ) {
1951 if ( 'enclosure' != $key || !is_array( $val ) )
1953 foreach( $val as $enc ) {
1954 $enclosure = split( "\n", $enc );
1955 $pung[] = trim( $enclosure[ 0 ] );
1958 $pung = apply_filters('get_enclosed', $pung);
1963 * Retrieve URLs already pinged for a post.
1968 * @param int $post_id Post ID.
1971 function get_pung($post_id) {
1973 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
1974 $pung = trim($pung);
1975 $pung = preg_split('/\s/', $pung);
1976 $pung = apply_filters('get_pung', $pung);
1981 * Retrieve URLs that need to be pinged.
1986 * @param int $post_id Post ID
1989 function get_to_ping($post_id) {
1991 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
1992 $to_ping = trim($to_ping);
1993 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
1994 $to_ping = apply_filters('get_to_ping', $to_ping);
1999 * Do trackbacks for a list of URLs.
2003 * @param string $tb_list Comma separated list of URLs
2004 * @param int $post_id Post ID
2006 function trackback_url_list($tb_list, $post_id) {
2007 if ( ! empty( $tb_list ) ) {
2009 $postdata = wp_get_single_post($post_id, ARRAY_A);
2011 // import postdata as variables
2012 extract($postdata, EXTR_SKIP);
2015 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
2017 if (strlen($excerpt) > 255) {
2018 $excerpt = substr($excerpt,0,252) . '...';
2021 $trackback_urls = explode(',', $tb_list);
2022 foreach( (array) $trackback_urls as $tb_url) {
2023 $tb_url = trim($tb_url);
2024 trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
2034 * Get a list of page IDs.
2039 * @return array List of page IDs.
2041 function get_all_page_ids() {
2044 if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
2045 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
2046 wp_cache_add('all_page_ids', $page_ids, 'posts');
2053 * Retrieves page data given a page ID or page object.
2057 * @param mixed $page Page object or page ID. Passed by reference.
2058 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
2059 * @param string $filter How the return value should be filtered.
2060 * @return mixed Page data.
2062 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
2063 if ( empty($page) ) {
2064 if ( isset( $GLOBALS['page'] ) && isset( $GLOBALS['page']->ID ) ) {
2065 return get_post($GLOBALS['page'], $output, $filter);
2072 $the_page = get_post($page, $output, $filter);
2077 * Retrieves a page given its path.
2082 * @param string $page_path Page path
2083 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
2084 * @return mixed Null when complete.
2086 function get_page_by_path($page_path, $output = OBJECT) {
2088 $page_path = rawurlencode(urldecode($page_path));
2089 $page_path = str_replace('%2F', '/', $page_path);
2090 $page_path = str_replace('%20', ' ', $page_path);
2091 $page_paths = '/' . trim($page_path, '/');
2092 $leaf_path = sanitize_title(basename($page_paths));
2093 $page_paths = explode('/', $page_paths);
2095 foreach( (array) $page_paths as $pathdir)
2096 $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
2098 $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 ));
2100 if ( empty($pages) )
2103 foreach ($pages as $page) {
2104 $path = '/' . $leaf_path;
2106 while ($curpage->post_parent != 0) {
2107 $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 ));
2108 $path = '/' . $curpage->post_name . $path;
2111 if ( $path == $full_path )
2112 return get_page($page->ID, $output);
2119 * Retrieve a page given its title.
2124 * @param string $page_title Page title
2125 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
2128 function get_page_by_title($page_title, $output = OBJECT) {
2130 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
2132 return get_page($page, $output);
2138 * Retrieve child pages from list of pages matching page ID.
2140 * Matches against the pages parameter against the page ID. Also matches all
2141 * children for the same to retrieve all children of a page. Does not make any
2142 * SQL queries to get the children.
2146 * @param int $page_id Page ID.
2147 * @param array $pages List of pages' objects.
2150 function &get_page_children($page_id, $pages) {
2151 $page_list = array();
2152 foreach ( (array) $pages as $page ) {
2153 if ( $page->post_parent == $page_id ) {
2154 $page_list[] = $page;
2155 if ( $children = get_page_children($page->ID, $pages) )
2156 $page_list = array_merge($page_list, $children);
2163 * Order the pages with children under parents in a flat list.
2167 * @param array $posts Posts array.
2168 * @param int $parent Parent page ID.
2169 * @return array A list arranged by hierarchy. Children immediately follow their parents.
2171 function get_page_hierarchy($posts, $parent = 0) {
2172 $result = array ( );
2173 if ($posts) { foreach ( (array) $posts as $post) {
2174 if ($post->post_parent == $parent) {
2175 $result[$post->ID] = $post->post_name;
2176 $children = get_page_hierarchy($posts, $post->ID);
2177 $result += $children; //append $children to $result
2184 * Builds URI for a page.
2186 * Sub pages will be in the "directory" under the parent page post name.
2190 * @param int $page_id Page ID.
2191 * @return string Page URI.
2193 function get_page_uri($page_id) {
2194 $page = get_page($page_id);
2195 $uri = $page->post_name;
2197 // A page cannot be it's own parent.
2198 if ( $page->post_parent == $page->ID )
2201 while ($page->post_parent != 0) {
2202 $page = get_page($page->post_parent);
2203 $uri = $page->post_name . "/" . $uri;
2210 * Retrieve a list of pages.
2212 * The defaults that can be overridden are the following: 'child_of',
2213 * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
2214 * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
2219 * @param mixed $args Optional. Array or string of options that overrides defaults.
2220 * @return array List of pages matching defaults or $args
2222 function &get_pages($args = '') {
2226 'child_of' => 0, 'sort_order' => 'ASC',
2227 'sort_column' => 'post_title', 'hierarchical' => 1,
2228 'exclude' => '', 'include' => '',
2229 'meta_key' => '', 'meta_value' => '',
2230 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
2231 'number' => '', 'offset' => 0
2234 $r = wp_parse_args( $args, $defaults );
2235 extract( $r, EXTR_SKIP );
2236 $number = (int) $number;
2237 $offset = (int) $offset;
2240 $key = md5( serialize( compact(array_keys($defaults)) ) );
2241 if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
2242 if ( is_array($cache) && isset( $cache[ $key ] ) ) {
2243 $pages = apply_filters('get_pages', $cache[ $key ], $r );
2248 if ( !is_array($cache) )
2252 if ( !empty($include) ) {
2253 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
2258 $hierarchical = false;
2259 $incpages = preg_split('/[\s,]+/',$include);
2260 if ( count($incpages) ) {
2261 foreach ( $incpages as $incpage ) {
2262 if (empty($inclusions))
2263 $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
2265 $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
2269 if (!empty($inclusions))
2273 if ( !empty($exclude) ) {
2274 $expages = preg_split('/[\s,]+/',$exclude);
2275 if ( count($expages) ) {
2276 foreach ( $expages as $expage ) {
2277 if (empty($exclusions))
2278 $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
2280 $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
2284 if (!empty($exclusions))
2288 if (!empty($authors)) {
2289 $post_authors = preg_split('/[\s,]+/',$authors);
2291 if ( count($post_authors) ) {
2292 foreach ( $post_authors as $post_author ) {
2293 //Do we have an author id or an author login?
2294 if ( 0 == intval($post_author) ) {
2295 $post_author = get_userdatabylogin($post_author);
2296 if ( empty($post_author) )
2298 if ( empty($post_author->ID) )
2300 $post_author = $post_author->ID;
2303 if ( '' == $author_query )
2304 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
2306 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
2308 if ( '' != $author_query )
2309 $author_query = " AND ($author_query)";
2314 $where = "$exclusions $inclusions ";
2315 if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
2316 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
2318 // meta_key and meta_value might be slashed
2319 $meta_key = stripslashes($meta_key);
2320 $meta_value = stripslashes($meta_value);
2321 if ( ! empty( $meta_key ) )
2322 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
2323 if ( ! empty( $meta_value ) )
2324 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
2329 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
2331 $query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
2332 $query .= $author_query;
2333 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
2335 if ( !empty($number) )
2336 $query .= ' LIMIT ' . $offset . ',' . $number;
2338 $pages = $wpdb->get_results($query);
2340 if ( empty($pages) ) {
2341 $pages = apply_filters('get_pages', array(), $r);
2346 update_page_cache($pages);
2348 if ( $child_of || $hierarchical )
2349 $pages = & get_page_children($child_of, $pages);
2351 if ( !empty($exclude_tree) ) {
2354 $exclude = (int) $exclude_tree;
2355 $children = get_page_children($exclude, $pages);
2356 $excludes = array();
2357 foreach ( $children as $child )
2358 $excludes[] = $child->ID;
2359 $excludes[] = $exclude;
2360 $total = count($pages);
2361 for ( $i = 0; $i < $total; $i++ ) {
2362 if ( in_array($pages[$i]->ID, $excludes) )
2367 $cache[ $key ] = $pages;
2368 wp_cache_set( 'get_pages', $cache, 'posts' );
2370 $pages = apply_filters('get_pages', $pages, $r);
2376 // Attachment functions
2380 * Check if the attachment URI is local one and is really an attachment.
2384 * @param string $url URL to check
2385 * @return bool True on success, false on failure.
2387 function is_local_attachment($url) {
2388 if (strpos($url, get_bloginfo('url')) === false)
2390 if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
2392 if ( $id = url_to_postid($url) ) {
2393 $post = & get_post($id);
2394 if ( 'attachment' == $post->post_type )
2401 * Insert an attachment.
2403 * If you set the 'ID' in the $object parameter, it will mean that you are
2404 * updating and attempt to update the attachment. You can also set the
2405 * attachment name or title by setting the key 'post_name' or 'post_title'.
2407 * You can set the dates for the attachment manually by setting the 'post_date'
2408 * and 'post_date_gmt' keys' values.
2410 * By default, the comments will use the default settings for whether the
2411 * comments are allowed. You can close them manually or keep them open by
2412 * setting the value for the 'comment_status' key.
2414 * The $object parameter can have the following:
2415 * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
2416 * 'post_type' - Default is 'post', will be set to attachment. Can not override.
2417 * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
2418 * 'ping_status' - Default is the value in default ping status option. Whether the attachment
2420 * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
2422 * 'menu_order' - Default is 0. The order it is displayed.
2423 * 'to_ping' - Whether to ping.
2424 * 'pinged' - Default is empty string.
2425 * 'post_password' - Default is empty string. The password to access the attachment.
2426 * 'guid' - Global Unique ID for referencing the attachment.
2427 * 'post_content_filtered' - Attachment post content filtered.
2428 * 'post_excerpt' - Attachment excerpt.
2433 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
2434 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
2436 * @param string|array $object Arguments to override defaults.
2437 * @param string $file Optional filename.
2438 * @param int $post_parent Parent post ID.
2439 * @return int Attachment ID.
2441 function wp_insert_attachment($object, $file = false, $parent = 0) {
2442 global $wpdb, $user_ID;
2444 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
2445 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2446 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
2447 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
2449 $object = wp_parse_args($object, $defaults);
2450 if ( !empty($parent) )
2451 $object['post_parent'] = $parent;
2453 $object = sanitize_post($object, 'db');
2455 // export array as variables
2456 extract($object, EXTR_SKIP);
2458 // Make sure we set a valid category
2459 if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
2460 $post_category = array(get_option('default_category'));
2463 if ( empty($post_author) )
2464 $post_author = $user_ID;
2466 $post_type = 'attachment';
2467 $post_status = 'inherit';
2469 // Are we updating or creating?
2470 if ( !empty($ID) ) {
2472 $post_ID = (int) $ID;
2478 // Create a valid post name.
2479 if ( empty($post_name) )
2480 $post_name = sanitize_title($post_title);
2482 $post_name = sanitize_title($post_name);
2484 // expected_slashed ($post_name)
2485 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2487 if ( empty($post_date) )
2488 $post_date = current_time('mysql');
2489 if ( empty($post_date_gmt) )
2490 $post_date_gmt = current_time('mysql', 1);
2492 if ( empty($post_modified) )
2493 $post_modified = $post_date;
2494 if ( empty($post_modified_gmt) )
2495 $post_modified_gmt = $post_date_gmt;
2497 if ( empty($comment_status) ) {
2499 $comment_status = 'closed';
2501 $comment_status = get_option('default_comment_status');
2503 if ( empty($ping_status) )
2504 $ping_status = get_option('default_ping_status');
2506 if ( isset($to_ping) )
2507 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
2511 if ( isset($post_parent) )
2512 $post_parent = (int) $post_parent;
2516 if ( isset($menu_order) )
2517 $menu_order = (int) $menu_order;
2521 if ( !isset($post_password) )
2522 $post_password = '';
2524 if ( ! isset($pinged) )
2527 // expected_slashed (everything!)
2528 $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' ) );
2529 $data = stripslashes_deep( $data );
2532 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
2534 // If there is a suggested ID, use it if not already present
2535 if ( !empty($import_id) ) {
2536 $import_id = (int) $import_id;
2537 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2538 $data['ID'] = $import_id;
2542 $wpdb->insert( $wpdb->posts, $data );
2543 $post_ID = (int) $wpdb->insert_id;
2546 if ( empty($post_name) ) {
2547 $post_name = sanitize_title($post_title, $post_ID);
2548 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
2551 wp_set_post_categories($post_ID, $post_category);
2554 update_attached_file( $post_ID, $file );
2556 clean_post_cache($post_ID);
2559 do_action('edit_attachment', $post_ID);
2561 do_action('add_attachment', $post_ID);
2568 * Delete an attachment.
2570 * Will remove the file also, when the attachment is removed. Removes all post
2571 * meta fields, taxonomy, comments, etc associated with the attachment (except
2576 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
2578 * @param int $postid Attachment ID.
2579 * @return mixed False on failure. Post data on success.
2581 function wp_delete_attachment($postid) {
2584 if ( !$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2587 if ( 'attachment' != $post->post_type )
2590 $meta = wp_get_attachment_metadata( $postid );
2591 $file = get_attached_file( $postid );
2593 do_action('delete_attachment', $postid);
2595 /** @todo Delete for pluggable post taxonomies too */
2596 wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
2598 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2600 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2602 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
2604 $uploadPath = wp_upload_dir();
2606 if ( ! empty($meta['thumb']) ) {
2607 // Don't delete the thumb if another attachment uses it
2608 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)) ) {
2609 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
2610 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
2611 @ unlink( path_join($uploadPath['basedir'], $thumbfile) );
2615 // remove intermediate images if there are any
2616 $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
2617 foreach ( $sizes as $size ) {
2618 if ( $intermediate = image_get_intermediate_size($postid, $size) ) {
2619 $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
2620 @ unlink( path_join($uploadPath['basedir'], $intermediate_file) );
2624 $file = apply_filters('wp_delete_file', $file);
2626 if ( ! empty($file) )
2629 clean_post_cache($postid);
2635 * Retrieve attachment meta field for attachment ID.
2639 * @param int $post_id Attachment ID
2640 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
2641 * @return string|bool Attachment meta field. False on failure.
2643 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
2644 $post_id = (int) $post_id;
2645 if ( !$post =& get_post( $post_id ) )
2648 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
2651 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
2655 * Update metadata for an attachment.
2659 * @param int $post_id Attachment ID.
2660 * @param array $data Attachment data.
2663 function wp_update_attachment_metadata( $post_id, $data ) {
2664 $post_id = (int) $post_id;
2665 if ( !$post =& get_post( $post_id ) )
2668 $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
2670 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
2674 * Retrieve the URL for an attachment.
2678 * @param int $post_id Attachment ID.
2681 function wp_get_attachment_url( $post_id = 0 ) {
2682 $post_id = (int) $post_id;
2683 if ( !$post =& get_post( $post_id ) )
2687 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
2688 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
2689 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
2690 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
2691 elseif ( false !== strpos($file, 'wp-content/uploads') )
2692 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
2694 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
2698 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.
2699 $url = get_the_guid( $post->ID );
2701 if ( 'attachment' != $post->post_type || empty($url) )
2704 return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
2708 * Retrieve thumbnail for an attachment.
2712 * @param int $post_id Attachment ID.
2713 * @return mixed False on failure. Thumbnail file path on success.
2715 function wp_get_attachment_thumb_file( $post_id = 0 ) {
2716 $post_id = (int) $post_id;
2717 if ( !$post =& get_post( $post_id ) )
2719 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
2722 $file = get_attached_file( $post->ID );
2724 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
2725 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
2730 * Retrieve URL for an attachment thumbnail.
2734 * @param int $post_id Attachment ID
2735 * @return string|bool False on failure. Thumbnail URL on success.
2737 function wp_get_attachment_thumb_url( $post_id = 0 ) {
2738 $post_id = (int) $post_id;
2739 if ( !$post =& get_post( $post_id ) )
2741 if ( !$url = wp_get_attachment_url( $post->ID ) )
2744 $sized = image_downsize( $post_id, 'thumbnail' );
2748 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
2751 $url = str_replace(basename($url), basename($thumb), $url);
2753 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
2757 * Check if the attachment is an image.
2761 * @param int $post_id Attachment ID
2764 function wp_attachment_is_image( $post_id = 0 ) {
2765 $post_id = (int) $post_id;
2766 if ( !$post =& get_post( $post_id ) )
2769 if ( !$file = get_attached_file( $post->ID ) )
2772 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
2774 $image_exts = array('jpg', 'jpeg', 'gif', 'png');
2776 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
2782 * Retrieve the icon for a MIME type.
2786 * @param string $mime MIME type
2787 * @return string|bool
2789 function wp_mime_type_icon( $mime = 0 ) {
2790 if ( !is_numeric($mime) )
2791 $icon = wp_cache_get("mime_type_icon_$mime");
2792 if ( empty($icon) ) {
2794 $post_mimes = array();
2795 if ( is_numeric($mime) ) {
2796 $mime = (int) $mime;
2797 if ( $post =& get_post( $mime ) ) {
2798 $post_id = (int) $post->ID;
2799 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
2800 if ( !empty($ext) ) {
2801 $post_mimes[] = $ext;
2802 if ( $ext_type = wp_ext2type( $ext ) )
2803 $post_mimes[] = $ext_type;
2805 $mime = $post->post_mime_type;
2810 $post_mimes[] = $mime;
2813 $icon_files = wp_cache_get('icon_files');
2815 if ( !is_array($icon_files) ) {
2816 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
2817 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
2818 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
2819 $icon_files = array();
2821 $dir = array_shift($keys = array_keys($dirs));
2822 $uri = array_shift($dirs);
2823 if ( $dh = opendir($dir) ) {
2824 while ( false !== $file = readdir($dh) ) {
2825 $file = basename($file);
2826 if ( substr($file, 0, 1) == '.' )
2828 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
2829 if ( is_dir("$dir/$file") )
2830 $dirs["$dir/$file"] = "$uri/$file";
2833 $icon_files["$dir/$file"] = "$uri/$file";
2838 wp_cache_set('icon_files', $icon_files, 600);
2841 // Icon basename - extension = MIME wildcard
2842 foreach ( $icon_files as $file => $uri )
2843 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
2845 if ( ! empty($mime) ) {
2846 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
2847 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
2848 $post_mimes[] = str_replace('/', '_', $mime);
2851 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
2852 $matches['default'] = array('default');
2854 foreach ( $matches as $match => $wilds ) {
2855 if ( isset($types[$wilds[0]])) {
2856 $icon = $types[$wilds[0]];
2857 if ( !is_numeric($mime) )
2858 wp_cache_set("mime_type_icon_$mime", $icon);
2864 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
2868 * Checked for changed slugs for published posts and save old slug.
2870 * The function is used along with form POST data. It checks for the wp-old-slug
2871 * POST field. Will only be concerned with published posts and the slug actually
2874 * If the slug was changed and not already part of the old slugs then it will be
2875 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
2878 * The most logically usage of this function is redirecting changed posts, so
2879 * that those that linked to an changed post will be redirected to the new post.
2883 * @param int $post_id Post ID.
2884 * @return int Same as $post_id
2886 function wp_check_for_changed_slugs($post_id) {
2887 if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
2890 $post = &get_post($post_id);
2892 // we're only concerned with published posts
2893 if ( $post->post_status != 'publish' || $post->post_type != 'post' )
2896 // only bother if the slug has changed
2897 if ( $post->post_name == $_POST['wp-old-slug'] )
2900 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
2902 // if we haven't added this old slug before, add it now
2903 if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
2904 add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
2906 // if the new slug was used previously, delete it from the list
2907 if ( in_array($post->post_name, $old_slugs) )
2908 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
2914 * Retrieve the private post SQL based on capability.
2916 * This function provides a standardized way to appropriately select on the
2917 * post_status of posts/pages. The function will return a piece of SQL code that
2918 * can be added to a WHERE clause; this SQL is constructed to allow all
2919 * published posts, and all private posts to which the user has access.
2921 * It also allows plugins that define their own post type to control the cap by
2922 * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
2923 * the capability the user must have to read the private post type.
2928 * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
2930 * @param string $post_type currently only supports 'post' or 'page'.
2931 * @return string SQL code that can be added to a where clause.
2933 function get_private_posts_cap_sql($post_type) {
2938 if ($post_type == 'post') {
2939 $cap = 'read_private_posts';
2941 } elseif ($post_type == 'page') {
2942 $cap = 'read_private_pages';
2943 // Dunno what it is, maybe plugins have their own post type?
2945 $cap = apply_filters('pub_priv_sql_capability', $cap);
2948 // We don't know what it is, filters don't change anything,
2949 // so set the SQL up to return nothing.
2954 $sql = '(post_status = \'publish\'';
2956 if (current_user_can($cap)) {
2957 // Does the user have the capability to view private posts? Guess so.
2958 $sql .= ' OR post_status = \'private\'';
2959 } elseif (is_user_logged_in()) {
2960 // Users can view their own private posts.
2961 $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
2970 * Retrieve the date the the last post was published.
2972 * The server timezone is the default and is the difference between GMT and
2973 * server time. The 'blog' value is the date when the last post was posted. The
2974 * 'gmt' is when the last post was posted in GMT formatted date.
2980 * @uses apply_filters() Calls 'get_lastpostdate' filter
2982 * @global mixed $cache_lastpostdate Stores the last post date
2983 * @global mixed $pagenow The current page being viewed
2985 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
2986 * @return string The date of the last post.
2988 function get_lastpostdate($timezone = 'server') {
2989 global $cache_lastpostdate, $wpdb, $blog_id;
2990 $add_seconds_server = date('Z');
2991 if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
2992 switch(strtolower($timezone)) {
2994 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
2997 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
3000 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
3003 $cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
3005 $lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
3007 return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
3011 * Retrieve last post modified date depending on timezone.
3013 * The server timezone is the default and is the difference between GMT and
3014 * server time. The 'blog' value is just when the last post was modified. The
3015 * 'gmt' is when the last post was modified in GMT time.
3020 * @uses apply_filters() Calls 'get_lastpostmodified' filter
3022 * @global mixed $cache_lastpostmodified Stores the date the last post was modified
3024 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
3025 * @return string The date the post was last modified.
3027 function get_lastpostmodified($timezone = 'server') {
3028 global $cache_lastpostmodified, $wpdb, $blog_id;
3029 $add_seconds_server = date('Z');
3030 if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
3031 switch(strtolower($timezone)) {
3033 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3036 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3039 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3042 $lastpostdate = get_lastpostdate($timezone);
3043 if ( $lastpostdate > $lastpostmodified ) {
3044 $lastpostmodified = $lastpostdate;
3046 $cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
3048 $lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
3050 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
3054 * Updates posts in cache.
3056 * @usedby update_page_cache() Aliased by this function.
3058 * @package WordPress
3062 * @param array $posts Array of post objects
3064 function update_post_cache(&$posts) {
3068 foreach ( $posts as $post )
3069 wp_cache_add($post->ID, $post, 'posts');
3073 * Will clean the post in the cache.
3075 * Cleaning means delete from the cache of the post. Will call to clean the term
3076 * object cache associated with the post ID.
3078 * clean_post_cache() will call itself recursively for each child post.
3080 * This function not run if $_wp_suspend_cache_invalidation is not empty. See
3081 * wp_suspend_cache_invalidation().
3083 * @package WordPress
3087 * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
3089 * @param int $id The Post ID in the cache to clean
3091 function clean_post_cache($id) {
3092 global $_wp_suspend_cache_invalidation, $wpdb;
3094 if ( !empty($_wp_suspend_cache_invalidation) )
3099 wp_cache_delete($id, 'posts');
3100 wp_cache_delete($id, 'post_meta');
3102 clean_object_term_cache($id, 'post');
3104 wp_cache_delete( 'wp_get_archives', 'general' );
3106 do_action('clean_post_cache', $id);
3108 if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
3109 foreach( $children as $cid )
3110 clean_post_cache( $cid );
3115 * Alias of update_post_cache().
3117 * @see update_post_cache() Posts and pages are the same, alias is intentional
3119 * @package WordPress
3123 * @param array $pages list of page objects
3125 function update_page_cache(&$pages) {
3126 update_post_cache($pages);
3130 * Will clean the page in the cache.
3132 * Clean (read: delete) page from cache that matches $id. Will also clean cache
3133 * associated with 'all_page_ids' and 'get_pages'.
3135 * @package WordPress
3139 * @uses do_action() Will call the 'clean_page_cache' hook action.
3141 * @param int $id Page ID to clean
3143 function clean_page_cache($id) {
3144 clean_post_cache($id);
3146 wp_cache_delete( 'all_page_ids', 'posts' );
3147 wp_cache_delete( 'get_pages', 'posts' );
3149 do_action('clean_page_cache', $id);
3153 * Call major cache updating functions for list of Post objects.
3155 * @package WordPress
3160 * @uses update_post_cache()
3161 * @uses update_object_term_cache()
3162 * @uses update_postmeta_cache()
3164 * @param array $posts Array of Post objects
3166 function update_post_caches(&$posts) {
3167 // No point in doing all this work if we didn't match any posts.
3171 update_post_cache($posts);
3173 $post_ids = array();
3175 for ($i = 0; $i < count($posts); $i++)
3176 $post_ids[] = $posts[$i]->ID;
3178 update_object_term_cache($post_ids, 'post');
3180 update_postmeta_cache($post_ids);
3184 * Updates metadata cache for list of post IDs.
3186 * Performs SQL query to retrieve the metadata for the post IDs and updates the
3187 * metadata cache for the posts. Therefore, the functions, which call this
3188 * function, do not need to perform SQL queries on their own.
3190 * @package WordPress
3196 * @param array $post_ids List of post IDs.
3197 * @return bool|array Returns false if there is nothing to update or an array of metadata.
3199 function update_postmeta_cache($post_ids) {
3202 if ( empty( $post_ids ) )
3205 if ( !is_array($post_ids) ) {
3206 $post_ids = preg_replace('|[^0-9,]|', '', $post_ids);
3207 $post_ids = explode(',', $post_ids);
3210 $post_ids = array_map('intval', $post_ids);
3213 foreach ( (array) $post_ids as $id ) {
3214 if ( false === wp_cache_get($id, 'post_meta') )
3218 if ( empty( $ids ) )
3221 // Get post-meta info
3222 $id_list = join(',', $ids);
3224 if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN ($id_list)", ARRAY_A) ) {
3225 foreach ( (array) $meta_list as $metarow) {
3226 $mpid = (int) $metarow['post_id'];
3227 $mkey = $metarow['meta_key'];
3228 $mval = $metarow['meta_value'];
3230 // Force subkeys to be array type:
3231 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
3232 $cache[$mpid] = array();
3233 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
3234 $cache[$mpid][$mkey] = array();
3236 // Add a value to the current pid/key:
3237 $cache[$mpid][$mkey][] = $mval;
3241 foreach ( (array) $ids as $id ) {
3242 if ( ! isset($cache[$id]) )
3243 $cache[$id] = array();
3246 foreach ( (array) array_keys($cache) as $post)
3247 wp_cache_set($post, $cache[$post], 'post_meta');
3257 * Hook for managing future post transitions to published.
3262 * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
3263 * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
3265 * @param string $new_status New post status
3266 * @param string $old_status Previous post status
3267 * @param object $post Object type containing the post information
3269 function _transition_post_status($new_status, $old_status, $post) {
3272 if ( $old_status != 'publish' && $new_status == 'publish' ) {
3273 // Reset GUID if transitioning to publish and it is empty
3274 if ( '' == get_the_guid($post->ID) )
3275 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
3276 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
3279 // Always clears the hook in case the post status bounced from future to draft.
3280 wp_clear_scheduled_hook('publish_future_post', $post->ID);
3284 * Hook used to schedule publication for a post marked for the future.
3286 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
3291 * @param int $deprecated Not Used. Can be set to null.
3292 * @param object $post Object type containing the post information
3294 function _future_post_hook($deprecated = '', $post) {
3295 wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
3296 wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
3300 * Hook to schedule pings and enclosures when a post is published.
3305 * @uses XMLRPC_REQUEST and APP_REQUEST constants.
3306 * @uses do_action() Calls 'xmlprc_publish_post' on post ID if XMLRPC_REQUEST is defined.
3307 * @uses do_action() Calls 'app_publish_post' on post ID if APP_REQUEST is defined.
3309 * @param int $post_id The ID in the database table of the post being published
3311 function _publish_post_hook($post_id) {
3314 if ( defined('XMLRPC_REQUEST') )
3315 do_action('xmlrpc_publish_post', $post_id);
3316 if ( defined('APP_REQUEST') )
3317 do_action('app_publish_post', $post_id);
3319 if ( defined('WP_IMPORTING') )
3322 $data = array( 'post_id' => $post_id, 'meta_value' => '1' );
3323 if ( get_option('default_pingback_flag') )
3324 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
3325 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
3326 wp_schedule_single_event(time(), 'do_pings');
3330 * Hook used to prevent page/post cache and rewrite rules from staying dirty.
3332 * Does two things. If the post is a page and has a template then it will
3333 * update/add that template to the meta. For both pages and posts, it will clean
3334 * the post cache to make sure that the cache updates to the changes done
3335 * recently. For pages, the rewrite rules of WordPress are flushed to allow for
3338 * The $post parameter, only uses 'post_type' property and 'page_template'
3343 * @uses $wp_rewrite Flushes Rewrite Rules.
3345 * @param int $post_id The ID in the database table for the $post
3346 * @param object $post Object type containing the post information
3348 function _save_post_hook($post_id, $post) {
3349 if ( $post->post_type == 'page' ) {
3350 clean_page_cache($post_id);
3351 // Avoid flushing rules for every post during import.
3352 if ( !defined('WP_IMPORTING') ) {
3354 $wp_rewrite->flush_rules(false);
3357 clean_post_cache($post_id);
3362 * Retrieve post ancestors and append to post ancestors property.
3364 * Will only retrieve ancestors once, if property is already set, then nothing
3365 * will be done. If there is not a parent post, or post ID and post parent ID
3366 * are the same then nothing will be done.
3368 * The parameter is passed by reference, so nothing needs to be returned. The
3369 * property will be updated and can be referenced after the function is
3370 * complete. The post parent will be an ancestor and the parent of the post
3371 * parent will be an ancestor. There will only be two ancestors at the most.
3377 * @param object $_post Post data.
3378 * @return null When nothing needs to be done.
3380 function _get_post_ancestors(&$_post) {
3383 if ( isset($_post->ancestors) )
3386 $_post->ancestors = array();
3388 if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
3391 $id = $_post->ancestors[] = $_post->post_parent;
3392 while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
3393 if ( $id == $ancestor )
3395 $id = $_post->ancestors[] = $ancestor;
3400 * Determines which fields of posts are to be saved in revisions.
3402 * Does two things. If passed a post *array*, it will return a post array ready
3403 * to be insterted into the posts table as a post revision. Otherwise, returns
3404 * an array whose keys are the post fields to be saved for post revisions.
3406 * @package WordPress
3407 * @subpackage Post_Revisions
3410 * @uses apply_filters() Calls '_wp_post_revision_fields' on 'title', 'content' and 'excerpt' fields.
3412 * @param array $post Optional a post array to be processed for insertion as a post revision.
3413 * @param bool $autosave optional Is the revision an autosave?
3414 * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
3416 function _wp_post_revision_fields( $post = null, $autosave = false ) {
3417 static $fields = false;
3420 // Allow these to be versioned
3422 'post_title' => __( 'Title' ),
3423 'post_content' => __( 'Content' ),
3424 'post_excerpt' => __( 'Excerpt' ),
3428 $fields = apply_filters( '_wp_post_revision_fields', $fields );
3430 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
3431 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
3432 unset( $fields[$protect] );
3435 if ( !is_array($post) )
3439 foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
3440 $return[$field] = $post[$field];
3442 $return['post_parent'] = $post['ID'];
3443 $return['post_status'] = 'inherit';
3444 $return['post_type'] = 'revision';
3445 $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
3446 $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
3447 $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
3453 * Saves an already existing post as a post revision.
3455 * Typically used immediately prior to post updates.
3457 * @package WordPress
3458 * @subpackage Post_Revisions
3461 * @uses _wp_put_post_revision()
3463 * @param int $post_id The ID of the post to save as a revision.
3464 * @return mixed Null or 0 if error, new revision ID, if success.
3466 function wp_save_post_revision( $post_id ) {
3467 // We do autosaves manually with wp_create_post_autosave()
3468 if ( @constant( 'DOING_AUTOSAVE' ) )
3471 // WP_POST_REVISIONS = 0, false
3472 if ( !constant('WP_POST_REVISIONS') )
3475 if ( !$post = get_post( $post_id, ARRAY_A ) )
3478 if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
3481 $return = _wp_put_post_revision( $post );
3483 // WP_POST_REVISIONS = true (default), -1
3484 if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
3487 // all revisions and (possibly) one autosave
3488 $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
3490 // WP_POST_REVISIONS = (int) (# of autasaves to save)
3491 $delete = count($revisions) - WP_POST_REVISIONS;
3496 $revisions = array_slice( $revisions, 0, $delete );
3498 for ( $i = 0; isset($revisions[$i]); $i++ ) {
3499 if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
3501 wp_delete_post_revision( $revisions[$i]->ID );
3508 * Retrieve the autosaved data of the specified post.
3510 * Returns a post object containing the information that was autosaved for the
3513 * @package WordPress
3514 * @subpackage Post_Revisions
3517 * @param int $post_id The post ID.
3518 * @return object|bool The autosaved data or false on failure or when no autosave exists.
3520 function wp_get_post_autosave( $post_id ) {
3522 if ( !$post = get_post( $post_id ) )
3526 'name' => "{$post->ID}-autosave",
3527 'post_parent' => $post->ID,
3528 'post_type' => 'revision',
3529 'post_status' => 'inherit'
3532 // Use WP_Query so that the result gets cached
3533 $autosave_query = new WP_Query;
3535 add_action( 'parse_query', '_wp_get_post_autosave_hack' );
3536 $autosave = $autosave_query->query( $q );
3537 remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
3539 if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
3540 return $autosave[0];
3546 * Internally used to hack WP_Query into submission.
3548 * @package WordPress
3549 * @subpackage Post_Revisions
3552 * @param object $query WP_Query object
3554 function _wp_get_post_autosave_hack( $query ) {
3555 $query->is_single = false;
3559 * Determines if the specified post is a revision.
3561 * @package WordPress
3562 * @subpackage Post_Revisions
3565 * @param int|object $post Post ID or post object.
3566 * @return bool|int False if not a revision, ID of revision's parent otherwise.
3568 function wp_is_post_revision( $post ) {
3569 if ( !$post = wp_get_post_revision( $post ) )
3571 return (int) $post->post_parent;
3575 * Determines if the specified post is an autosave.
3577 * @package WordPress
3578 * @subpackage Post_Revisions
3581 * @param int|object $post Post ID or post object.
3582 * @return bool|int False if not a revision, ID of autosave's parent otherwise
3584 function wp_is_post_autosave( $post ) {
3585 if ( !$post = wp_get_post_revision( $post ) )
3587 if ( "{$post->post_parent}-autosave" !== $post->post_name )
3589 return (int) $post->post_parent;
3593 * Inserts post data into the posts table as a post revision.
3595 * @package WordPress
3596 * @subpackage Post_Revisions
3599 * @uses wp_insert_post()
3601 * @param int|object|array $post Post ID, post object OR post array.
3602 * @param bool $autosave Optional. Is the revision an autosave?
3603 * @return mixed Null or 0 if error, new revision ID if success.
3605 function _wp_put_post_revision( $post = null, $autosave = false ) {
3606 if ( is_object($post) )
3607 $post = get_object_vars( $post );
3608 elseif ( !is_array($post) )
3609 $post = get_post($post, ARRAY_A);
3610 if ( !$post || empty($post['ID']) )
3613 if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
3614 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
3616 $post = _wp_post_revision_fields( $post, $autosave );
3617 $post = add_magic_quotes($post); //since data is from db
3619 $revision_id = wp_insert_post( $post );
3620 if ( is_wp_error($revision_id) )
3621 return $revision_id;
3624 do_action( '_wp_put_post_revision', $revision_id );
3625 return $revision_id;
3629 * Gets a post revision.
3631 * @package WordPress
3632 * @subpackage Post_Revisions
3637 * @param int|object $post Post ID or post object
3638 * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
3639 * @param string $filter Optional sanitation filter. @see sanitize_post()
3640 * @return mixed Null if error or post object if success
3642 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
3644 if ( !$revision = get_post( $post, OBJECT, $filter ) )
3646 if ( 'revision' !== $revision->post_type )
3649 if ( $output == OBJECT ) {
3651 } elseif ( $output == ARRAY_A ) {
3652 $_revision = get_object_vars($revision);
3654 } elseif ( $output == ARRAY_N ) {
3655 $_revision = array_values(get_object_vars($revision));
3663 * Restores a post to the specified revision.
3665 * Can restore a past revision using all fields of the post revision, or only selected fields.
3667 * @package WordPress
3668 * @subpackage Post_Revisions
3671 * @uses wp_get_post_revision()
3672 * @uses wp_update_post()
3673 * @uses do_action() Calls 'wp_restore_post_revision' on post ID and revision ID if wp_update_post()
3676 * @param int|object $revision_id Revision ID or revision object.
3677 * @param array $fields Optional. What fields to restore from. Defaults to all.
3678 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3680 function wp_restore_post_revision( $revision_id, $fields = null ) {
3681 if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
3684 if ( !is_array( $fields ) )
3685 $fields = array_keys( _wp_post_revision_fields() );
3688 foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
3689 $update[$field] = $revision[$field];
3694 $update['ID'] = $revision['post_parent'];
3696 $update = add_magic_quotes( $update ); //since data is from db
3698 $post_id = wp_update_post( $update );
3699 if ( is_wp_error( $post_id ) )
3703 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
3709 * Deletes a revision.
3711 * Deletes the row from the posts table corresponding to the specified revision.
3713 * @package WordPress
3714 * @subpackage Post_Revisions
3717 * @uses wp_get_post_revision()
3718 * @uses wp_delete_post()
3720 * @param int|object $revision_id Revision ID or revision object.
3721 * @param array $fields Optional. What fields to restore from. Defaults to all.
3722 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3724 function wp_delete_post_revision( $revision_id ) {
3725 if ( !$revision = wp_get_post_revision( $revision_id ) )
3728 $delete = wp_delete_post( $revision->ID );
3729 if ( is_wp_error( $delete ) )
3733 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
3739 * Returns all revisions of specified post.
3741 * @package WordPress
3742 * @subpackage Post_Revisions
3745 * @uses get_children()
3747 * @param int|object $post_id Post ID or post object
3748 * @return array empty if no revisions
3750 function wp_get_post_revisions( $post_id = 0, $args = null ) {
3751 if ( !constant('WP_POST_REVISIONS') )
3753 if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
3756 $defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
3757 $args = wp_parse_args( $args, $defaults );
3758 $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
3760 if ( !$revisions = get_children( $args ) )
3765 function _set_preview($post) {
3767 if ( ! is_object($post) )
3770 $preview = wp_get_post_autosave($post->ID);
3772 if ( ! is_object($preview) )
3775 $preview = sanitize_post($preview);
3777 $post->post_content = $preview->post_content;
3778 $post->post_title = $preview->post_title;
3779 $post->post_excerpt = $preview->post_excerpt;
3784 function _show_post_preview() {
3786 if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
3787 $id = (int) $_GET['preview_id'];
3789 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
3790 wp_die( __('You do not have permission to preview drafts.') );
3792 add_filter('the_preview', '_set_preview');