| [ Index ] |
PHP Cross Reference of Wordpress 2.7.1 |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Post functions and post utility function. 4 * 5 * @package WordPress 6 * @subpackage Post 7 * @since 1.5.0 8 */ 9 10 /** 11 * Retrieve attached file path based on attachment ID. 12 * 13 * You can optionally send it through the 'get_attached_file' filter, but by 14 * default it will just return the file path unfiltered. 15 * 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. 20 * 21 * @since 2.0.0 22 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID. 23 * 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. 27 */ 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"; 33 if ( $unfiltered ) 34 return $file; 35 return apply_filters( 'get_attached_file', $file, $attachment_id ); 36 } 37 38 /** 39 * Update attachment file path based on attachment ID. 40 * 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. 43 * 44 * @since 2.1.0 45 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID. 46 * 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. 50 */ 51 function update_attached_file( $attachment_id, $file ) { 52 if ( !get_post( $attachment_id ) ) 53 return false; 54 55 $file = apply_filters( 'update_attached_file', $file, $attachment_id ); 56 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, '/'); 62 } 63 } 64 65 return update_post_meta( $attachment_id, '_wp_attached_file', $file ); 66 } 67 68 /** 69 * Retrieve all children of the post parent ID. 70 * 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. 77 * 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. 83 * 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. 90 * 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. 96 * 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. 101 * 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. 106 * 107 * @see get_posts() Has additional arguments that can be replaced. 108 * @internal Claims made in the long description might be inaccurate. 109 * 110 * @since 2.0.0 111 * 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. 115 */ 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 ); 120 } else { 121 return false; 122 } 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); 127 } 128 129 $defaults = array( 130 'numberposts' => -1, 'post_type' => 'any', 131 'post_status' => 'any', 'post_parent' => 0, 132 ); 133 134 $r = wp_parse_args( $args, $defaults ); 135 136 $children = get_posts( $r ); 137 if ( !$children ) { 138 $kids = false; 139 return $kids; 140 } 141 142 update_post_cache($children); 143 144 foreach ( $children as $key => $child ) 145 $kids[$child->ID] =& $children[$key]; 146 147 if ( $output == OBJECT ) { 148 return $kids; 149 } elseif ( $output == ARRAY_A ) { 150 foreach ( (array) $kids as $kid ) 151 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]); 152 return $weeuns; 153 } elseif ( $output == ARRAY_N ) { 154 foreach ( (array) $kids as $kid ) 155 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID])); 156 return $babes; 157 } else { 158 return $kids; 159 } 160 } 161 162 /** 163 * Get extended entry info (<!--more-->). 164 * 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 167 * referenced. 168 * 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. 172 * 173 * @since 1.0.0 174 * 175 * @param string $post Post content. 176 * @return array Post before ('main') and after ('extended'). 177 */ 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); 182 } else { 183 $main = $post; 184 $extended = ''; 185 } 186 187 // Strip leading and trailing whitespace 188 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main); 189 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended); 190 191 return array('main' => $main, 'extended' => $extended); 192 } 193 194 /** 195 * Retrieves post data given a post ID or post object. 196 * 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. 199 * 200 * @since 1.5.1 201 * @uses $wpdb 202 * @link http://codex.wordpress.org/Function_Reference/get_post 203 * 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 208 */ 209 function &get_post(&$post, $output = OBJECT, $filter = 'raw') { 210 global $wpdb; 211 $null = null; 212 213 if ( empty($post) ) { 214 if ( isset($GLOBALS['post']) ) 215 $_post = & $GLOBALS['post']; 216 else 217 return $null; 218 } elseif ( is_object($post) && empty($post->filter) ) { 219 _get_post_ancestors($post); 220 wp_cache_add($post->ID, $post, 'posts'); 221 $_post = &$post; 222 } else { 223 if ( is_object($post) ) 224 $post = $post->ID; 225 $post = (int) $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)); 228 if ( ! $_post ) 229 return $null; 230 _get_post_ancestors($_post); 231 wp_cache_add($_post->ID, $_post, 'posts'); 232 } 233 } 234 235 $_post = sanitize_post($_post, $filter); 236 237 if ( $output == OBJECT ) { 238 return $_post; 239 } elseif ( $output == ARRAY_A ) { 240 $__post = get_object_vars($_post); 241 return $__post; 242 } elseif ( $output == ARRAY_N ) { 243 $__post = array_values(get_object_vars($_post)); 244 return $__post; 245 } else { 246 return $_post; 247 } 248 } 249 250 /** 251 * Retrieve ancestors of a post. 252 * 253 * @since 2.5.0 254 * 255 * @param int|object $post Post ID or post object 256 * @return array Ancestor IDs or empty array if none are found. 257 */ 258 function get_post_ancestors($post) { 259 $post = get_post($post); 260 261 if ( !empty($post->ancestors) ) 262 return $post->ancestors; 263 264 return array(); 265 } 266 267 /** 268 * Retrieve data from a post field based on Post ID. 269 * 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. 272 * 273 * The context values are based off of the taxonomy filter functions and 274 * supported values are found within those functions. 275 * 276 * @since 2.3.0 277 * @uses sanitize_post_field() See for possible $context values. 278 * 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 283 */ 284 function get_post_field( $field, $post, $context = 'display' ) { 285 $post = (int) $post; 286 $post = get_post( $post ); 287 288 if ( is_wp_error($post) ) 289 return $post; 290 291 if ( !is_object($post) ) 292 return ''; 293 294 if ( !isset($post->$field) ) 295 return ''; 296 297 return sanitize_post_field($field, $post->$field, $post->ID, $context); 298 } 299 300 /** 301 * Retrieve the mime type of an attachment based on the ID. 302 * 303 * This function can be used with any post type, but it makes more sense with 304 * attachments. 305 * 306 * @since 2.0.0 307 * 308 * @param int $ID Optional. Post ID. 309 * @return bool|string False on failure or returns the mime type 310 */ 311 function get_post_mime_type($ID = '') { 312 $post = & get_post($ID); 313 314 if ( is_object($post) ) 315 return $post->post_mime_type; 316 317 return false; 318 } 319 320 /** 321 * Retrieve the post status based on the Post ID. 322 * 323 * If the post ID is of an attachment, then the parent post status will be given 324 * instead. 325 * 326 * @since 2.0.0 327 * 328 * @param int $ID Post ID 329 * @return string|bool Post status or false on failure. 330 */ 331 function get_post_status($ID = '') { 332 $post = get_post($ID); 333 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); 337 else 338 return $post->post_status; 339 } 340 341 return false; 342 } 343 344 /** 345 * Retrieve all of the WordPress supported post statuses. 346 * 347 * Posts have a limited set of valid status values, this provides the 348 * post_status values and descriptions. 349 * 350 * @since 2.5.0 351 * 352 * @return array List of post statuses. 353 */ 354 function get_post_statuses( ) { 355 $status = array( 356 'draft' => __('Draft'), 357 'pending' => __('Pending Review'), 358 'private' => __('Private'), 359 'publish' => __('Published') 360 ); 361 362 return $status; 363 } 364 365 /** 366 * Retrieve all of the WordPress support page statuses. 367 * 368 * Pages have a limited set of valid status values, this provides the 369 * post_status values and descriptions. 370 * 371 * @since 2.5.0 372 * 373 * @return array List of page statuses. 374 */ 375 function get_page_statuses( ) { 376 $status = array( 377 'draft' => __('Draft'), 378 'private' => __('Private'), 379 'publish' => __('Published') 380 ); 381 382 return $status; 383 } 384 385 /** 386 * Retrieve the post type of the current post or of a given post. 387 * 388 * @since 2.1.0 389 * 390 * @uses $wpdb 391 * @uses $posts The Loop post global 392 * 393 * @param mixed $post Optional. Post object or post ID. 394 * @return bool|string post type or false on failure. 395 */ 396 function get_post_type($post = false) { 397 global $posts; 398 399 if ( false === $post ) 400 $post = $posts[0]; 401 elseif ( (int) $post ) 402 $post = get_post($post, OBJECT); 403 404 if ( is_object($post) ) 405 return $post->post_type; 406 407 return false; 408 } 409 410 /** 411 * Updates the post type for the post ID. 412 * 413 * The page or post cache will be cleaned for the post ID. 414 * 415 * @since 2.5.0 416 * 417 * @uses $wpdb 418 * 419 * @param int $post_id Post ID to change post type. Not actually optional. 420 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to name a few. 421 * @return int Amount of rows changed. Should be 1 for success and 0 for failure. 422 */ 423 function set_post_type( $post_id = 0, $post_type = 'post' ) { 424 global $wpdb; 425 426 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db'); 427 $return = $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_type = %s WHERE ID = %d", $post_type, $post_id) ); 428 429 if ( 'page' == $post_type ) 430 clean_page_cache($post_id); 431 else 432 clean_post_cache($post_id); 433 434 return $return; 435 } 436 437 /** 438 * Retrieve list of latest posts or posts matching criteria. 439 * 440 * The defaults are as follows: 441 * 'numberposts' - Default is 5. Total number of posts to retrieve. 442 * 'offset' - Default is 0. See {@link WP_Query::query()} for more. 443 * 'category' - What category to pull the posts from. 444 * 'orderby' - Default is 'post_date'. How to order the posts. 445 * 'order' - Default is 'DESC'. The order to retrieve the posts. 446 * 'include' - See {@link WP_Query::query()} for more. 447 * 'exclude' - See {@link WP_Query::query()} for more. 448 * 'meta_key' - See {@link WP_Query::query()} for more. 449 * 'meta_value' - See {@link WP_Query::query()} for more. 450 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few. 451 * 'post_parent' - The parent of the post or post type. 452 * 'post_status' - Default is 'published'. Post status to retrieve. 453 * 454 * @since 1.2.0 455 * @uses $wpdb 456 * @uses WP_Query::query() See for more default arguments and information. 457 * @link http://codex.wordpress.org/Template_Tags/get_posts 458 * 459 * @param array $args Optional. Override defaults. 460 * @return array List of posts. 461 */ 462 function get_posts($args = null) { 463 $defaults = array( 464 'numberposts' => 5, 'offset' => 0, 465 'category' => 0, 'orderby' => 'post_date', 466 'order' => 'DESC', 'include' => '', 467 'exclude' => '', 'meta_key' => '', 468 'meta_value' =>'', 'post_type' => 'post', 469 'suppress_filters' => true 470 ); 471 472 $r = wp_parse_args( $args, $defaults ); 473 if ( empty( $r['post_status'] ) ) 474 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish'; 475 if ( ! empty($r['numberposts']) ) 476 $r['posts_per_page'] = $r['numberposts']; 477 if ( ! empty($r['category']) ) 478 $r['cat'] = $r['category']; 479 if ( ! empty($r['include']) ) { 480 $incposts = preg_split('/[\s,]+/',$r['include']); 481 $r['posts_per_page'] = count($incposts); // only the number of posts included 482 $r['post__in'] = $incposts; 483 } elseif ( ! empty($r['exclude']) ) 484 $r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']); 485 486 $r['caller_get_posts'] = true; 487 488 $get_posts = new WP_Query; 489 return $get_posts->query($r); 490 491 } 492 493 // 494 // Post meta functions 495 // 496 497 /** 498 * Add meta data field to a post. 499 * 500 * Post meta data is called "Custom Fields" on the Administration Panels. 501 * 502 * @since 1.5.0 503 * @uses $wpdb 504 * @link http://codex.wordpress.org/Function_Reference/add_post_meta 505 * 506 * @param int $post_id Post ID. 507 * @param string $key Metadata name. 508 * @param mixed $value Metadata value. 509 * @param bool $unique Optional, default is false. Whether the same key should not be added. 510 * @return bool False for failure. True for success. 511 */ 512 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) { 513 global $wpdb; 514 515 // make sure meta is added to the post, not a revision 516 if ( $the_post = wp_is_post_revision($post_id) ) 517 $post_id = $the_post; 518 519 // expected_slashed ($meta_key) 520 $meta_key = stripslashes($meta_key); 521 522 if ( $unique && $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) 523 return false; 524 525 $meta_value = maybe_serialize( stripslashes_deep($meta_value) ); 526 527 $wpdb->insert( $wpdb->postmeta, compact( 'post_id', 'meta_key', 'meta_value' ) ); 528 529 wp_cache_delete($post_id, 'post_meta'); 530 531 return true; 532 } 533 534 /** 535 * Remove metadata matching criteria from a post. 536 * 537 * You can match based on the key, or key and value. Removing based on key and 538 * value, will keep from removing duplicate metadata with the same key. It also 539 * allows removing all metadata matching key, if needed. 540 * 541 * @since 1.5.0 542 * @uses $wpdb 543 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta 544 * 545 * @param int $post_id post ID 546 * @param string $meta_key Metadata name. 547 * @param mixed $meta_value Optional. Metadata value. 548 * @return bool False for failure. True for success. 549 */ 550 function delete_post_meta($post_id, $meta_key, $meta_value = '') { 551 global $wpdb; 552 553 // make sure meta is added to the post, not a revision 554 if ( $the_post = wp_is_post_revision($post_id) ) 555 $post_id = $the_post; 556 557 // expected_slashed ($meta_key, $meta_value) 558 $meta_key = stripslashes( $meta_key ); 559 $meta_value = maybe_serialize( stripslashes_deep($meta_value) ); 560 561 if ( empty( $meta_value ) ) 562 $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) ); 563 else 564 $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) ); 565 566 if ( !$meta_id ) 567 return false; 568 569 if ( empty( $meta_value ) ) 570 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) ); 571 else 572 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) ); 573 574 wp_cache_delete($post_id, 'post_meta'); 575 576 return true; 577 } 578 579 /** 580 * Retrieve post meta field for a post. 581 * 582 * @since 1.5.0 583 * @uses $wpdb 584 * @link http://codex.wordpress.org/Function_Reference/get_post_meta 585 * 586 * @param int $post_id Post ID. 587 * @param string $key The meta key to retrieve. 588 * @param bool $single Whether to return a single value. 589 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true. 590 */ 591 function get_post_meta($post_id, $key, $single = false) { 592 $post_id = (int) $post_id; 593 594 $meta_cache = wp_cache_get($post_id, 'post_meta'); 595 596 if ( !$meta_cache ) { 597 update_postmeta_cache($post_id); 598 $meta_cache = wp_cache_get($post_id, 'post_meta'); 599 } 600 601 if ( isset($meta_cache[$key]) ) { 602 if ( $single ) { 603 return maybe_unserialize( $meta_cache[$key][0] ); 604 } else { 605 return array_map('maybe_unserialize', $meta_cache[$key]); 606 } 607 } 608 609 return ''; 610 } 611 612 /** 613 * Update post meta field based on post ID. 614 * 615 * Use the $prev_value parameter to differentiate between meta fields with the 616 * same key and post ID. 617 * 618 * If the meta field for the post does not exist, it will be added. 619 * 620 * @since 1.5 621 * @uses $wpdb 622 * @link http://codex.wordpress.org/Function_Reference/update_post_meta 623 * 624 * @param int $post_id Post ID. 625 * @param string $key Metadata key. 626 * @param mixed $value Metadata value. 627 * @param mixed $prev_value Optional. Previous value to check before removing. 628 * @return bool False on failure, true if success. 629 */ 630 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') { 631 global $wpdb; 632 633 // make sure meta is added to the post, not a revision 634 if ( $the_post = wp_is_post_revision($post_id) ) 635 $post_id = $the_post; 636 637 // expected_slashed ($meta_key) 638 $meta_key = stripslashes($meta_key); 639 640 if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) { 641 return add_post_meta($post_id, $meta_key, $meta_value); 642 } 643 644 $meta_value = maybe_serialize( stripslashes_deep($meta_value) ); 645 646 $data = compact( 'meta_value' ); 647 $where = compact( 'meta_key', 'post_id' ); 648 649 if ( !empty( $prev_value ) ) { 650 $prev_value = maybe_serialize($prev_value); 651 $where['meta_value'] = $prev_value; 652 } 653 654 $wpdb->update( $wpdb->postmeta, $data, $where ); 655 wp_cache_delete($post_id, 'post_meta'); 656 return true; 657 } 658 659 /** 660 * Delete everything from post meta matching meta key. 661 * 662 * @since 2.3.0 663 * @uses $wpdb 664 * 665 * @param string $post_meta_key Key to search for when deleting. 666 * @return bool Whether the post meta key was deleted from the database 667 */ 668 function delete_post_meta_by_key($post_meta_key) { 669 global $wpdb; 670 if ( $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key)) ) { 671 /** @todo Get post_ids and delete cache */ 672 // wp_cache_delete($post_id, 'post_meta'); 673 return true; 674 } 675 return false; 676 } 677 678 /** 679 * Retrieve post meta fields, based on post ID. 680 * 681 * The post meta fields are retrieved from the cache, so the function is 682 * optimized to be called more than once. It also applies to the functions, that 683 * use this function. 684 * 685 * @since 1.2.0 686 * @link http://codex.wordpress.org/Function_Reference/get_post_custom 687 * 688 * @uses $id Current Loop Post ID 689 * 690 * @param int $post_id post ID 691 * @return array 692 */ 693 function get_post_custom($post_id = 0) { 694 global $id; 695 696 if ( !$post_id ) 697 $post_id = (int) $id; 698 699 $post_id = (int) $post_id; 700 701 if ( ! wp_cache_get($post_id, 'post_meta') ) 702 update_postmeta_cache($post_id); 703 704 return wp_cache_get($post_id, 'post_meta'); 705 } 706 707 /** 708 * Retrieve meta field names for a post. 709 * 710 * If there are no meta fields, then nothing (null) will be returned. 711 * 712 * @since 1.2.0 713 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys 714 * 715 * @param int $post_id post ID 716 * @return array|null Either array of the keys, or null if keys could not be retrieved. 717 */ 718 function get_post_custom_keys( $post_id = 0 ) { 719 $custom = get_post_custom( $post_id ); 720 721 if ( !is_array($custom) ) 722 return; 723 724 if ( $keys = array_keys($custom) ) 725 return $keys; 726 } 727 728 /** 729 * Retrieve values for a custom post field. 730 * 731 * The parameters must not be considered optional. All of the post meta fields 732 * will be retrieved and only the meta field key values returned. 733 * 734 * @since 1.2.0 735 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values 736 * 737 * @param string $key Meta field key. 738 * @param int $post_id Post ID 739 * @return array Meta field values. 740 */ 741 function get_post_custom_values( $key = '', $post_id = 0 ) { 742 $custom = get_post_custom($post_id); 743 744 return isset($custom[$key]) ? $custom[$key] : null; 745 } 746 747 /** 748 * Check if post is sticky. 749 * 750 * Sticky posts should remain at the top of The Loop. If the post ID is not 751 * given, then The Loop ID for the current post will be used. 752 * 753 * @since 2.7.0 754 * 755 * @param int $post_id Optional. Post ID. 756 * @return bool Whether post is sticky (true) or not sticky (false). 757 */ 758 function is_sticky($post_id = null) { 759 global $id; 760 761 $post_id = absint($post_id); 762 763 if ( !$post_id ) 764 $post_id = absint($id); 765 766 $stickies = get_option('sticky_posts'); 767 768 if ( !is_array($stickies) ) 769 return false; 770 771 if ( in_array($post_id, $stickies) ) 772 return true; 773 774 return false; 775 } 776 777 /** 778 * Sanitize every post field. 779 * 780 * If the context is 'raw', then the post object or array will just be returned. 781 * 782 * @since 2.3.0 783 * @uses sanitize_post_field() Used to sanitize the fields. 784 * 785 * @param object|array $post The Post Object or Array 786 * @param string $context Optional, default is 'display'. How to sanitize post fields. 787 * @return object|array The now sanitized Post Object or Array (will be the same type as $post) 788 */ 789 function sanitize_post($post, $context = 'display') { 790 if ( 'raw' == $context ) 791 return $post; 792 if ( is_object($post) ) { 793 if ( !isset($post->ID) ) 794 $post->ID = 0; 795 foreach ( array_keys(get_object_vars($post)) as $field ) 796 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context); 797 $post->filter = $context; 798 } else { 799 if ( !isset($post['ID']) ) 800 $post['ID'] = 0; 801 foreach ( array_keys($post) as $field ) 802 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context); 803 $post['filter'] = $context; 804 } 805 806 return $post; 807 } 808 809 /** 810 * Sanitize post field based on context. 811 * 812 * Possible context values are: raw, edit, db, attribute, js, and display. The 813 * display context is used by default. 814 * 815 * @since 2.3.0 816 * 817 * @param string $field The Post Object field name. 818 * @param mixed $value The Post Object value. 819 * @param int $post_id Post ID. 820 * @param string $context How to sanitize post fields. 821 * @return mixed Sanitized value. 822 */ 823 function sanitize_post_field($field, $value, $post_id, $context) { 824 $int_fields = array('ID', 'post_parent', 'menu_order'); 825 if ( in_array($field, $int_fields) ) 826 $value = (int) $value; 827 828 if ( 'raw' == $context ) 829 return $value; 830 831 $prefixed = false; 832 if ( false !== strpos($field, 'post_') ) { 833 $prefixed = true; 834 $field_no_prefix = str_replace('post_', '', $field); 835 } 836 837 if ( 'edit' == $context ) { 838 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password'); 839 840 if ( $prefixed ) { 841 $value = apply_filters("edit_$field", $value, $post_id); 842 // Old school 843 $value = apply_filters("$field_no_prefix}_edit_pre", $value, $post_id); 844 } else { 845 $value = apply_filters("edit_post_$field", $value, $post_id); 846 } 847 848 if ( in_array($field, $format_to_edit) ) { 849 if ( 'post_content' == $field ) 850 $value = format_to_edit($value, user_can_richedit()); 851 else 852 $value = format_to_edit($value); 853 } else { 854 $value = attribute_escape($value); 855 } 856 } else if ( 'db' == $context ) { 857 if ( $prefixed ) { 858 $value = apply_filters("pre_$field", $value); 859 $value = apply_filters("$field_no_prefix}_save_pre", $value); 860 } else { 861 $value = apply_filters("pre_post_$field", $value); 862 $value = apply_filters("$field}_pre", $value); 863 } 864 } else { 865 // Use display filters by default. 866 if ( $prefixed ) 867 $value = apply_filters($field, $value, $post_id, $context); 868 else 869 $value = apply_filters("post_$field", $value, $post_id, $context); 870 } 871 872 if ( 'attribute' == $context ) 873 $value = attribute_escape($value); 874 else if ( 'js' == $context ) 875 $value = js_escape($value); 876 877 return $value; 878 } 879 880 /** 881 * Make a post sticky. 882 * 883 * Sticky posts should be displayed at the top of the front page. 884 * 885 * @since 2.7.0 886 * 887 * @param int $post_id Post ID. 888 */ 889 function stick_post($post_id) { 890 $stickies = get_option('sticky_posts'); 891 892 if ( !is_array($stickies) ) 893 $stickies = array($post_id); 894 895 if ( ! in_array($post_id, $stickies) ) 896 $stickies[] = $post_id; 897 898 update_option('sticky_posts', $stickies); 899 } 900 901 /** 902 * Unstick a post. 903 * 904 * Sticky posts should be displayed at the top of the front page. 905 * 906 * @since 2.7.0 907 * 908 * @param int $post_id Post ID. 909 */ 910 function unstick_post($post_id) { 911 $stickies = get_option('sticky_posts'); 912 913 if ( !is_array($stickies) ) 914 return; 915 916 if ( ! in_array($post_id, $stickies) ) 917 return; 918 919 $offset = array_search($post_id, $stickies); 920 if ( false === $offset ) 921 return; 922 923 array_splice($stickies, $offset, 1); 924 925 update_option('sticky_posts', $stickies); 926 } 927 928 /** 929 * Count number of posts of a post type and is user has permissions to view. 930 * 931 * This function provides an efficient method of finding the amount of post's 932 * type a blog has. Another method is to count the amount of items in 933 * get_posts(), but that method has a lot of overhead with doing so. Therefore, 934 * when developing for 2.5+, use this function instead. 935 * 936 * The $perm parameter checks for 'readable' value and if the user can read 937 * private posts, it will display that for the user that is signed in. 938 * 939 * @since 2.5.0 940 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts 941 * 942 * @param string $type Optional. Post type to retrieve count 943 * @param string $perm Optional. 'readable' or empty. 944 * @return object Number of posts for each status 945 */ 946 function wp_count_posts( $type = 'post', $perm = '' ) { 947 global $wpdb; 948 949 $user = wp_get_current_user(); 950 951 $cache_key = $type; 952 953 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s"; 954 if ( 'readable' == $perm && is_user_logged_in() ) { 955 if ( !current_user_can("read_private_{$type}s") ) { 956 $cache_key .= '_' . $perm . '_' . $user->ID; 957 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))"; 958 } 959 } 960 $query .= ' GROUP BY post_status'; 961 962 $count = wp_cache_get($cache_key, 'counts'); 963 if ( false !== $count ) 964 return $count; 965 966 $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A ); 967 968 $stats = array( ); 969 foreach( (array) $count as $row_num => $row ) { 970 $stats[$row['post_status']] = $row['num_posts']; 971 } 972 973 $stats = (object) $stats; 974 wp_cache_set($cache_key, $stats, 'counts'); 975 976 return $stats; 977 } 978 979 980 /** 981 * Count number of attachments for the mime type(s). 982 * 983 * If you set the optional mime_type parameter, then an array will still be 984 * returned, but will only have the item you are looking for. It does not give 985 * you the number of attachments that are children of a post. You can get that 986 * by counting the number of children that post has. 987 * 988 * @since 2.5.0 989 * 990 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns. 991 * @return array Number of posts for each mime type. 992 */ 993 function wp_count_attachments( $mime_type = '' ) { 994 global $wpdb; 995 996 $and = wp_post_mime_type_where( $mime_type ); 997 $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' $and GROUP BY post_mime_type", ARRAY_A ); 998 999 $stats = array( ); 1000 foreach( (array) $count as $row ) { 1001 $stats[$row['post_mime_type']] = $row['num_posts']; 1002 } 1003 1004 return (object) $stats; 1005 } 1006 1007 /** 1008 * Check a MIME-Type against a list. 1009 * 1010 * If the wildcard_mime_types parameter is a string, it must be comma separated 1011 * list. If the real_mime_types is a string, it is also comma separated to 1012 * create the list. 1013 * 1014 * @since 2.5.0 1015 * 1016 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or flash (same as *flash*) 1017 * @param string|array $real_mime_types post_mime_type values 1018 * @return array array(wildcard=>array(real types)) 1019 */ 1020 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) { 1021 $matches = array(); 1022 if ( is_string($wildcard_mime_types) ) 1023 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types)); 1024 if ( is_string($real_mime_types) ) 1025 $real_mime_types = array_map('trim', explode(',', $real_mime_types)); 1026 $wild = '[-._a-z0-9]*'; 1027 foreach ( (array) $wildcard_mime_types as $type ) { 1028 $type = str_replace('*', $wild, $type); 1029 $patternses[1][$type] = "^$type$"; 1030 if ( false === strpos($type, '/') ) { 1031 $patternses[2][$type] = "^$type/"; 1032 $patternses[3][$type] = $type; 1033 } 1034 } 1035 asort($patternses); 1036 foreach ( $patternses as $patterns ) 1037 foreach ( $patterns as $type => $pattern ) 1038 foreach ( (array) $real_mime_types as $real ) 1039 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) ) 1040 $matches[$type][] = $real; 1041 return $matches; 1042 } 1043 1044 /** 1045 * Convert MIME types into SQL. 1046 * 1047 * @since 2.5.0 1048 * 1049 * @param string|array $mime_types List of mime types or comma separated string of mime types. 1050 * @return string The SQL AND clause for mime searching. 1051 */ 1052 function wp_post_mime_type_where($post_mime_types) { 1053 $where = ''; 1054 $wildcards = array('', '%', '%/%'); 1055 if ( is_string($post_mime_types) ) 1056 $post_mime_types = array_map('trim', explode(',', $post_mime_types)); 1057 foreach ( (array) $post_mime_types as $mime_type ) { 1058 $mime_type = preg_replace('/\s/', '', $mime_type); 1059 $slashpos = strpos($mime_type, '/'); 1060 if ( false !== $slashpos ) { 1061 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos)); 1062 $mime_subgroup = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1)); 1063 if ( empty($mime_subgroup) ) 1064 $mime_subgroup = '*'; 1065 else 1066 $mime_subgroup = str_replace('/', '', $mime_subgroup); 1067 $mime_pattern = "$mime_group/$mime_subgroup"; 1068 } else { 1069 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type); 1070 if ( false === strpos($mime_pattern, '*') ) 1071 $mime_pattern .= '/*'; 1072 } 1073 1074 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern); 1075 1076 if ( in_array( $mime_type, $wildcards ) ) 1077 return ''; 1078 1079 if ( false !== strpos($mime_pattern, '%') ) 1080 $wheres[] = "post_mime_type LIKE '$mime_pattern'"; 1081 else 1082 $wheres[] = "post_mime_type = '$mime_pattern'"; 1083 } 1084 if ( !empty($wheres) ) 1085 $where = ' AND (' . join(' OR ', $wheres) . ') '; 1086 return $where; 1087 } 1088 1089 /** 1090 * Removes a post, attachment, or page. 1091 * 1092 * When the post and page goes, everything that is tied to it is deleted also. 1093 * This includes comments, post meta fields, and terms associated with the post. 1094 * 1095 * @since 1.0.0 1096 * @uses do_action() Calls 'deleted_post' hook on post ID. 1097 * 1098 * @param int $postid Post ID. 1099 * @return mixed 1100 */ 1101 function wp_delete_post($postid = 0) { 1102 global $wpdb, $wp_rewrite; 1103 1104 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) ) 1105 return $post; 1106 1107 if ( 'attachment' == $post->post_type ) 1108 return wp_delete_attachment($postid); 1109 1110 do_action('delete_post', $postid); 1111 1112 /** @todo delete for pluggable post taxonomies too */ 1113 wp_delete_object_term_relationships($postid, array('category', 'post_tag')); 1114 1115 $parent_data = array( 'post_parent' => $post->post_parent ); 1116 $parent_where = array( 'post_parent' => $postid ); 1117 1118 if ( 'page' == $post->post_type) { 1119 // if the page is defined in option page_on_front or post_for_posts, 1120 // adjust the corresponding options 1121 if ( get_option('page_on_front') == $postid ) { 1122 update_option('show_on_front', 'posts'); 1123 delete_option('page_on_front'); 1124 } 1125 if ( get_option('page_for_posts') == $postid ) { 1126 delete_option('page_for_posts'); 1127 } 1128 1129 // Point children of this page to its parent, also clean the cache of affected children 1130 $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid); 1131 $children = $wpdb->get_results($children_query); 1132 1133 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) ); 1134 } 1135 1136 // Do raw query. wp_get_post_revisions() is filtered 1137 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) ); 1138 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up. 1139 foreach ( $revision_ids as $revision_id ) 1140 wp_delete_post_revision( $revision_id ); 1141 1142 // Point all attachments to this post up one level 1143 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) ); 1144 1145 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid )); 1146 1147 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid )); 1148 1149 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d", $postid )); 1150 1151 if ( 'page' == $post->post_type ) { 1152 clean_page_cache($postid); 1153 1154 foreach ( (array) $children as $child ) 1155 clean_page_cache($child->ID); 1156 1157 $wp_rewrite->flush_rules(); 1158 } else { 1159 clean_post_cache($postid); 1160 } 1161 1162 do_action('deleted_post', $postid); 1163 1164 return $post; 1165 } 1166 1167 /** 1168 * Retrieve the list of categories for a post. 1169 * 1170 * Compatibility layer for themes and plugins. Also an easy layer of abstraction 1171 * away from the complexity of the taxonomy layer. 1172 * 1173 * @since 2.1.0 1174 * 1175 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here. 1176 * 1177 * @param int $post_id Optional. The Post ID. 1178 * @param array $args Optional. Overwrite the defaults. 1179 * @return array 1180 */ 1181 function wp_get_post_categories( $post_id = 0, $args = array() ) { 1182 $post_id = (int) $post_id; 1183 1184 $defaults = array('fields' => 'ids'); 1185 $args = wp_parse_args( $args, $defaults ); 1186 1187 $cats = wp_get_object_terms($post_id, 'category', $args); 1188 return $cats; 1189 } 1190 1191 /** 1192 * Retrieve the tags for a post. 1193 * 1194 * There is only one default for this function, called 'fields' and by default 1195 * is set to 'all'. There are other defaults that can be override in 1196 * {@link wp_get_object_terms()}. 1197 * 1198 * @package WordPress 1199 * @subpackage Post 1200 * @since 2.3.0 1201 * 1202 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here 1203 * 1204 * @param int $post_id Optional. The Post ID 1205 * @param array $args Optional. Overwrite the defaults 1206 * @return array List of post tags. 1207 */ 1208 function wp_get_post_tags( $post_id = 0, $args = array() ) { 1209 $post_id = (int) $post_id; 1210 1211 $defaults = array('fields' => 'all'); 1212 $args = wp_parse_args( $args, $defaults ); 1213 1214 $tags = wp_get_object_terms($post_id, 'post_tag', $args); 1215 1216 return $tags; 1217 } 1218 1219 /** 1220 * Retrieve number of recent posts. 1221 * 1222 * @since 1.0.0 1223 * @uses $wpdb 1224 * 1225 * @param int $num Optional, default is 10. Number of posts to get. 1226 * @return array List of posts. 1227 */ 1228 function wp_get_recent_posts($num = 10) { 1229 global $wpdb; 1230 1231 // Set the limit clause, if we got a limit 1232 $num = (int) $num; 1233 if ($num) { 1234 $limit = "LIMIT $num"; 1235 } 1236 1237 $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit"; 1238 $result = $wpdb->get_results($sql,ARRAY_A); 1239 1240 return $result ? $result : array(); 1241 } 1242 1243 /** 1244 * Retrieve a single post, based on post ID. 1245 * 1246 * Has categories in 'post_category' property or key. Has tags in 'tags_input' 1247 * property or key. 1248 * 1249 * @since 1.0.0 1250 * 1251 * @param int $postid Post ID. 1252 * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A. 1253 * @return object|array Post object or array holding post contents and information 1254 */ 1255 function wp_get_single_post($postid = 0, $mode = OBJECT) { 1256 $postid = (int) $postid; 1257 1258 $post = get_post($postid, $mode); 1259 1260 // Set categories and tags 1261 if($mode == OBJECT) { 1262 $post->post_category = wp_get_post_categories($postid); 1263 $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names')); 1264 } 1265 else { 1266 $post['post_category'] = wp_get_post_categories($postid); 1267 $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names')); 1268 } 1269 1270 return $post; 1271 } 1272 1273 /** 1274 * Insert a post. 1275 * 1276 * If the $postarr parameter has 'ID' set to a value, then post will be updated. 1277 * 1278 * You can set the post date manually, but setting the values for 'post_date' 1279 * and 'post_date_gmt' keys. You can close the comments or open the comments by 1280 * setting the value for 'comment_status' key. 1281 * 1282 * The defaults for the parameter $postarr are: 1283 * 'post_status' - Default is 'draft'. 1284 * 'post_type' - Default is 'post'. 1285 * 'post_author' - Default is current user ID. The ID of the user, who added 1286 * the post. 1287 * 'ping_status' - Default is the value in default ping status option. 1288 * Whether the attachment can accept pings. 1289 * 'post_parent' - Default is 0. Set this for the post it belongs to, if 1290 * any. 1291 * 'menu_order' - Default is 0. The order it is displayed. 1292 * 'to_ping' - Whether to ping. 1293 * 'pinged' - Default is empty string. 1294 * 'post_password' - Default is empty string. The password to access the 1295 * attachment. 1296 * 'guid' - Global Unique ID for referencing the attachment. 1297 * 'post_content_filtered' - Post content filtered. 1298 * 'post_excerpt' - Post excerpt. 1299 * 1300 * @since 1.0.0 1301 * @uses $wpdb 1302 * @uses $wp_rewrite 1303 * @uses $user_ID 1304 * 1305 * @param array $postarr Optional. Override defaults. 1306 * @param bool $wp_error Optional. Allow return of WP_Error on failure. 1307 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success. 1308 */ 1309 function wp_insert_post($postarr = array(), $wp_error = false) { 1310 global $wpdb, $wp_rewrite, $user_ID; 1311 1312 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 1313 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 1314 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 1315 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0); 1316 1317 $postarr = wp_parse_args($postarr, $defaults); 1318 $postarr = sanitize_post($postarr, 'db'); 1319 1320 // export array as variables 1321 extract($postarr, EXTR_SKIP); 1322 1323 // Are we updating or creating? 1324 $update = false; 1325 if ( !empty($ID) ) { 1326 $update = true; 1327 $previous_status = get_post_field('post_status', $ID); 1328 } else { 1329 $previous_status = 'new'; 1330 } 1331 1332 if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) ) { 1333 if ( $wp_error ) 1334 return new WP_Error('empty_content', __('Content, title, and excerpt are empty.')); 1335 else 1336 return 0; 1337 } 1338 1339 // Make sure we set a valid category 1340 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) { 1341 $post_category = array(get_option('default_category')); 1342 } 1343 1344 //Set the default tag list 1345 if ( !isset($tags_input) ) 1346 $tags_input = array(); 1347 1348 if ( empty($post_author) ) 1349 $post_author = $user_ID; 1350 1351 if ( empty($post_status) ) 1352 $post_status = 'draft'; 1353 1354 if ( empty($post_type) ) 1355 $post_type = 'post'; 1356 1357 $post_ID = 0; 1358 1359 // Get the post ID and GUID 1360 if ( $update ) { 1361 $post_ID = (int) $ID; 1362 $guid = get_post_field( 'guid', $post_ID ); 1363 } 1364 1365 // Don't allow contributors to set to set the post slug for pending review posts 1366 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) 1367 $post_name = ''; 1368 1369 // Create a valid post name. Drafts and pending posts are allowed to have an empty 1370 // post name. 1371 if ( empty($post_name) ) { 1372 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) ) 1373 $post_name = sanitize_title($post_title); 1374 } else { 1375 $post_name = sanitize_title($post_name); 1376 } 1377 1378 // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now 1379 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date ) 1380 $post_date = current_time('mysql'); 1381 1382 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) { 1383 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) ) 1384 $post_date_gmt = get_gmt_from_date($post_date); 1385 else 1386 $post_date_gmt = '0000-00-00 00:00:00'; 1387 } 1388 1389 if ( $update || '0000-00-00 00:00:00' == $post_date ) { 1390 $post_modified = current_time( 'mysql' ); 1391 $post_modified_gmt = current_time( 'mysql', 1 ); 1392 } else { 1393 $post_modified = $post_date; 1394 $post_modified_gmt = $post_date_gmt; 1395 } 1396 1397 if ( 'publish' == $post_status ) { 1398 $now = gmdate('Y-m-d H:i:59'); 1399 if ( mysql2date('U', $post_date_gmt) > mysql2date('U', $now) ) 1400 $post_status = 'future'; 1401 } 1402 1403 if ( empty($comment_status) ) { 1404 if ( $update ) 1405 $comment_status = 'closed'; 1406 else 1407 $comment_status = get_option('default_comment_status'); 1408 } 1409 if ( empty($ping_status) ) 1410 $ping_status = get_option('default_ping_status'); 1411 1412 if ( isset($to_ping) ) 1413 $to_ping = preg_replace('|\s+|', "\n", $to_ping); 1414 else 1415 $to_ping = ''; 1416 1417 if ( ! isset($pinged) ) 1418 $pinged = ''; 1419 1420 if ( isset($post_parent) ) 1421 $post_parent = (int) $post_parent; 1422 else 1423 $post_parent = 0; 1424 1425 if ( !empty($post_ID) ) { 1426 if ( $post_parent == $post_ID ) { 1427 // Post can't be its own parent 1428 $post_parent = 0; 1429 } elseif ( !empty($post_parent) ) { 1430 $parent_post = get_post($post_parent); 1431 // Check for circular dependency 1432 if ( $parent_post->post_parent == $post_ID ) 1433 $post_parent = 0; 1434 } 1435 } 1436 1437 if ( isset($menu_order) ) 1438 $menu_order = (int) $menu_order; 1439 else 1440 $menu_order = 0; 1441 1442 if ( !isset($post_password) || 'private' == $post_status ) 1443 $post_password = ''; 1444 1445 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) ) { 1446 $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d AND post_parent = %d LIMIT 1", $post_name, $post_type, $post_ID, $post_parent)); 1447 1448 if ($post_name_check || in_array($post_name, $wp_rewrite->feeds) ) { 1449 $suffix = 2; 1450 do { 1451 $alt_post_name = substr($post_name, 0, 200-(strlen($suffix)+1)). "-$suffix"; 1452 $post_name_check = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d AND post_parent = %d LIMIT 1", $alt_post_name, $post_type, $post_ID, $post_parent)); 1453 $suffix++; 1454 } while ($post_name_check); 1455 $post_name = $alt_post_name; 1456 } 1457 } 1458 1459 // expected_slashed (everything!) 1460 $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) ); 1461 $data = apply_filters('wp_insert_post_data', $data, $postarr); 1462 $data = stripslashes_deep( $data ); 1463 $where = array( 'ID' => $post_ID ); 1464 1465 if ($update) { 1466 do_action( 'pre_post_update', $post_ID ); 1467 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) { 1468 if ( $wp_error ) 1469 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error); 1470 else 1471 return 0; 1472 } 1473 } else { 1474 if ( isset($post_mime_type) ) 1475 $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update 1476 // If there is a suggested ID, use it if not already present 1477 if ( !empty($import_id) ) { 1478 $import_id = (int) $import_id; 1479 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) { 1480 $data['ID'] = $import_id; 1481 } 1482 } 1483 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) { 1484 if ( $wp_error ) 1485 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error); 1486 else 1487 return 0; 1488 } 1489 $post_ID = (int) $wpdb->insert_id; 1490 1491 // use the newly generated $post_ID 1492 $where = array( 'ID' => $post_ID ); 1493 } 1494 1495 if ( empty($post_name) && !in_array( $post_status, array( 'draft', 'pending' ) ) ) { 1496 $post_name = sanitize_title($post_title, $post_ID); 1497 $wpdb->update( $wpdb->posts, compact( 'post_name' ), $where ); 1498 } 1499 1500 wp_set_post_categories( $post_ID, $post_category ); 1501 wp_set_post_tags( $post_ID, $tags_input ); 1502 1503 $current_guid = get_post_field( 'guid', $post_ID ); 1504 1505 if ( 'page' == $post_type ) 1506 clean_page_cache($post_ID); 1507 else 1508 clean_post_cache($post_ID); 1509 1510 // Set GUID 1511 if ( !$update && '' == $current_guid ) 1512 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where ); 1513 1514 $post = get_post($post_ID); 1515 1516 if ( !empty($page_template) && 'page' == $post_type ) { 1517 $post->page_template = $page_template; 1518 $page_templates = get_page_templates(); 1519 if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) { 1520 if ( $wp_error ) 1521 return new WP_Error('invalid_page_template', __('The page template is invalid.')); 1522 else 1523 return 0; 1524 } 1525 update_post_meta($post_ID, '_wp_page_template', $page_template); 1526 } 1527 1528 wp_transition_post_status($post_status, $previous_status, $post); 1529 1530 if ( $update) 1531 do_action('edit_post', $post_ID, $post); 1532 1533 do_action('save_post', $post_ID, $post); 1534 do_action('wp_insert_post', $post_ID, $post); 1535 1536 return $post_ID; 1537 } 1538 1539 /** 1540 * Update a post with new post data. 1541 * 1542 * The date does not have to be set for drafts. You can set the date and it will 1543 * not be overridden. 1544 * 1545 * @since 1.0.0 1546 * 1547 * @param array|object $postarr Post data. 1548 * @return int 0 on failure, Post ID on success. 1549 */ 1550 function wp_update_post($postarr = array()) { 1551 if ( is_object($postarr) ) 1552 $postarr = get_object_vars($postarr); 1553 1554 // First, get all of the original fields 1555 $post = wp_get_single_post($postarr['ID'], ARRAY_A); 1556 1557 // Escape data pulled from DB. 1558 $post = add_magic_quotes($post); 1559 1560 // Passed post category list overwrites existing category list if not empty. 1561 if ( isset($postarr['post_category']) && is_array($postarr['post_category']) 1562 && 0 != count($postarr['post_category']) ) 1563 $post_cats = $postarr['post_category']; 1564 else 1565 $post_cats = $post['post_category']; 1566 1567 // Drafts shouldn't be assigned a date unless explicitly done so by the user 1568 if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) && 1569 ('0000-00-00 00:00:00' == $post['post_date_gmt']) ) 1570 $clear_date = true; 1571 else 1572 $clear_date = false; 1573 1574 // Merge old and new fields with new fields overwriting old ones. 1575 $postarr = array_merge($post, $postarr); 1576 $postarr['post_category'] = $post_cats; 1577 if ( $clear_date ) { 1578 $postarr['post_date'] = current_time('mysql'); 1579 $postarr['post_date_gmt'] = ''; 1580 } 1581 1582 if ($postarr['post_type'] == 'attachment') 1583 return wp_insert_attachment($postarr); 1584 1585 return wp_insert_post($postarr); 1586 } 1587 1588 /** 1589 * Publish a post by transitioning the post status. 1590 * 1591 * @since 2.1.0 1592 * @uses $wpdb 1593 * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data. 1594 * 1595 * @param int $post_id Post ID. 1596 * @return null 1597 */ 1598 function wp_publish_post($post_id) { 1599 global $wpdb; 1600 1601 $post = get_post($post_id); 1602 1603 if ( empty($post) ) 1604 return; 1605 1606 if ( 'publish' == $post->post_status ) 1607 return; 1608 1609 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) ); 1610 1611 $old_status = $post->post_status; 1612 $post->post_status = 'publish'; 1613 wp_transition_post_status('publish', $old_status, $post); 1614 1615 // Update counts for the post's terms. 1616 foreach ( (array) get_object_taxonomies('post') as $taxonomy ) { 1617 $tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids'); 1618 wp_update_term_count($tt_ids, $taxonomy); 1619 } 1620 1621 do_action('edit_post', $post_id, $post); 1622 do_action('save_post', $post_id, $post); 1623 do_action('wp_insert_post', $post_id, $post); 1624 } 1625 1626 /** 1627 * Publish future post and make sure post ID has future post status. 1628 * 1629 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron 1630 * from publishing drafts, etc. 1631 * 1632 * @since 2.5.0 1633 * 1634 * @param int $post_id Post ID. 1635 * @return null Nothing is returned. Which can mean that no action is required or post was published. 1636 */ 1637 function check_and_publish_future_post($post_id) { 1638 1639 $post = get_post($post_id); 1640 1641 if ( empty($post) ) 1642 return; 1643 1644 if ( 'future' != $post->post_status ) 1645 return; 1646 1647 $time = strtotime( $post->post_date_gmt . ' GMT' ); 1648 1649 if ( $time > time() ) { // Uh oh, someone jumped the gun! 1650 wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system 1651 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) ); 1652 return; 1653 } 1654 1655 return wp_publish_post($post_id); 1656 } 1657 1658 /** 1659 * Adds tags to a post. 1660 * 1661 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true. 1662 * 1663 * @package WordPress 1664 * @subpackage Post 1665 * @since 2.3.0 1666 * 1667 * @param int $post_id Post ID 1668 * @param string $tags The tags to set for the post, separated by commas. 1669 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise 1670 */ 1671 function wp_add_post_tags($post_id = 0, $tags = '') { 1672 return wp_set_post_tags($post_id, $tags, true); 1673 } 1674 1675 1676 /** 1677 * Set the tags for a post. 1678 * 1679 * @since 2.3.0 1680 * @uses wp_set_object_terms() Sets the tags for the post. 1681 * 1682 * @param int $post_id Post ID. 1683 * @param string $tags The tags to set for the post, separated by commas. 1684 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags. 1685 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise 1686 */ 1687 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) { 1688 1689 $post_id = (int) $post_id; 1690 1691 if ( !$post_id ) 1692 return false; 1693 1694 if ( empty($tags) ) 1695 $tags = array(); 1696 $tags = (is_array($tags)) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") ); 1697 wp_set_object_terms($post_id, $tags, 'post_tag', $append); 1698 } 1699 1700 /** 1701 * Set categories for a post. 1702 * 1703 * If the post categories parameter is not set, then the default category is 1704 * going used. 1705 * 1706 * @since 2.1.0 1707 * 1708 * @param int $post_ID Post ID. 1709 * @param array $post_categories Optional. List of categories. 1710 * @return bool|mixed 1711 */ 1712 function wp_set_post_categories($post_ID = 0, $post_categories = array()) { 1713 $post_ID = (int) $post_ID; 1714 // If $post_categories isn't already an array, make it one: 1715 if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories)) 1716 $post_categories = array(get_option('default_category')); 1717 else if ( 1 == count($post_categories) && '' == $post_categories[0] ) 1718 return true; 1719 1720 $post_categories = array_map('intval', $post_categories); 1721 $post_categories = array_unique($post_categories); 1722 1723 return wp_set_object_terms($post_ID, $post_categories, 'category'); 1724 } 1725 1726 /** 1727 * Transition the post status of a post. 1728 * 1729 * Calls hooks to transition post status. If the new post status is not the same 1730 * as the previous post status, then two hooks will be ran, the first is 1731 * 'transition_post_status' with new status, old status, and post data. The 1732 * next action called is 'OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the 1733 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the 1734 * post data. 1735 * 1736 * The final action will run whether or not the post statuses are the same. The 1737 * action is named 'NEWSTATUS_POSTTYPE', NEWSTATUS is from the $new_status 1738 * parameter and POSTTYPE is post_type post data. 1739 * 1740 * @since 2.3.0 1741 * 1742 * @param string $new_status Transition to this post status. 1743 * @param string $old_status Previous post status. 1744 * @param object $post Post data. 1745 */ 1746 function wp_transition_post_status($new_status, $old_status, $post) { 1747 if ( $new_status != $old_status ) { 1748 do_action('transition_post_status', $new_status, $old_status, $post); 1749 do_action("$old_status}_to_$new_status", $post); 1750 } 1751 do_action("$new_status}_$post->post_type", $post->ID, $post); 1752 } 1753 1754 // 1755 // Trackback and ping functions 1756 // 1757 1758 /** 1759 * Add a URL to those already pung. 1760 * 1761 * @since 1.5.0 1762 * @uses $wpdb 1763 * 1764 * @param int $post_id Post ID. 1765 * @param string $uri Ping URI. 1766 * @return int How many rows were updated. 1767 */ 1768 function add_ping($post_id, $uri) { 1769 global $wpdb; 1770 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id )); 1771 $pung = trim($pung); 1772 $pung = preg_split('/\s/', $pung); 1773 $pung[] = $uri; 1774 $new = implode("\n", $pung); 1775 $new = apply_filters('add_ping', $new); 1776 // expected_slashed ($new) 1777 $new = stripslashes($new); 1778 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) ); 1779 } 1780 1781 /** 1782 * Retrieve enclosures already enclosed for a post. 1783 * 1784 * @since 1.5.0 1785 * @uses $wpdb 1786 * 1787 * @param int $post_id Post ID. 1788 * @return array List of enclosures 1789 */ 1790 function get_enclosed($post_id) { 1791 $custom_fields = get_post_custom( $post_id ); 1792 $pung = array(); 1793 if ( !is_array( $custom_fields ) ) 1794 return $pung; 1795 1796 foreach ( $custom_fields as $key => $val ) { 1797 if ( 'enclosure' != $key || !is_array( $val ) ) 1798 continue; 1799 foreach( $val as $enc ) { 1800 $enclosure = split( "\n", $enc ); 1801 $pung[] = trim( $enclosure[ 0 ] ); 1802 } 1803 } 1804 $pung = apply_filters('get_enclosed', $pung); 1805 return $pung; 1806 } 1807 1808 /** 1809 * Retrieve URLs already pinged for a post. 1810 * 1811 * @since 1.5.0 1812 * @uses $wpdb 1813 * 1814 * @param int $post_id Post ID. 1815 * @return array 1816 */ 1817 function get_pung($post_id) { 1818 global $wpdb; 1819 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id )); 1820 $pung = trim($pung); 1821 $pung = preg_split('/\s/', $pung); 1822 $pung = apply_filters('get_pung', $pung); 1823 return $pung; 1824 } 1825 1826 /** 1827 * Retrieve URLs that need to be pinged. 1828 * 1829 * @since 1.5.0 1830 * @uses $wpdb 1831 * 1832 * @param int $post_id Post ID 1833 * @return array 1834 */ 1835 function get_to_ping($post_id) { 1836 global $wpdb; 1837 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id )); 1838 $to_ping = trim($to_ping); 1839 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY); 1840 $to_ping = apply_filters('get_to_ping', $to_ping); 1841 return $to_ping; 1842 } 1843 1844 /** 1845 * Do trackbacks for a list of URLs. 1846 * 1847 * @since 1.0.0 1848 * 1849 * @param string $tb_list Comma separated list of URLs 1850 * @param int $post_id Post ID 1851 */ 1852 function trackback_url_list($tb_list, $post_id) { 1853 if ( ! empty( $tb_list ) ) { 1854 // get post data 1855 $postdata = wp_get_single_post($post_id, ARRAY_A); 1856 1857 // import postdata as variables 1858 extract($postdata, EXTR_SKIP); 1859 1860 // form an excerpt 1861 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content); 1862 1863 if (strlen($excerpt) > 255) { 1864 $excerpt = substr($excerpt,0,252) . '...'; 1865 } 1866 1867 $trackback_urls = explode(',', $tb_list); 1868 foreach( (array) $trackback_urls as $tb_url) { 1869 $tb_url = trim($tb_url); 1870 trackback($tb_url, stripslashes($post_title), $excerpt, $post_id); 1871 } 1872 } 1873 } 1874 1875 // 1876 // Page functions 1877 // 1878 1879 /** 1880 * Get a list of page IDs. 1881 * 1882 * @since 2.0.0 1883 * @uses $wpdb 1884 * 1885 * @return array List of page IDs. 1886 */ 1887 function get_all_page_ids() { 1888 global $wpdb; 1889 1890 if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) { 1891 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'"); 1892 wp_cache_add('all_page_ids', $page_ids, 'posts'); 1893 } 1894 1895 return $page_ids; 1896 } 1897 1898 /** 1899 * Retrieves page data given a page ID or page object. 1900 * 1901 * @since 1.5.1 1902 * 1903 * @param mixed $page Page object or page ID. Passed by reference. 1904 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N. 1905 * @param string $filter How the return value should be filtered. 1906 * @return mixed Page data. 1907 */ 1908 function &get_page(&$page, $output = OBJECT, $filter = 'raw') { 1909 if ( empty($page) ) { 1910 if ( isset( $GLOBALS['page'] ) && isset( $GLOBALS['page']->ID ) ) { 1911 return get_post($GLOBALS['page'], $output, $filter); 1912 } else { 1913 $page = null; 1914 return $page; 1915 } 1916 } 1917 1918 $the_page = get_post($page, $output, $filter); 1919 return $the_page; 1920 } 1921 1922 /** 1923 * Retrieves a page given its path. 1924 * 1925 * @since 2.1.0 1926 * @uses $wpdb 1927 * 1928 * @param string $page_path Page path 1929 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. 1930 * @return mixed Null when complete. 1931 */ 1932 function get_page_by_path($page_path, $output = OBJECT) { 1933 global $wpdb; 1934 $page_path = rawurlencode(urldecode($page_path)); 1935 $page_path = str_replace('%2F', '/', $page_path); 1936 $page_path = str_replace('%20', ' ', $page_path); 1937 $page_paths = '/' . trim($page_path, '/'); 1938 $leaf_path = sanitize_title(basename($page_paths)); 1939 $page_paths = explode('/', $page_paths); 1940 $full_path = ''; 1941 foreach( (array) $page_paths as $pathdir) 1942 $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); 1943 1944 $pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = 'page' OR post_type = 'attachment')", $leaf_path )); 1945 1946 if ( empty($pages) ) 1947 return null; 1948 1949 foreach ($pages as $page) { 1950 $path = '/' . $leaf_path; 1951 $curpage = $page; 1952 while ($curpage->post_parent != 0) { 1953 $curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type='page'", $curpage->post_parent )); 1954 $path = '/' . $curpage->post_name . $path; 1955 } 1956 1957 if ( $path == $full_path ) 1958 return get_page($page->ID, $output); 1959 } 1960 1961 return null; 1962 } 1963 1964 /** 1965 * Retrieve a page given its title. 1966 * 1967 * @since 2.1.0 1968 * @uses $wpdb 1969 * 1970 * @param string $page_title Page title 1971 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. 1972 * @return mixed 1973 */ 1974 function get_page_by_title($page_title, $output = OBJECT) { 1975 global $wpdb; 1976 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title )); 1977 if ( $page ) 1978 return get_page($page, $output); 1979 1980 return null; 1981 } 1982 1983 /** 1984 * Retrieve child pages from list of pages matching page ID. 1985 * 1986 * Matches against the pages parameter against the page ID. Also matches all 1987 * children for the same to retrieve all children of a page. Does not make any 1988 * SQL queries to get the children. 1989 * 1990 * @since 1.5.1 1991 * 1992 * @param int $page_id Page ID. 1993 * @param array $pages List of pages' objects. 1994 * @return array 1995 */ 1996 function &get_page_children($page_id, $pages) { 1997 $page_list = array(); 1998 foreach ( (array) $pages as $page ) { 1999 if ( $page->post_parent == $page_id ) { 2000 $page_list[] = $page; 2001 if ( $children = get_page_children($page->ID, $pages) ) 2002 $page_list = array_merge($page_list, $children); 2003 } 2004 } 2005 return $page_list; 2006 } 2007 2008 /** 2009 * Order the pages with children under parents in a flat list. 2010 * 2011 * Fetches the pages returned as a FLAT list, but arranged in order of their 2012 * hierarchy, i.e., child parents immediately follow their parents. 2013 * 2014 * @since 2.0.0 2015 * 2016 * @param array $posts Posts array. 2017 * @param int $parent Parent page ID. 2018 * @return array 2019 */ 2020 function get_page_hierarchy($posts, $parent = 0) { 2021 $result = array ( ); 2022 if ($posts) { foreach ( (array) $posts as $post) { 2023 if ($post->post_parent == $parent) { 2024 $result[$post->ID] = $post->post_name; 2025 $children = get_page_hierarchy($posts, $post->ID); 2026 $result += $children; //append $children to $result 2027 } 2028 } } 2029 return $result; 2030 } 2031 2032 /** 2033 * Builds URI for a page. 2034 * 2035 * Sub pages will be in the "directory" under the parent page post name. 2036 * 2037 * @since 1.5.0 2038 * 2039 * @param int $page_id Page ID. 2040 * @return string Page URI. 2041 */ 2042 function get_page_uri($page_id) { 2043 $page = get_page($page_id); 2044 $uri = $page->post_name; 2045 2046 // A page cannot be it's own parent. 2047 if ( $page->post_parent == $page->ID ) 2048 return $uri; 2049 2050 while ($page->post_parent != 0) { 2051 $page = get_page($page->post_parent); 2052 $uri = $page->post_name . "/" . $uri; 2053 } 2054 2055 return $uri; 2056 } 2057 2058 /** 2059 * Retrieve a list of pages. 2060 * 2061 * The defaults that can be overridden are the following: 'child_of', 2062 * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude', 2063 * 'include', 'meta_key', 'meta_value', and 'authors'. 2064 * 2065 * @since 1.5.0 2066 * @uses $wpdb 2067 * 2068 * @param mixed $args Optional. Array or string of options that overrides defaults. 2069 * @return array List of pages matching defaults or $args 2070 */ 2071 function &get_pages($args = '') { 2072 global $wpdb; 2073 2074 $defaults = array( 2075 'child_of' => 0, 'sort_order' => 'ASC', 2076 'sort_column' => 'post_title', 'hierarchical' => 1, 2077 'exclude' => '', 'include' => '', 2078 'meta_key' => '', 'meta_value' => '', 2079 'authors' => '', 'parent' => -1, 'exclude_tree' => '' 2080 ); 2081 2082 $r = wp_parse_args( $args, $defaults ); 2083 extract( $r, EXTR_SKIP ); 2084 2085 $key = md5( serialize( compact(array_keys($defaults)) ) ); 2086 if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) { 2087 if ( isset( $cache[ $key ] ) ) { 2088 $pages = apply_filters('get_pages', $cache[ $key ], $r ); 2089 return $pages; 2090 } 2091 } 2092 2093 $inclusions = ''; 2094 if ( !empty($include) ) { 2095 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include 2096 $parent = -1; 2097 $exclude = ''; 2098 $meta_key = ''; 2099 $meta_value = ''; 2100 $hierarchical = false; 2101 $incpages = preg_split('/[\s,]+/',$include); 2102 if ( count($incpages) ) { 2103 foreach ( $incpages as $incpage ) { 2104 if (empty($inclusions)) 2105 $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage); 2106 else 2107 $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage); 2108 } 2109 } 2110 } 2111 if (!empty($inclusions)) 2112 $inclusions .= ')'; 2113 2114 $exclusions = ''; 2115 if ( !empty($exclude) ) { 2116 $expages = preg_split('/[\s,]+/',$exclude); 2117 if ( count($expages) ) { 2118 foreach ( $expages as $expage ) { 2119 if (empty($exclusions)) 2120 $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage); 2121 else 2122 $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage); 2123 } 2124 } 2125 } 2126 if (!empty($exclusions)) 2127 $exclusions .= ')'; 2128 2129 $author_query = ''; 2130 if (!empty($authors)) { 2131 $post_authors = preg_split('/[\s,]+/',$authors); 2132 2133 if ( count($post_authors) ) { 2134 foreach ( $post_authors as $post_author ) { 2135 //Do we have an author id or an author login? 2136 if ( 0 == intval($post_author) ) { 2137 $post_author = get_userdatabylogin($post_author); 2138 if ( empty($post_author) ) 2139 continue; 2140 if ( empty($post_author->ID) ) 2141 continue; 2142 $post_author = $post_author->ID; 2143 } 2144 2145 if ( '' == $author_query ) 2146 $author_query = $wpdb->prepare(' post_author = %d ', $post_author); 2147 else 2148 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author); 2149 } 2150 if ( '' != $author_query ) 2151 $author_query = " AND ($author_query)"; 2152 } 2153 } 2154 2155 $join = ''; 2156 $where = "$exclusions $inclusions "; 2157 if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) { 2158 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )"; 2159 2160 // meta_key and meta_value might be slashed 2161 $meta_key = stripslashes($meta_key); 2162 $meta_value = stripslashes($meta_value); 2163 if ( ! empty( $meta_key ) ) 2164 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key); 2165 if ( ! empty( $meta_value ) ) 2166 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value); 2167 2168 } 2169 2170 if ( $parent >= 0 ) 2171 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent); 2172 2173 $query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where "; 2174 $query .= $author_query; 2175 $query .= " ORDER BY " . $sort_column . " " . $sort_order ; 2176 2177 $pages = $wpdb->get_results($query); 2178 2179 if ( empty($pages) ) { 2180 $pages = apply_filters('get_pages', array(), $r); 2181 return $pages; 2182 } 2183 2184 // Update cache. 2185 update_page_cache($pages); 2186 2187 if ( $child_of || $hierarchical ) 2188 $pages = & get_page_children($child_of, $pages); 2189 2190 if ( !empty($exclude_tree) ) { 2191 $exclude = array(); 2192 2193 $exclude = (int) $exclude_tree; 2194 $children = get_page_children($exclude, $pages); 2195 $excludes = array(); 2196 foreach ( $children as $child ) 2197 $excludes[] = $child->ID; 2198 $excludes[] = $exclude; 2199 $total = count($pages); 2200 for ( $i = 0; $i < $total; $i++ ) { 2201 if ( in_array($pages[$i]->ID, $excludes) ) 2202 unset($pages[$i]); 2203 } 2204 } 2205 2206 $cache[ $key ] = $pages; 2207 wp_cache_set( 'get_pages', $cache, 'posts' ); 2208 2209 $pages = apply_filters('get_pages', $pages, $r); 2210 2211 return $pages; 2212 } 2213 2214 // 2215 // Attachment functions 2216 // 2217 2218 /** 2219 * Check if the attachment URI is local one and is really an attachment. 2220 * 2221 * @since 2.0.0 2222 * 2223 * @param string $url URL to check 2224 * @return bool True on success, false on failure. 2225 */ 2226 function is_local_attachment($url) { 2227 if (strpos($url, get_bloginfo('url')) === false) 2228 return false; 2229 if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false) 2230 return true; 2231 if ( $id = url_to_postid($url) ) { 2232 $post = & get_post($id); 2233 if ( 'attachment' == $post->post_type ) 2234 return true; 2235 } 2236 return false; 2237 } 2238 2239 /** 2240 * Insert an attachment. 2241 * 2242 * If you set the 'ID' in the $object parameter, it will mean that you are 2243 * updating and attempt to update the attachment. You can also set the 2244 * attachment name or title by setting the key 'post_name' or 'post_title'. 2245 * 2246 * You can set the dates for the attachment manually by setting the 'post_date' 2247 * and 'post_date_gmt' keys' values. 2248 * 2249 * By default, the comments will use the default settings for whether the 2250 * comments are allowed. You can close them manually or keep them open by 2251 * setting the value for the 'comment_status' key. 2252 * 2253 * The $object parameter can have the following: 2254 * 'post_status' - Default is 'draft'. Can not be override, set the same as 2255 * parent post. 2256 * 'post_type' - Default is 'post', will be set to attachment. Can not 2257 * override. 2258 * 'post_author' - Default is current user ID. The ID of the user, who added 2259 * the attachment. 2260 * 'ping_status' - Default is the value in default ping status option. 2261 * Whether the attachment can accept pings. 2262 * 'post_parent' - Default is 0. Can use $parent parameter or set this for 2263 * the post it belongs to, if any. 2264 * 'menu_order' - Default is 0. The order it is displayed. 2265 * 'to_ping' - Whether to ping. 2266 * 'pinged' - Default is empty string. 2267 * 'post_password' - Default is empty string. The password to access the 2268 * attachment. 2269 * 'guid' - Global Unique ID for referencing the attachment. 2270 * 'post_content_filtered' - Attachment post content filtered. 2271 * 'post_excerpt' - Attachment excerpt. 2272 * 2273 * @since 2.0.0 2274 * @uses $wpdb 2275 * @uses $user_ID 2276 * 2277 * @param string|array $object Arguments to override defaults. 2278 * @param string $file Optional filename. 2279 * @param int $post_parent Parent post ID. 2280 * @return int Attachment ID. 2281 */ 2282 function wp_insert_attachment($object, $file = false, $parent = 0) { 2283 global $wpdb, $user_ID; 2284 2285 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 2286 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 2287 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 2288 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0); 2289 2290 $object = wp_parse_args($object, $defaults); 2291 if ( !empty($parent) ) 2292 $object['post_parent'] = $parent; 2293 2294 $object = sanitize_post($object, 'db'); 2295 2296 // export array as variables 2297 extract($object, EXTR_SKIP); 2298 2299 // Make sure we set a valid category 2300 if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) { 2301 $post_category = array(get_option('default_category')); 2302 } 2303 2304 if ( empty($post_author) ) 2305 $post_author = $user_ID; 2306 2307 $post_type = 'attachment'; 2308 $post_status = 'inherit'; 2309 2310 // Are we updating or creating? 2311 if ( !empty($ID) ) { 2312 $update = true; 2313 $post_ID = (int) $ID; 2314 } else { 2315 $update = false; 2316 $post_ID = 0; 2317 } 2318 2319 // Create a valid post name. 2320 if ( empty($post_name) ) 2321 $post_name = sanitize_title($post_title); 2322 else 2323 $post_name = sanitize_title($post_name); 2324 2325 // expected_slashed ($post_name) 2326 $post_name_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_status = 'inherit' AND ID != %d LIMIT 1", $post_name, $post_ID)); 2327 2328 if ($post_name_check) { 2329 $suffix = 2; 2330 while ($post_name_check) { 2331 $alt_post_name = $post_name . "-$suffix"; 2332 // expected_slashed ($alt_post_name, $post_name) 2333 $post_name_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_status = 'inherit' AND ID != %d AND post_parent = %d LIMIT 1", $alt_post_name, $post_ID, $post_parent)); 2334 $suffix++; 2335 } 2336 $post_name = $alt_post_name; 2337 } 2338 2339 if ( empty($post_date) ) 2340 $post_date = current_time('mysql'); 2341 if ( empty($post_date_gmt) ) 2342 $post_date_gmt = current_time('mysql', 1); 2343 2344 if ( empty($post_modified) ) 2345 $post_modified = $post_date; 2346 if ( empty($post_modified_gmt) ) 2347 $post_modified_gmt = $post_date_gmt; 2348 2349 if ( empty($comment_status) ) { 2350 if ( $update ) 2351 $comment_status = 'closed'; 2352 else 2353 $comment_status = get_option('default_comment_status'); 2354 } 2355 if ( empty($ping_status) ) 2356 $ping_status = get_option('default_ping_status'); 2357 2358 if ( isset($to_ping) ) 2359 $to_ping = preg_replace('|\s+|', "\n", $to_ping); 2360 else 2361 $to_ping = ''; 2362 2363 if ( isset($post_parent) ) 2364 $post_parent = (int) $post_parent; 2365 else 2366 $post_parent = 0; 2367 2368 if ( isset($menu_order) ) 2369 $menu_order = (int) $menu_order; 2370 else 2371 $menu_order = 0; 2372 2373 if ( !isset($post_password) ) 2374 $post_password = ''; 2375 2376 if ( ! isset($pinged) ) 2377 $pinged = ''; 2378 2379 // expected_slashed (everything!) 2380 $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' ) ); 2381 $data = stripslashes_deep( $data ); 2382 2383 if ( $update ) { 2384 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) ); 2385 } else { 2386 // If there is a suggested ID, use it if not already present 2387 if ( !empty($import_id) ) { 2388 $import_id = (int) $import_id; 2389 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) { 2390 $data['ID'] = $import_id; 2391 } 2392 } 2393 2394 $wpdb->insert( $wpdb->posts, $data ); 2395 $post_ID = (int) $wpdb->insert_id; 2396 } 2397 2398 if ( empty($post_name) ) { 2399 $post_name = sanitize_title($post_title, $post_ID); 2400 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) ); 2401 } 2402 2403 wp_set_post_categories($post_ID, $post_category); 2404 2405 if ( $file ) 2406 update_attached_file( $post_ID, $file ); 2407 2408 clean_post_cache($post_ID); 2409 2410 if ( $update) { 2411 do_action('edit_attachment', $post_ID); 2412 } else { 2413 do_action('add_attachment', $post_ID); 2414 } 2415 2416 return $post_ID; 2417 } 2418 2419 /** 2420 * Delete an attachment. 2421 * 2422 * Will remove the file also, when the attachment is removed. Removes all post 2423 * meta fields, taxonomy, comments, etc associated with the attachment (except 2424 * the main post). 2425 * 2426 * @since 2.0.0 2427 * @uses $wpdb 2428 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID. 2429 * 2430 * @param int $postid Attachment ID. 2431 * @return mixed False on failure. Post data on success. 2432 */ 2433 function wp_delete_attachment($postid) { 2434 global $wpdb; 2435 2436 if ( !$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) ) 2437 return $post; 2438 2439 if ( 'attachment' != $post->post_type ) 2440 return false; 2441 2442 $meta = wp_get_attachment_metadata( $postid ); 2443 $file = get_attached_file( $postid ); 2444 2445 /** @todo Delete for pluggable post taxonomies too */ 2446 wp_delete_object_term_relationships($postid, array('category', 'post_tag')); 2447 2448 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid )); 2449 2450 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid )); 2451 2452 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d ", $postid )); 2453 2454 $uploadPath = wp_upload_dir(); 2455 2456 if ( ! empty($meta['thumb']) ) { 2457 // Don't delete the thumb if another attachment uses it 2458 if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%'.$meta['thumb'].'%', $postid)) ) { 2459 $thumbfile = str_replace(basename($file), $meta['thumb'], $file); 2460 $thumbfile = apply_filters('wp_delete_file', $thumbfile); 2461 @ unlink( path_join($uploadPath['basedir'], $thumbfile) ); 2462 } 2463 } 2464 2465 // remove intermediate images if there are any 2466 $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large')); 2467 foreach ( $sizes as $size ) { 2468 if ( $intermediate = image_get_intermediate_size($postid, $size) ) { 2469 $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']); 2470 @ unlink( path_join($uploadPath['basedir'], $intermediate_file) ); 2471 } 2472 } 2473 2474 $file = apply_filters('wp_delete_file', $file); 2475 2476 if ( ! empty($file) ) 2477 @ unlink($file); 2478 2479 clean_post_cache($postid); 2480 2481 do_action('delete_attachment', $postid); 2482 2483 return $post; 2484 } 2485 2486 /** 2487 * Retrieve attachment meta field for attachment ID. 2488 * 2489 * @since 2.1.0 2490 * 2491 * @param int $post_id Attachment ID 2492 * @param bool $unfiltered Optional, default is false. If true, filters are not run. 2493 * @return string|bool Attachment meta field. False on failure. 2494 */ 2495 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) { 2496 $post_id = (int) $post_id; 2497 if ( !$post =& get_post( $post_id ) ) 2498 return false; 2499 2500 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true ); 2501 if ( $unfiltered ) 2502 return $data; 2503 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID ); 2504 } 2505 2506 /** 2507 * Update metadata for an attachment. 2508 * 2509 * @since 2.1.0 2510 * 2511 * @param int $post_id Attachment ID. 2512 * @param array $data Attachment data. 2513 * @return int 2514 */ 2515 function wp_update_attachment_metadata( $post_id, $data ) { 2516 $post_id = (int) $post_id; 2517 if ( !$post =& get_post( $post_id ) ) 2518 return false; 2519 2520 $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ); 2521 2522 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data); 2523 } 2524 2525 /** 2526 * Retrieve the URL for an attachment. 2527 * 2528 * @since 2.1.0 2529 * 2530 * @param int $post_id Attachment ID. 2531 * @return string 2532 */ 2533 function wp_get_attachment_url( $post_id = 0 ) { 2534 $post_id = (int) $post_id; 2535 if ( !$post =& get_post( $post_id ) ) 2536 return false; 2537 2538 $url = ''; 2539 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file 2540 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory 2541 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location 2542 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location 2543 elseif ( false !== strpos($file, 'wp-content/uploads') ) 2544 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 ); 2545 else 2546 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir. 2547 } 2548 } 2549 2550 if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this. 2551 $url = get_the_guid( $post->ID ); 2552 2553 if ( 'attachment' != $post->post_type || empty($url) ) 2554 return false; 2555 2556 return apply_filters( 'wp_get_attachment_url', $url, $post->ID ); 2557 } 2558 2559 /** 2560 * Retrieve thumbnail for an attachment. 2561 * 2562 * @since 2.1.0 2563 * 2564 * @param int $post_id Attachment ID. 2565 * @return mixed False on failure. Thumbnail file path on success. 2566 */ 2567 function wp_get_attachment_thumb_file( $post_id = 0 ) { 2568 $post_id = (int) $post_id; 2569 if ( !$post =& get_post( $post_id ) ) 2570 return false; 2571 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) ) 2572 return false; 2573 2574 $file = get_attached_file( $post->ID ); 2575 2576 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) 2577 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID ); 2578 return false; 2579 } 2580 2581 /** 2582 * Retrieve URL for an attachment thumbnail. 2583 * 2584 * @since 2.1.0 2585 * 2586 * @param int $post_id Attachment ID 2587 * @return string|bool False on failure. Thumbnail URL on success. 2588 */ 2589 function wp_get_attachment_thumb_url( $post_id = 0 ) { 2590 $post_id = (int) $post_id; 2591 if ( !$post =& get_post( $post_id ) ) 2592 return false; 2593 if ( !$url = wp_get_attachment_url( $post->ID ) ) 2594 return false; 2595 2596 $sized = image_downsize( $post_id, 'thumbnail' ); 2597 if ( $sized ) 2598 return $sized[0]; 2599 2600 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) ) 2601 return false; 2602 2603 $url = str_replace(basename($url), basename($thumb), $url); 2604 2605 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID ); 2606 } 2607 2608 /** 2609 * Check if the attachment is an image. 2610 * 2611 * @since 2.1.0 2612 * 2613 * @param int $post_id Attachment ID 2614 * @return bool 2615 */ 2616 function wp_attachment_is_image( $post_id = 0 ) { 2617 $post_id = (int) $post_id; 2618 if ( !$post =& get_post( $post_id ) ) 2619 return false; 2620 2621 if ( !$file = get_attached_file( $post->ID ) ) 2622 return false; 2623 2624 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false; 2625 2626 $image_exts = array('jpg', 'jpeg', 'gif', 'png'); 2627 2628 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) ) 2629 return true; 2630 return false; 2631 } 2632 2633 /** 2634 * Retrieve the icon for a MIME type. 2635 * 2636 * @since 2.1.0 2637 * 2638 * @param string $mime MIME type 2639 * @return string|bool 2640 */ 2641 function wp_mime_type_icon( $mime = 0 ) { 2642 if ( !is_numeric($mime) ) 2643 $icon = wp_cache_get("mime_type_icon_$mime"); 2644 if ( empty($icon) ) { 2645 $post_id = 0; 2646 $post_mimes = array(); 2647 if ( is_numeric($mime) ) { 2648 $mime = (int) $mime; 2649 if ( $post =& get_post( $mime ) ) { 2650 $post_id = (int) $post->ID; 2651 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid); 2652 if ( !empty($ext) ) { 2653 $post_mimes[] = $ext; 2654 if ( $ext_type = wp_ext2type( $ext ) ) 2655 $post_mimes[] = $ext_type; 2656 } 2657 $mime = $post->post_mime_type; 2658 } else { 2659 $mime = 0; 2660 } 2661 } else { 2662 $post_mimes[] = $mime; 2663 } 2664 2665 $icon_files = wp_cache_get('icon_files'); 2666 2667 if ( !is_array($icon_files) ) { 2668 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' ); 2669 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') ); 2670 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) ); 2671 $icon_files = array(); 2672 while ( $dirs ) { 2673 $dir = array_shift($keys = array_keys($dirs)); 2674 $uri = array_shift($dirs); 2675 if ( $dh = opendir($dir) ) { 2676 while ( false !== $file = readdir($dh) ) { 2677 $file = basename($file); 2678 if ( substr($file, 0, 1) == '.' ) 2679 continue; 2680 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) { 2681 if ( is_dir("$dir/$file") ) 2682 $dirs["$dir/$file"] = "$uri/$file"; 2683 continue; 2684 } 2685 $icon_files["$dir/$file"] = "$uri/$file"; 2686 } 2687 closedir($dh); 2688 } 2689 } 2690 wp_cache_set('icon_files', $icon_files, 600); 2691 } 2692 2693 // Icon basename - extension = MIME wildcard 2694 foreach ( $icon_files as $file => $uri ) 2695 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file]; 2696 2697 if ( ! empty($mime) ) { 2698 $post_mimes[] = substr($mime, 0, strpos($mime, '/')); 2699 $post_mimes[] = substr($mime, strpos($mime, '/') + 1); 2700 $post_mimes[] = str_replace('/', '_', $mime); 2701 } 2702 2703 $matches = wp_match_mime_types(array_keys($types), $post_mimes); 2704 $matches['default'] = array('default'); 2705 2706 foreach ( $matches as $match => $wilds ) { 2707 if ( isset($types[$wilds[0]])) { 2708 $icon = $types[$wilds[0]]; 2709 if ( !is_numeric($mime) ) 2710 wp_cache_set("mime_type_icon_$mime", $icon); 2711 break; 2712 } 2713 } 2714 } 2715 2716 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type. 2717 } 2718 2719 /** 2720 * Checked for changed slugs for published posts and save old slug. 2721 * 2722 * The function is used along with form POST data. It checks for the wp-old-slug 2723 * POST field. Will only be concerned with published posts and the slug actually 2724 * changing. 2725 * 2726 * If the slug was changed and not already part of the old slugs then it will be 2727 * added to the post meta field ('_wp_old_slug') for storing old slugs for that 2728 * post. 2729 * 2730 * The most logically usage of this function is redirecting changed posts, so 2731 * that those that linked to an changed post will be redirected to the new post. 2732 * 2733 * @since 2.1.0 2734 * 2735 * @param int $post_id Post ID. 2736 * @return int Same as $post_id 2737 */ 2738 function wp_check_for_changed_slugs($post_id) { 2739 if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) ) 2740 return $post_id; 2741 2742 $post = &get_post($post_id); 2743 2744 // we're only concerned with published posts 2745 if ( $post->post_status != 'publish' || $post->post_type != 'post' ) 2746 return $post_id; 2747 2748 // only bother if the slug has changed 2749 if ( $post->post_name == $_POST['wp-old-slug'] ) 2750 return $post_id; 2751 2752 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug'); 2753 2754 // if we haven't added this old slug before, add it now 2755 if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) ) 2756 add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']); 2757 2758 // if the new slug was used previously, delete it from the list 2759 if ( in_array($post->post_name, $old_slugs) ) 2760 delete_post_meta($post_id, '_wp_old_slug', $post->post_name); 2761 2762 return $post_id; 2763 } 2764 2765 /** 2766 * Retrieve the private post SQL based on capability. 2767 * 2768 * This function provides a standardized way to appropriately select on the 2769 * post_status of posts/pages. The function will return a piece of SQL code that 2770 * can be added to a WHERE clause; this SQL is constructed to allow all 2771 * published posts, and all private posts to which the user has access. 2772 * 2773 * It also allows plugins that define their own post type to control the cap by 2774 * using the hook 'pub_priv_sql_capability'. The plugin is expected to return 2775 * the capability the user must have to read the private post type. 2776 * 2777 * @since 2.2.0 2778 * 2779 * @uses $user_ID 2780 * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types. 2781 * 2782 * @param string $post_type currently only supports 'post' or 'page'. 2783 * @return string SQL code that can be added to a where clause. 2784 */ 2785 function get_private_posts_cap_sql($post_type) { 2786 global $user_ID; 2787 $cap = ''; 2788 2789 // Private posts 2790 if ($post_type == 'post') { 2791 $cap = 'read_private_posts'; 2792 // Private pages 2793 } elseif ($post_type == 'page') { 2794 $cap = 'read_private_pages'; 2795 // Dunno what it is, maybe plugins have their own post type? 2796 } else { 2797 $cap = apply_filters('pub_priv_sql_capability', $cap); 2798 2799 if (empty($cap)) { 2800 // We don't know what it is, filters don't change anything, 2801 // so set the SQL up to return nothing. 2802 return '1 = 0'; 2803 } 2804 } 2805 2806 $sql = '(post_status = \'publish\''; 2807 2808 if (current_user_can($cap)) { 2809 // Does the user have the capability to view private posts? Guess so. 2810 $sql .= ' OR post_status = \'private\''; 2811 } elseif (is_user_logged_in()) { 2812 // Users can view their own private posts. 2813 $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\''; 2814 } 2815 2816 $sql .= ')'; 2817 2818 return $sql; 2819 } 2820 2821 /** 2822 * Retrieve the date the the last post was published. 2823 * 2824 * The server timezone is the default and is the difference between GMT and 2825 * server time. The 'blog' value is the date when the last post was posted. The 2826 * 'gmt' is when the last post was posted in GMT formatted date. 2827 * 2828 * @since 0.71 2829 * 2830 * @uses $wpdb 2831 * @uses $blog_id 2832 * @uses apply_filters() Calls 'get_lastpostdate' filter 2833 * 2834 * @global mixed $cache_lastpostdate Stores the last post date 2835 * @global mixed $pagenow The current page being viewed 2836 * 2837 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. 2838 * @return string The date of the last post. 2839 */ 2840 function get_lastpostdate($timezone = 'server') { 2841 global $cache_lastpostdate, $wpdb, $blog_id; 2842 $add_seconds_server = date('Z'); 2843 if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) { 2844 switch(strtolower($timezone)) { 2845 case 'gmt': 2846 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1"); 2847 break; 2848 case 'blog': 2849 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1"); 2850 break; 2851 case 'server': 2852 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1"); 2853 break; 2854 } 2855 $cache_lastpostdate[$blog_id][$timezone] = $lastpostdate; 2856 } else { 2857 $lastpostdate = $cache_lastpostdate[$blog_id][$timezone]; 2858 } 2859 return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone ); 2860 } 2861 2862 /** 2863 * Retrieve last post modified date depending on timezone. 2864 * 2865 * The server timezone is the default and is the difference between GMT and 2866 * server time. The 'blog' value is just when the last post was modified. The 2867 * 'gmt' is when the last post was modified in GMT time. 2868 * 2869 * @since 1.2.0 2870 * @uses $wpdb 2871 * @uses $blog_id 2872 * @uses apply_filters() Calls 'get_lastpostmodified' filter 2873 * 2874 * @global mixed $cache_lastpostmodified Stores the date the last post was modified 2875 * 2876 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. 2877 * @return string The date the post was last modified. 2878 */ 2879 function get_lastpostmodified($timezone = 'server') { 2880 global $cache_lastpostmodified, $wpdb, $blog_id; 2881 $add_seconds_server = date('Z'); 2882 if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) { 2883 switch(strtolower($timezone)) { 2884 case 'gmt': 2885 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1"); 2886 break; 2887 case 'blog': 2888 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1"); 2889 break; 2890 case 'server': 2891 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1"); 2892 break; 2893 } 2894 $lastpostdate = get_lastpostdate($timezone); 2895 if ( $lastpostdate > $lastpostmodified ) { 2896 $lastpostmodified = $lastpostdate; 2897 } 2898 $cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified; 2899 } else { 2900 $lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone]; 2901 } 2902 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone ); 2903 } 2904 2905 /** 2906 * Updates posts in cache. 2907 * 2908 * @usedby update_page_cache() Aliased by this function. 2909 * 2910 * @package WordPress 2911 * @subpackage Cache 2912 * @since 1.5.1 2913 * 2914 * @param array $posts Array of post objects 2915 */ 2916 function update_post_cache(&$posts) { 2917 if ( !$posts ) 2918 return; 2919 2920 foreach ( $posts as $post ) 2921 wp_cache_add($post->ID, $post, 'posts'); 2922 } 2923 2924 /** 2925 * Will clean the post in the cache. 2926 * 2927 * Cleaning means delete from the cache of the post. Will call to clean the term 2928 * object cache associated with the post ID. 2929 * 2930 * @package WordPress 2931 * @subpackage Cache 2932 * @since 2.0.0 2933 * 2934 * @uses do_action() Will call the 'clean_post_cache' hook action. 2935 * 2936 * @param int $id The Post ID in the cache to clean 2937 */ 2938 function clean_post_cache($id) { 2939 global $_wp_suspend_cache_invalidation, $wpdb; 2940 2941 if ( !empty($_wp_suspend_cache_invalidation) ) 2942 return; 2943 2944 $id = (int) $id; 2945 2946 wp_cache_delete($id, 'posts'); 2947 wp_cache_delete($id, 'post_meta'); 2948 2949 clean_object_term_cache($id, 'post'); 2950 2951 wp_cache_delete( 'wp_get_archives', 'general' ); 2952 2953 do_action('clean_post_cache', $id); 2954 2955 if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) { 2956 foreach( $children as $cid ) 2957 clean_post_cache( $cid ); 2958 } 2959 } 2960 2961 /** 2962 * Alias of update_post_cache(). 2963 * 2964 * @see update_post_cache() Posts and pages are the same, alias is intentional 2965 * 2966 * @package WordPress 2967 * @subpackage Cache 2968 * @since 1.5.1 2969 * 2970 * @param array $pages list of page objects 2971 */ 2972 function update_page_cache(&$pages) { 2973 update_post_cache($pages); 2974 } 2975 2976 /** 2977 * Will clean the page in the cache. 2978 * 2979 * Clean (read: delete) page from cache that matches $id. Will also clean cache 2980 * associated with 'all_page_ids' and 'get_pages'. 2981 * 2982 * @package WordPress 2983 * @subpackage Cache 2984 * @since 2.0.0 2985 * 2986 * @uses do_action() Will call the 'clean_page_cache' hook action. 2987 * 2988 * @param int $id Page ID to clean 2989 */ 2990 function clean_page_cache($id) { 2991 clean_post_cache($id); 2992 2993 wp_cache_delete( 'all_page_ids', 'posts' ); 2994 wp_cache_delete( 'get_pages', 'posts' ); 2995 2996 do_action('clean_page_cache', $id); 2997 } 2998 2999 /** 3000 * Call major cache updating functions for list of Post objects. 3001 * 3002 * @package WordPress 3003 * @subpackage Cache 3004 * @since 1.5.0 3005 * 3006 * @uses $wpdb 3007 * @uses update_post_cache() 3008 * @uses update_object_term_cache() 3009 * @uses update_postmeta_cache() 3010 * 3011 * @param array $posts Array of Post objects 3012 */ 3013 function update_post_caches(&$posts) { 3014 // No point in doing all this work if we didn't match any posts. 3015 if ( !$posts ) 3016 return; 3017 3018 update_post_cache($posts); 3019 3020 $post_ids = array(); 3021 3022 for ($i = 0; $i < count($posts); $i++) 3023 $post_ids[] = $posts[$i]->ID; 3024 3025 update_object_term_cache($post_ids, 'post'); 3026 3027 update_postmeta_cache($post_ids); 3028 } 3029 3030 /** 3031 * Updates metadata cache for list of post IDs. 3032 * 3033 * Performs SQL query to retrieve the metadata for the post IDs and updates the 3034 * metadata cache for the posts. Therefore, the functions, which call this 3035 * function, do not need to perform SQL queries on their own. 3036 * 3037 * @package WordPress 3038 * @subpackage Cache 3039 * @since 2.1.0 3040 * 3041 * @uses $wpdb 3042 * 3043 * @param array $post_ids List of post IDs. 3044 * @return bool|array Returns false if there is nothing to update or an array of metadata. 3045 */ 3046 function update_postmeta_cache($post_ids) { 3047 global $wpdb; 3048 3049 if ( empty( $post_ids ) ) 3050 return false; 3051 3052 if ( !is_array($post_ids) ) { 3053 $post_ids = preg_replace('|[^0-9,]|', '', $post_ids); 3054 $post_ids = explode(',', $post_ids); 3055 } 3056 3057 $post_ids = array_map('intval', $post_ids); 3058 3059 $ids = array(); 3060 foreach ( (array) $post_ids as $id ) { 3061 if ( false === wp_cache_get($id, 'post_meta') ) 3062 $ids[] = $id; 3063 } 3064 3065 if ( empty( $ids ) ) 3066 return false; 3067 3068 // Get post-meta info 3069 $id_list = join(',', $ids); 3070 $cache = array(); 3071 if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN ($id_list)", ARRAY_A) ) { 3072 foreach ( (array) $meta_list as $metarow) { 3073 $mpid = (int) $metarow['post_id']; 3074 $mkey = $metarow['meta_key']; 3075 $mval = $metarow['meta_value']; 3076 3077 // Force subkeys to be array type: 3078 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) ) 3079 $cache[$mpid] = array(); 3080 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) ) 3081 $cache[$mpid][$mkey] = array(); 3082 3083 // Add a value to the current pid/key: 3084 $cache[$mpid][$mkey][] = $mval; 3085 } 3086 } 3087 3088 foreach ( (array) $ids as $id ) { 3089 if ( ! isset($cache[$id]) ) 3090 $cache[$id] = array(); 3091 } 3092 3093 foreach ( (array) array_keys($cache) as $post) 3094 wp_cache_set($post, $cache[$post], 'post_meta'); 3095 3096 return $cache; 3097 } 3098 3099 // 3100 // Hooks 3101 // 3102 3103 /** 3104 * Hook for managing future post transitions to published. 3105 * 3106 * @since 2.3.0 3107 * @access private 3108 * @uses $wpdb 3109 * 3110 * @param string $new_status New post status 3111 * @param string $old_status Previous post status 3112 * @param object $post Object type containing the post information 3113 */ 3114 function _transition_post_status($new_status, $old_status, $post) { 3115 global $wpdb; 3116 3117 if ( $old_status != 'publish' && $new_status == 'publish' ) { 3118 // Reset GUID if transitioning to publish and it is empty 3119 if ( '' == get_the_guid($post->ID) ) 3120 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) ); 3121 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish 3122 } 3123 3124 // Always clears the hook in case the post status bounced from future to draft. 3125 wp_clear_scheduled_hook('publish_future_post', $post->ID); 3126 } 3127 3128 /** 3129 * Hook used to schedule publication for a post marked for the future. 3130 * 3131 * The $post properties used and must exist are 'ID' and 'post_date_gmt'. 3132 * 3133 * @since 2.3.0 3134 * 3135 * @param int $deprecated Not Used. Can be set to null. 3136 * @param object $post Object type containing the post information 3137 */ 3138 function _future_post_hook($deprecated = '', $post) { 3139 wp_clear_scheduled_hook( 'publish_future_post', $post->ID ); 3140 wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID)); 3141 } 3142 3143 /** 3144 * Hook to schedule pings and enclosures when a post is published. 3145 * 3146 * @since 2.3.0 3147 * @uses $wpdb 3148 * @uses XMLRPC_REQUEST 3149 * @uses APP_REQUEST 3150 * @uses do_action Calls 'xmlprc_publish_post' action if XMLRPC_REQUEST is defined. Calls 'app_publish_post' 3151 * action if APP_REQUEST is defined. 3152 * 3153 * @param int $post_id The ID in the database table of the post being published 3154 */ 3155 function _publish_post_hook($post_id) { 3156 global $wpdb; 3157 3158 if ( defined('XMLRPC_REQUEST') ) 3159 do_action('xmlrpc_publish_post', $post_id); 3160 if ( defined('APP_REQUEST') ) 3161 do_action('app_publish_post', $post_id); 3162 3163 if ( defined('WP_IMPORTING') ) 3164 return; 3165 3166 $data = array( 'post_id' => $post_id, 'meta_value' => '1' ); 3167 if ( get_option('default_pingback_flag') ) 3168 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) ); 3169 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) ); 3170 wp_schedule_single_event(time(), 'do_pings'); 3171 } 3172 3173 /** 3174 * Hook used to prevent page/post cache and rewrite rules from staying dirty. 3175 * 3176 * Does two things. If the post is a page and has a template then it will 3177 * update/add that template to the meta. For both pages and posts, it will clean 3178 * the post cache to make sure that the cache updates to the changes done 3179 * recently. For pages, the rewrite rules of WordPress are flushed to allow for 3180 * any changes. 3181 * 3182 * The $post parameter, only uses 'post_type' property and 'page_template' 3183 * property. 3184 * 3185 * @since 2.3.0 3186 * @uses $wp_rewrite Flushes Rewrite Rules. 3187 * 3188 * @param int $post_id The ID in the database table for the $post 3189 * @param object $post Object type containing the post information 3190 */ 3191 function _save_post_hook($post_id, $post) { 3192 if ( $post->post_type == 'page' ) { 3193 clean_page_cache($post_id); 3194 // Avoid flushing rules for every post during import. 3195 if ( !defined('WP_IMPORTING') ) { 3196 global $wp_rewrite; 3197 $wp_rewrite->flush_rules(); 3198 } 3199 } else { 3200 clean_post_cache($post_id); 3201 } 3202 } 3203 3204 /** 3205 * Retrieve post ancestors and append to post ancestors property. 3206 * 3207 * Will only retrieve ancestors once, if property is already set, then nothing 3208 * will be done. If there is not a parent post, or post ID and post parent ID 3209 * are the same then nothing will be done. 3210 * 3211 * The parameter is passed by reference, so nothing needs to be returned. The 3212 * property will be updated and can be referenced after the function is 3213 * complete. The post parent will be an ancestor and the parent of the post 3214 * parent will be an ancestor. There will only be two ancestors at the most. 3215 * 3216 * @access private 3217 * @since unknown 3218 * @uses $wpdb 3219 * 3220 * @param object $_post Post data. 3221 * @return null When nothing needs to be done. 3222 */ 3223 function _get_post_ancestors(&$_post) { 3224 global $wpdb; 3225 3226 if ( isset($_post->ancestors) ) 3227 return; 3228 3229 $_post->ancestors = array(); 3230 3231 if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent ) 3232 return; 3233 3234 $id = $_post->ancestors[] = $_post->post_parent; 3235 while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) { 3236 if ( $id == $ancestor ) 3237 break; 3238 $id = $_post->ancestors[] = $ancestor; 3239 } 3240 } 3241 3242 /** 3243 * Determines which fields of posts are to be saved in revisions. 3244 * 3245 * Does two things. If passed a post *array*, it will return a post array ready 3246 * to be insterted into the posts table as a post revision. Otherwise, returns 3247 * an array whose keys are the post fields to be saved for post revisions. 3248 * 3249 * @package WordPress 3250 * @subpackage Post_Revisions 3251 * @since 2.6.0 3252 * @access private 3253 * 3254 * @param array $post Optional a post array to be processed for insertion as a post revision. 3255 * @param bool $autosave optional Is the revision an autosave? 3256 * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned. 3257 */ 3258 function _wp_post_revision_fields( $post = null, $autosave = false ) { 3259 static $fields = false; 3260 3261 if ( !$fields ) { 3262 // Allow these to be versioned 3263 $fields = array( 3264 'post_title' => __( 'Title' ), 3265 'post_content' => __( 'Content' ), 3266 'post_excerpt' => __( 'Excerpt' ), 3267 ); 3268 3269 // Runs only once 3270 $fields = apply_filters( '_wp_post_revision_fields', $fields ); 3271 3272 // WP uses these internally either in versioning or elsewhere - they cannot be versioned 3273 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect ) 3274 unset( $fields[$protect] ); 3275 } 3276 3277 if ( !is_array($post) ) 3278 return $fields; 3279 3280 $return = array(); 3281 foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field ) 3282 $return[$field] = $post[$field]; 3283 3284 $return['post_parent'] = $post['ID']; 3285 $return['post_status'] = 'inherit'; 3286 $return['post_type'] = 'revision'; 3287 $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision"; 3288 $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : ''; 3289 $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : ''; 3290 3291 return $return; 3292 } 3293 3294 /** 3295 * Saves an already existing post as a post revision. 3296 * 3297 * Typically used immediately prior to post updates. 3298 * 3299 * @package WordPress 3300 * @subpackage Post_Revisions 3301 * @since 2.6.0 3302 * 3303 * @uses _wp_put_post_revision() 3304 * 3305 * @param int $post_id The ID of the post to save as a revision. 3306 * @return mixed Null or 0 if error, new revision ID, if success. 3307 */ 3308 function wp_save_post_revision( $post_id ) { 3309 // We do autosaves manually with wp_create_post_autosave() 3310 if ( @constant( 'DOING_AUTOSAVE' ) ) 3311 return; 3312 3313 // WP_POST_REVISIONS = 0, false 3314 if ( !constant('WP_POST_REVISIONS') ) 3315 return; 3316 3317 if ( !$post = get_post( $post_id, ARRAY_A ) ) 3318 return; 3319 3320 if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) ) 3321 return; 3322 3323 $return = _wp_put_post_revision( $post ); 3324 3325 // WP_POST_REVISIONS = true (default), -1 3326 if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 ) 3327 return $return; 3328 3329 // all revisions and (possibly) one autosave 3330 $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) ); 3331 3332 // WP_POST_REVISIONS = (int) (# of autasaves to save) 3333 $delete = count($revisions) - WP_POST_REVISIONS; 3334 3335 if ( $delete < 1 ) 3336 return $return; 3337 3338 $revisions = array_slice( $revisions, 0, $delete ); 3339 3340 for ( $i = 0; isset($revisions[$i]); $i++ ) { 3341 if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) ) 3342 continue; 3343 wp_delete_post_revision( $revisions[$i]->ID ); 3344 } 3345 3346 return $return; 3347 } 3348 3349 /** 3350 * Retrieve the autosaved data of the specified post. 3351 * 3352 * Returns a post object containing the information that was autosaved for the 3353 * specified post. 3354 * 3355 * @package WordPress 3356 * @subpackage Post_Revisions 3357 * @since 2.6.0 3358 * 3359 * @param int $post_id The post ID. 3360 * @return object|bool The autosaved data or false on failure or when no autosave exists. 3361 */ 3362 function wp_get_post_autosave( $post_id ) { 3363 3364 if ( !$post = get_post( $post_id ) ) 3365 return false; 3366 3367 $q = array( 3368 'name' => "{$post->ID}-autosave", 3369 'post_parent' => $post->ID, 3370 'post_type' => 'revision', 3371 'post_status' => 'inherit' 3372 ); 3373 3374 // Use WP_Query so that the result gets cached 3375 $autosave_query = new WP_Query; 3376 3377 add_action( 'parse_query', '_wp_get_post_autosave_hack' ); 3378 $autosave = $autosave_query->query( $q ); 3379 remove_action( 'parse_query', '_wp_get_post_autosave_hack' ); 3380 3381 if ( $autosave && is_array($autosave) && is_object($autosave[0]) ) 3382 return $autosave[0]; 3383 3384 return false; 3385 } 3386 3387 /** 3388 * Internally used to hack WP_Query into submission. 3389 * 3390 * @package WordPress 3391 * @subpackage Post_Revisions 3392 * @since 2.6.0 3393 * 3394 * @param object $query WP_Query object 3395 */ 3396 function _wp_get_post_autosave_hack( $query ) { 3397 $query->is_single = false; 3398 } 3399 3400 /** 3401 * Determines if the specified post is a revision. 3402 * 3403 * @package WordPress 3404 * @subpackage Post_Revisions 3405 * @since 2.6.0 3406 * 3407 * @param int|object $post Post ID or post object. 3408 * @return bool|int False if not a revision, ID of revision's parent otherwise. 3409 */ 3410 function wp_is_post_revision( $post ) { 3411 if ( !$post = wp_get_post_revision( $post ) ) 3412 return false; 3413 return (int) $post->post_parent; 3414 } 3415 3416 /** 3417 * Determines if the specified post is an autosave. 3418 * 3419 * @package WordPress 3420 * @subpackage Post_Revisions 3421 * @since 2.6.0 3422 * 3423 * @param int|object $post Post ID or post object. 3424 * @return bool|int False if not a revision, ID of autosave's parent otherwise 3425 */ 3426 function wp_is_post_autosave( $post ) { 3427 if ( !$post = wp_get_post_revision( $post ) ) 3428 return false; 3429 if ( "{$post->post_parent}-autosave" !== $post->post_name ) 3430 return false; 3431 return (int) $post->post_parent; 3432 } 3433 3434 /** 3435 * Inserts post data into the posts table as a post revision. 3436 * 3437 * @package WordPress 3438 * @subpackage Post_Revisions 3439 * @since 2.6.0 3440 * 3441 * @uses wp_insert_post() 3442 * 3443 * @param int|object|array $post Post ID, post object OR post array. 3444 * @param bool $autosave Optional. Is the revision an autosave? 3445 * @return mixed Null or 0 if error, new revision ID if success. 3446 */ 3447 function _wp_put_post_revision( $post = null, $autosave = false ) { 3448 if ( is_object($post) ) 3449 $post = get_object_vars( $post ); 3450 elseif ( !is_array($post) ) 3451 $post = get_post($post, ARRAY_A); 3452 if ( !$post || empty($post['ID']) ) 3453 return; 3454 3455 if ( isset($post['post_type']) && 'revision' == $post['post_type'] ) 3456 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) ); 3457 3458 $post = _wp_post_revision_fields( $post, $autosave ); 3459 3460 $revision_id = wp_insert_post( $post ); 3461 if ( is_wp_error($revision_id) ) 3462 return $revision_id; 3463 3464 if ( $revision_id ) 3465 do_action( '_wp_put_post_revision', $revision_id ); 3466 return $revision_id; 3467 } 3468 3469 /** 3470 * Gets a post revision. 3471 * 3472 * @package WordPress 3473 * @subpackage Post_Revisions 3474 * @since 2.6.0 3475 * 3476 * @uses get_post() 3477 * 3478 * @param int|object $post Post ID or post object 3479 * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N. 3480 * @param string $filter Optional sanitation filter. @see sanitize_post() 3481 * @return mixed Null if error or post object if success 3482 */ 3483 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') { 3484 $null = null; 3485 if ( !$revision = get_post( $post, OBJECT, $filter ) ) 3486 return $revision; 3487 if ( 'revision' !== $revision->post_type ) 3488 return $null; 3489 3490 if ( $output == OBJECT ) { 3491 return $revision; 3492 } elseif ( $output == ARRAY_A ) { 3493 $_revision = get_object_vars($revision); 3494 return $_revision; 3495 } elseif ( $output == ARRAY_N ) { 3496 $_revision = array_values(get_object_vars($revision)); 3497 return $_revision; 3498 } 3499 3500 return $revision; 3501 } 3502 3503 /** 3504 * Restores a post to the specified revision. 3505 * 3506 * Can restore a past using all fields of the post revision, or only selected 3507 * fields. 3508 * 3509 * @package WordPress 3510 * @subpackage Post_Revisions 3511 * @since 2.6.0 3512 * 3513 * @uses wp_get_post_revision() 3514 * @uses wp_update_post() 3515 * 3516 * @param int|object $revision_id Revision ID or revision object. 3517 * @param array $fields Optional. What fields to restore from. Defaults to all. 3518 * @return mixed Null if error, false if no fields to restore, (int) post ID if success. 3519 */ 3520 function wp_restore_post_revision( $revision_id, $fields = null ) { 3521 if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) ) 3522 return $revision; 3523 3524 if ( !is_array( $fields ) ) 3525 $fields = array_keys( _wp_post_revision_fields() ); 3526 3527 $update = array(); 3528 foreach( array_intersect( array_keys( $revision ), $fields ) as $field ) 3529 $update[$field] = $revision[$field]; 3530 3531 if ( !$update ) 3532 return false; 3533 3534 $update['ID'] = $revision['post_parent']; 3535 3536 $post_id = wp_update_post( $update ); 3537 if ( is_wp_error( $post_id ) ) 3538 return $post_id; 3539 3540 if ( $post_id ) 3541 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] ); 3542 3543 return $post_id; 3544 } 3545 3546 /** 3547 * Deletes a revision. 3548 * 3549 * Deletes the row from the posts table corresponding to the specified revision. 3550 * 3551 * @package WordPress 3552 * @subpackage Post_Revisions 3553 * @since 2.6.0 3554 * 3555 * @uses wp_get_post_revision() 3556 * @uses wp_delete_post() 3557 * 3558 * @param int|object $revision_id Revision ID or revision object. 3559 * @param array $fields Optional. What fields to restore from. Defaults to all. 3560 * @return mixed Null if error, false if no fields to restore, (int) post ID if success. 3561 */ 3562 function wp_delete_post_revision( $revision_id ) { 3563 if ( !$revision = wp_get_post_revision( $revision_id ) ) 3564 return $revision; 3565 3566 $delete = wp_delete_post( $revision->ID ); 3567 if ( is_wp_error( $delete ) ) 3568 return $delete; 3569 3570 if ( $delete ) 3571 do_action( 'wp_delete_post_revision', $revision->ID, $revision ); 3572 3573 return $delete; 3574 } 3575 3576 /** 3577 * Returns all revisions of specified post. 3578 * 3579 * @package WordPress 3580 * @subpackage Post_Revisions 3581 * @since 2.6.0 3582 * 3583 * @uses get_children() 3584 * 3585 * @param int|object $post_id Post ID or post object 3586 * @return array empty if no revisions 3587 */ 3588 function wp_get_post_revisions( $post_id = 0, $args = null ) { 3589 if ( !constant('WP_POST_REVISIONS') ) 3590 return array(); 3591 if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) ) 3592 return array(); 3593 3594 $defaults = array( 'order' => 'DESC', 'orderby' => 'date' ); 3595 $args = wp_parse_args( $args, $defaults ); 3596 $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) ); 3597 3598 if ( !$revisions = get_children( $args ) ) 3599 return array(); 3600 return $revisions; 3601 } 3602 3603 function _set_preview($post) { 3604 3605 if ( ! is_object($post) ) 3606 return $post; 3607 3608 $preview = wp_get_post_autosave($post->ID); 3609 3610 if ( ! is_object($preview) ) 3611 return $post; 3612 3613 $preview = sanitize_post($preview); 3614 3615 $post->post_content = $preview->post_content; 3616 $post->post_title = $preview->post_title; 3617 $post->post_excerpt = $preview->post_excerpt; 3618 3619 return $post; 3620 } 3621 3622 function _show_post_preview() { 3623 3624 if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) { 3625 $id = (int) $_GET['preview_id']; 3626 3627 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) ) 3628 wp_die( __('You do not have permission to preview drafts.') ); 3629 3630 add_filter('the_preview', '_set_preview'); 3631 } 3632 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated: Mon Mar 23 16:23:02 2009 | Cross-referenced by PHPXref 0.7 |