[ Index ]

WordPress Cross Reference

title

Body

[close]

/wp-includes/ -> post.php (source)

   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  // Post Type Registration
  12  //
  13  
  14  /**
  15   * Creates the initial post types when 'init' action is fired.
  16   *
  17   * @since 2.9.0
  18   */
  19  function create_initial_post_types() {
  20      register_post_type( 'post', array(
  21          'labels' => array(
  22              'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
  23          ),
  24          'public'  => true,
  25          '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  26          '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  27          'capability_type' => 'post',
  28          'map_meta_cap' => true,
  29          'hierarchical' => false,
  30          'rewrite' => false,
  31          'query_var' => false,
  32          'delete_with_user' => true,
  33          'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
  34      ) );
  35  
  36      register_post_type( 'page', array(
  37          'labels' => array(
  38              'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
  39          ),
  40          'public' => true,
  41          'publicly_queryable' => false,
  42          '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  43          '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  44          'capability_type' => 'page',
  45          'map_meta_cap' => true,
  46          'hierarchical' => true,
  47          'rewrite' => false,
  48          'query_var' => false,
  49          'delete_with_user' => true,
  50          'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
  51      ) );
  52  
  53      register_post_type( 'attachment', array(
  54          'labels' => array(
  55              'name' => _x('Media', 'post type general name'),
  56              'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
  57              'add_new' => _x( 'Add New', 'add new media' ),
  58               'edit_item' => __( 'Edit Media' ),
  59               'view_item' => __( 'View Attachment Page' ),
  60          ),
  61          'public' => true,
  62          'show_ui' => true,
  63          '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  64          '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  65          'capability_type' => 'post',
  66          'capabilities' => array(
  67              'create_posts' => 'upload_files',
  68          ),
  69          'map_meta_cap' => true,
  70          'hierarchical' => false,
  71          'rewrite' => false,
  72          'query_var' => false,
  73          'show_in_nav_menus' => false,
  74          'delete_with_user' => true,
  75          'supports' => array( 'title', 'author', 'comments' ),
  76      ) );
  77  
  78      register_post_type( 'revision', array(
  79          'labels' => array(
  80              'name' => __( 'Revisions' ),
  81              'singular_name' => __( 'Revision' ),
  82          ),
  83          'public' => false,
  84          '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  85          '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
  86          'capability_type' => 'post',
  87          'map_meta_cap' => true,
  88          'hierarchical' => false,
  89          'rewrite' => false,
  90          'query_var' => false,
  91          'can_export' => false,
  92          'delete_with_user' => true,
  93          'supports' => array( 'author' ),
  94      ) );
  95  
  96      register_post_type( 'nav_menu_item', array(
  97          'labels' => array(
  98              'name' => __( 'Navigation Menu Items' ),
  99              'singular_name' => __( 'Navigation Menu Item' ),
 100          ),
 101          'public' => false,
 102          '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
 103          'hierarchical' => false,
 104          'rewrite' => false,
 105          'delete_with_user' => false,
 106          'query_var' => false,
 107      ) );
 108  
 109      register_post_status( 'publish', array(
 110          'label'       => _x( 'Published', 'post' ),
 111          'public'      => true,
 112          '_builtin'    => true, /* internal use only. */
 113          'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
 114      ) );
 115  
 116      register_post_status( 'future', array(
 117          'label'       => _x( 'Scheduled', 'post' ),
 118          'protected'   => true,
 119          '_builtin'    => true, /* internal use only. */
 120          'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
 121      ) );
 122  
 123      register_post_status( 'draft', array(
 124          'label'       => _x( 'Draft', 'post' ),
 125          'protected'   => true,
 126          '_builtin'    => true, /* internal use only. */
 127          'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
 128      ) );
 129  
 130      register_post_status( 'pending', array(
 131          'label'       => _x( 'Pending', 'post' ),
 132          'protected'   => true,
 133          '_builtin'    => true, /* internal use only. */
 134          'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
 135      ) );
 136  
 137      register_post_status( 'private', array(
 138          'label'       => _x( 'Private', 'post' ),
 139          'private'     => true,
 140          '_builtin'    => true, /* internal use only. */
 141          'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
 142      ) );
 143  
 144      register_post_status( 'trash', array(
 145          'label'       => _x( 'Trash', 'post' ),
 146          'internal'    => true,
 147          '_builtin'    => true, /* internal use only. */
 148          'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
 149          'show_in_admin_status_list' => true,
 150      ) );
 151  
 152      register_post_status( 'auto-draft', array(
 153          'label'    => 'auto-draft',
 154          'internal' => true,
 155          '_builtin' => true, /* internal use only. */
 156      ) );
 157  
 158      register_post_status( 'inherit', array(
 159          'label'    => 'inherit',
 160          'internal' => true,
 161          '_builtin' => true, /* internal use only. */
 162          'exclude_from_search' => false,
 163      ) );
 164  }
 165  add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
 166  
 167  /**
 168   * Retrieve attached file path based on attachment ID.
 169   *
 170   * By default the path will go through the 'get_attached_file' filter, but
 171   * passing a true to the $unfiltered argument of get_attached_file() will
 172   * return the file path unfiltered.
 173   *
 174   * The function works by getting the single post meta name, named
 175   * '_wp_attached_file' and returning it. This is a convenience function to
 176   * prevent looking up the meta name and provide a mechanism for sending the
 177   * attached filename through a filter.
 178   *
 179   * @since 2.0.0
 180   *
 181   * @param int $attachment_id Attachment ID.
 182   * @param bool $unfiltered Whether to apply filters.
 183   * @return string|bool The file path to where the attached file should be, false otherwise.
 184   */
 185  function get_attached_file( $attachment_id, $unfiltered = false ) {
 186      $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
 187      // If the file is relative, prepend upload dir
 188      if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
 189          $file = $uploads['basedir'] . "/$file";
 190      if ( $unfiltered )
 191          return $file;
 192      return apply_filters( 'get_attached_file', $file, $attachment_id );
 193  }
 194  
 195  /**
 196   * Update attachment file path based on attachment ID.
 197   *
 198   * Used to update the file path of the attachment, which uses post meta name
 199   * '_wp_attached_file' to store the path of the attachment.
 200   *
 201   * @since 2.1.0
 202   * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
 203   *
 204   * @param int $attachment_id Attachment ID
 205   * @param string $file File path for the attachment
 206   * @return bool True on success, false on failure.
 207   */
 208  function update_attached_file( $attachment_id, $file ) {
 209      if ( !get_post( $attachment_id ) )
 210          return false;
 211  
 212      $file = apply_filters( 'update_attached_file', $file, $attachment_id );
 213      if ( $file = _wp_relative_upload_path( $file ) )
 214          return update_post_meta( $attachment_id, '_wp_attached_file', $file );
 215      else
 216          return delete_post_meta( $attachment_id, '_wp_attached_file' );
 217  }
 218  
 219  /**
 220   * Return relative path to an uploaded file.
 221   *
 222   * The path is relative to the current upload dir.
 223   *
 224   * @since 2.9.0
 225   * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
 226   *
 227   * @param string $path Full path to the file
 228   * @return string relative path on success, unchanged path on failure.
 229   */
 230  function _wp_relative_upload_path( $path ) {
 231      $new_path = $path;
 232  
 233      $uploads = wp_upload_dir();
 234      if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
 235              $new_path = str_replace( $uploads['basedir'], '', $new_path );
 236              $new_path = ltrim( $new_path, '/' );
 237      }
 238  
 239      return apply_filters( '_wp_relative_upload_path', $new_path, $path );
 240  }
 241  
 242  /**
 243   * Retrieve all children of the post parent ID.
 244   *
 245   * Normally, without any enhancements, the children would apply to pages. In the
 246   * context of the inner workings of WordPress, pages, posts, and attachments
 247   * share the same table, so therefore the functionality could apply to any one
 248   * of them. It is then noted that while this function does not work on posts, it
 249   * does not mean that it won't work on posts. It is recommended that you know
 250   * what context you wish to retrieve the children of.
 251   *
 252   * Attachments may also be made the child of a post, so if that is an accurate
 253   * statement (which needs to be verified), it would then be possible to get
 254   * all of the attachments for a post. Attachments have since changed since
 255   * version 2.5, so this is most likely unaccurate, but serves generally as an
 256   * example of what is possible.
 257   *
 258   * The arguments listed as defaults are for this function and also of the
 259   * {@link get_posts()} function. The arguments are combined with the
 260   * get_children defaults and are then passed to the {@link get_posts()}
 261   * function, which accepts additional arguments. You can replace the defaults in
 262   * this function, listed below and the additional arguments listed in the
 263   * {@link get_posts()} function.
 264   *
 265   * The 'post_parent' is the most important argument and important attention
 266   * needs to be paid to the $args parameter. If you pass either an object or an
 267   * integer (number), then just the 'post_parent' is grabbed and everything else
 268   * is lost. If you don't specify any arguments, then it is assumed that you are
 269   * in The Loop and the post parent will be grabbed for from the current post.
 270   *
 271   * The 'post_parent' argument is the ID to get the children. The 'numberposts'
 272   * is the amount of posts to retrieve that has a default of '-1', which is
 273   * used to get all of the posts. Giving a number higher than 0 will only
 274   * retrieve that amount of posts.
 275   *
 276   * The 'post_type' and 'post_status' arguments can be used to choose what
 277   * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
 278   * post types are 'post', 'pages', and 'attachments'. The 'post_status'
 279   * argument will accept any post status within the write administration panels.
 280   *
 281   * @see get_posts() Has additional arguments that can be replaced.
 282   * @internal Claims made in the long description might be inaccurate.
 283   *
 284   * @since 2.0.0
 285   *
 286   * @param mixed $args Optional. User defined arguments for replacing the defaults.
 287   * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
 288   * @return array|bool False on failure and the type will be determined by $output parameter.
 289   */
 290  function get_children($args = '', $output = OBJECT) {
 291      $kids = array();
 292      if ( empty( $args ) ) {
 293          if ( isset( $GLOBALS['post'] ) ) {
 294              $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
 295          } else {
 296              return $kids;
 297          }
 298      } elseif ( is_object( $args ) ) {
 299          $args = array('post_parent' => (int) $args->post_parent );
 300      } elseif ( is_numeric( $args ) ) {
 301          $args = array('post_parent' => (int) $args);
 302      }
 303  
 304      $defaults = array(
 305          'numberposts' => -1, 'post_type' => 'any',
 306          'post_status' => 'any', 'post_parent' => 0,
 307      );
 308  
 309      $r = wp_parse_args( $args, $defaults );
 310  
 311      $children = get_posts( $r );
 312  
 313      if ( ! $children )
 314          return $kids;
 315  
 316      if ( ! empty( $r['fields'] ) )
 317          return $children;
 318  
 319      update_post_cache($children);
 320  
 321      foreach ( $children as $key => $child )
 322          $kids[$child->ID] = $children[$key];
 323  
 324      if ( $output == OBJECT ) {
 325          return $kids;
 326      } elseif ( $output == ARRAY_A ) {
 327          foreach ( (array) $kids as $kid )
 328              $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
 329          return $weeuns;
 330      } elseif ( $output == ARRAY_N ) {
 331          foreach ( (array) $kids as $kid )
 332              $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
 333          return $babes;
 334      } else {
 335          return $kids;
 336      }
 337  }
 338  
 339  /**
 340   * Get extended entry info (<!--more-->).
 341   *
 342   * There should not be any space after the second dash and before the word
 343   * 'more'. There can be text or space(s) after the word 'more', but won't be
 344   * referenced.
 345   *
 346   * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
 347   * the <code><!--more--></code>. The 'extended' key has the content after the
 348   * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text.
 349   *
 350   * @since 1.0.0
 351   *
 352   * @param string $post Post content.
 353   * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text').
 354   */
 355  function get_extended($post) {
 356      //Match the new style more links
 357      if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
 358          list($main, $extended) = explode($matches[0], $post, 2);
 359          $more_text = $matches[1];
 360      } else {
 361          $main = $post;
 362          $extended = '';
 363          $more_text = '';
 364      }
 365  
 366      // ` leading and trailing whitespace
 367      $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
 368      $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
 369      $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
 370  
 371      return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
 372  }
 373  
 374  /**
 375   * Retrieves post data given a post ID or post object.
 376   *
 377   * See {@link sanitize_post()} for optional $filter values. Also, the parameter
 378   * $post, must be given as a variable, since it is passed by reference.
 379   *
 380   * @since 1.5.1
 381   * @link http://codex.wordpress.org/Function_Reference/get_post
 382   *
 383   * @param int|object $post Post ID or post object. Optional, default is the current post from the loop.
 384   * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
 385   * @param string $filter Optional, default is raw.
 386   * @return WP_Post|null WP_Post on success or null on failure
 387   */
 388  function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
 389      if ( empty( $post ) && isset( $GLOBALS['post'] ) )
 390          $post = $GLOBALS['post'];
 391  
 392      if ( is_a( $post, 'WP_Post' ) ) {
 393          $_post = $post;
 394      } elseif ( is_object( $post ) ) {
 395          if ( empty( $post->filter ) ) {
 396              $_post = sanitize_post( $post, 'raw' );
 397              $_post = new WP_Post( $_post );
 398          } elseif ( 'raw' == $post->filter ) {
 399              $_post = new WP_Post( $post );
 400          } else {
 401              $_post = WP_Post::get_instance( $post->ID );
 402          }
 403      } else {
 404          $_post = WP_Post::get_instance( $post );
 405      }
 406  
 407      if ( ! $_post )
 408          return null;
 409  
 410      $_post = $_post->filter( $filter );
 411  
 412      if ( $output == ARRAY_A )
 413          return $_post->to_array();
 414      elseif ( $output == ARRAY_N )
 415          return array_values( $_post->to_array() );
 416  
 417      return $_post;
 418  }
 419  
 420  /**
 421   * WordPress Post class.
 422   *
 423   * @since 3.5.0
 424   *
 425   */
 426  final class WP_Post {
 427  
 428      /**
 429       * Post ID.
 430       *
 431       * @var int
 432       */
 433      public $ID;
 434  
 435      /**
 436       * ID of post author.
 437       *
 438       * A numeric string, for compatibility reasons.
 439       *
 440       * @var string
 441       */
 442      public $post_author = 0;
 443  
 444      /**
 445       * The post's local publication time.
 446       *
 447       * @var string
 448       */
 449      public $post_date = '0000-00-00 00:00:00';
 450  
 451      /**
 452       * The post's GMT publication time.
 453       *
 454       * @var string
 455       */
 456      public $post_date_gmt = '0000-00-00 00:00:00';
 457  
 458      /**
 459       * The post's content.
 460       *
 461       * @var string
 462       */
 463      public $post_content = '';
 464  
 465      /**
 466       * The post's title.
 467       *
 468       * @var string
 469       */
 470      public $post_title = '';
 471  
 472      /**
 473       * The post's excerpt.
 474       *
 475       * @var string
 476       */
 477      public $post_excerpt = '';
 478  
 479      /**
 480       * The post's status.
 481       *
 482       * @var string
 483       */
 484      public $post_status = 'publish';
 485  
 486      /**
 487       * Whether comments are allowed.
 488       *
 489       * @var string
 490       */
 491      public $comment_status = 'open';
 492  
 493      /**
 494       * Whether pings are allowed.
 495       *
 496       * @var string
 497       */
 498      public $ping_status = 'open';
 499  
 500      /**
 501       * The post's password in plain text.
 502       *
 503       * @var string
 504       */
 505      public $post_password = '';
 506  
 507      /**
 508       * The post's slug.
 509       *
 510       * @var string
 511       */
 512      public $post_name = '';
 513  
 514      /**
 515       * URLs queued to be pinged.
 516       *
 517       * @var string
 518       */
 519      public $to_ping = '';
 520  
 521      /**
 522       * URLs that have been pinged.
 523       *
 524       * @var string
 525       */
 526      public $pinged = '';
 527  
 528      /**
 529       * The post's local modified time.
 530       *
 531       * @var string
 532       */
 533      public $post_modified = '0000-00-00 00:00:00';
 534  
 535      /**
 536       * The post's GMT modified time.
 537       *
 538       * @var string
 539       */
 540      public $post_modified_gmt = '0000-00-00 00:00:00';
 541  
 542      /**
 543       * A utility DB field for post content.
 544       *
 545       *
 546       * @var string
 547       */
 548      public $post_content_filtered = '';
 549  
 550      /**
 551       * ID of a post's parent post.
 552       *
 553       * @var int
 554       */
 555      public $post_parent = 0;
 556  
 557      /**
 558       * The unique identifier for a post, not necessarily a URL, used as the feed GUID.
 559       *
 560       * @var string
 561       */
 562      public $guid = '';
 563  
 564      /**
 565       * A field used for ordering posts.
 566       *
 567       * @var int
 568       */
 569      public $menu_order = 0;
 570  
 571      /**
 572       * The post's type, like post or page.
 573       *
 574       * @var string
 575       */
 576      public $post_type = 'post';
 577  
 578      /**
 579       * An attachment's mime type.
 580       *
 581       * @var string
 582       */
 583      public $post_mime_type = '';
 584  
 585      /**
 586       * Cached comment count.
 587       *
 588       * A numeric string, for compatibility reasons.
 589       *
 590       * @var string
 591       */
 592      public $comment_count = 0;
 593  
 594      /**
 595       * Stores the post object's sanitization level.
 596       *
 597       * Does not correspond to a DB field.
 598       *
 599       * @var string
 600       */
 601      public $filter;
 602  
 603  	public static function get_instance( $post_id ) {
 604          global $wpdb;
 605  
 606          $post_id = (int) $post_id;
 607          if ( ! $post_id )
 608              return false;
 609  
 610          $_post = wp_cache_get( $post_id, 'posts' );
 611  
 612          if ( ! $_post ) {
 613              $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
 614  
 615              if ( ! $_post )
 616                  return false;
 617  
 618              $_post = sanitize_post( $_post, 'raw' );
 619              wp_cache_add( $_post->ID, $_post, 'posts' );
 620          } elseif ( empty( $_post->filter ) ) {
 621              $_post = sanitize_post( $_post, 'raw' );
 622          }
 623  
 624          return new WP_Post( $_post );
 625      }
 626  
 627  	public function __construct( $post ) {
 628          foreach ( get_object_vars( $post ) as $key => $value )
 629              $this->$key = $value;
 630      }
 631  
 632  	public function __isset( $key ) {
 633          if ( 'ancestors' == $key )
 634              return true;
 635  
 636          if ( 'page_template' == $key )
 637              return ( 'page' == $this->post_type );
 638  
 639          if ( 'post_category' == $key )
 640             return true;
 641  
 642          if ( 'tags_input' == $key )
 643             return true;
 644  
 645          return metadata_exists( 'post', $this->ID, $key );
 646      }
 647  
 648  	public function __get( $key ) {
 649          if ( 'page_template' == $key && $this->__isset( $key ) ) {
 650              return get_post_meta( $this->ID, '_wp_page_template', true );
 651          }
 652  
 653          if ( 'post_category' == $key ) {
 654              if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
 655                  $terms = get_the_terms( $this, 'category' );
 656  
 657              if ( empty( $terms ) )
 658                  return array();
 659  
 660              return wp_list_pluck( $terms, 'term_id' );
 661          }
 662  
 663          if ( 'tags_input' == $key ) {
 664              if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
 665                  $terms = get_the_terms( $this, 'post_tag' );
 666  
 667              if ( empty( $terms ) )
 668                  return array();
 669  
 670              return wp_list_pluck( $terms, 'name' );
 671          }
 672  
 673          // Rest of the values need filtering
 674  
 675          if ( 'ancestors' == $key )
 676              $value = get_post_ancestors( $this );
 677          else
 678              $value = get_post_meta( $this->ID, $key, true );
 679  
 680          if ( $this->filter )
 681              $value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
 682  
 683          return $value;
 684      }
 685  
 686  	public function filter( $filter ) {
 687          if ( $this->filter == $filter )
 688              return $this;
 689  
 690          if ( $filter == 'raw' )
 691              return self::get_instance( $this->ID );
 692  
 693          return sanitize_post( $this, $filter );
 694      }
 695  
 696  	public function to_array() {
 697          $post = get_object_vars( $this );
 698  
 699          foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
 700              if ( $this->__isset( $key ) )
 701                  $post[ $key ] = $this->__get( $key );
 702          }
 703  
 704          return $post;
 705      }
 706  }
 707  
 708  /**
 709   * Retrieve ancestors of a post.
 710   *
 711   * @since 2.5.0
 712   *
 713   * @param int|object $post Post ID or post object
 714   * @return array Ancestor IDs or empty array if none are found.
 715   */
 716  function get_post_ancestors( $post ) {
 717      $post = get_post( $post );
 718  
 719      if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
 720          return array();
 721  
 722      $ancestors = array();
 723  
 724      $id = $ancestors[] = $post->post_parent;
 725  
 726      while ( $ancestor = get_post( $id ) ) {
 727          // Loop detection: If the ancestor has been seen before, break.
 728          if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
 729              break;
 730  
 731          $id = $ancestors[] = $ancestor->post_parent;
 732      }
 733  
 734      return $ancestors;
 735  }
 736  
 737  /**
 738   * Retrieve data from a post field based on Post ID.
 739   *
 740   * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
 741   * etc and based off of the post object property or key names.
 742   *
 743   * The context values are based off of the taxonomy filter functions and
 744   * supported values are found within those functions.
 745   *
 746   * @since 2.3.0
 747   * @uses sanitize_post_field() See for possible $context values.
 748   *
 749   * @param string $field Post field name.
 750   * @param int|object $post Post ID or post object.
 751   * @param string $context Optional. How to filter the field. Default is 'display'.
 752   * @return string The value of the post field on success, empty string on failure.
 753   */
 754  function get_post_field( $field, $post, $context = 'display' ) {
 755      $post = get_post( $post );
 756  
 757      if ( !$post )
 758          return '';
 759  
 760      if ( !isset($post->$field) )
 761          return '';
 762  
 763      return sanitize_post_field($field, $post->$field, $post->ID, $context);
 764  }
 765  
 766  /**
 767   * Retrieve the mime type of an attachment based on the ID.
 768   *
 769   * This function can be used with any post type, but it makes more sense with
 770   * attachments.
 771   *
 772   * @since 2.0.0
 773   *
 774   * @param int $ID Optional. Post ID. Default is the current post from the loop.
 775   * @return string|bool The mime type on success, false on failure.
 776   */
 777  function get_post_mime_type($ID = '') {
 778      $post = get_post($ID);
 779  
 780      if ( is_object($post) )
 781          return $post->post_mime_type;
 782  
 783      return false;
 784  }
 785  
 786  /**
 787   * Retrieve the post status based on the Post ID.
 788   *
 789   * If the post ID is of an attachment, then the parent post status will be given
 790   * instead.
 791   *
 792   * @since 2.0.0
 793   *
 794   * @param int $ID Optional. Post ID. Default is the current post from the loop.
 795   * @return string|bool Post status on success, false on failure.
 796   */
 797  function get_post_status($ID = '') {
 798      $post = get_post($ID);
 799  
 800      if ( !is_object($post) )
 801          return false;
 802  
 803      if ( 'attachment' == $post->post_type ) {
 804          if ( 'private' == $post->post_status )
 805              return 'private';
 806  
 807          // Unattached attachments are assumed to be published
 808          if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
 809              return 'publish';
 810  
 811          // Inherit status from the parent
 812          if ( $post->post_parent && ( $post->ID != $post->post_parent ) )
 813              return get_post_status($post->post_parent);
 814      }
 815  
 816      return $post->post_status;
 817  }
 818  
 819  /**
 820   * Retrieve all of the WordPress supported post statuses.
 821   *
 822   * Posts have a limited set of valid status values, this provides the
 823   * post_status values and descriptions.
 824   *
 825   * @since 2.5.0
 826   *
 827   * @return array List of post statuses.
 828   */
 829  function get_post_statuses() {
 830      $status = array(
 831          'draft'            => __('Draft'),
 832          'pending'        => __('Pending Review'),
 833          'private'        => __('Private'),
 834          'publish'        => __('Published')
 835      );
 836  
 837      return $status;
 838  }
 839  
 840  /**
 841   * Retrieve all of the WordPress support page statuses.
 842   *
 843   * Pages have a limited set of valid status values, this provides the
 844   * post_status values and descriptions.
 845   *
 846   * @since 2.5.0
 847   *
 848   * @return array List of page statuses.
 849   */
 850  function get_page_statuses() {
 851      $status = array(
 852          'draft'            => __('Draft'),
 853          'private'        => __('Private'),
 854          'publish'        => __('Published')
 855      );
 856  
 857      return $status;
 858  }
 859  
 860  /**
 861   * Register a post status. Do not use before init.
 862   *
 863   * A simple function for creating or modifying a post status based on the
 864   * parameters given. The function will accept an array (second optional
 865   * parameter), along with a string for the post status name.
 866   *
 867   *
 868   * Optional $args contents:
 869   *
 870   * label - A descriptive name for the post status marked for translation. Defaults to $post_status.
 871   * public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
 872   * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false.
 873   * show_in_admin_all_list - Whether to include posts in the edit listing for their post type
 874   * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
 875   *                             listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
 876   *
 877   * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
 878   *
 879   * @package WordPress
 880   * @subpackage Post
 881   * @since 3.0.0
 882   * @uses $wp_post_statuses Inserts new post status object into the list
 883   *
 884   * @param string $post_status Name of the post status.
 885   * @param array|string $args See above description.
 886   */
 887  function register_post_status($post_status, $args = array()) {
 888      global $wp_post_statuses;
 889  
 890      if (!is_array($wp_post_statuses))
 891          $wp_post_statuses = array();
 892  
 893      // Args prefixed with an underscore are reserved for internal use.
 894      $defaults = array(
 895          'label' => false,
 896          'label_count' => false,
 897          'exclude_from_search' => null,
 898          '_builtin' => false,
 899          'public' => null,
 900          'internal' => null,
 901          'protected' => null,
 902          'private' => null,
 903          'publicly_queryable' => null,
 904          'show_in_admin_status_list' => null,
 905          'show_in_admin_all_list' => null,
 906      );
 907      $args = wp_parse_args($args, $defaults);
 908      $args = (object) $args;
 909  
 910      $post_status = sanitize_key($post_status);
 911      $args->name = $post_status;
 912  
 913      if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
 914          $args->internal = true;
 915  
 916      if ( null === $args->public  )
 917          $args->public = false;
 918  
 919      if ( null === $args->private  )
 920          $args->private = false;
 921  
 922      if ( null === $args->protected  )
 923          $args->protected = false;
 924  
 925      if ( null === $args->internal  )
 926          $args->internal = false;
 927  
 928      if ( null === $args->publicly_queryable )
 929          $args->publicly_queryable = $args->public;
 930  
 931      if ( null === $args->exclude_from_search )
 932          $args->exclude_from_search = $args->internal;
 933  
 934      if ( null === $args->show_in_admin_all_list )
 935          $args->show_in_admin_all_list = !$args->internal;
 936  
 937      if ( null === $args->show_in_admin_status_list )
 938          $args->show_in_admin_status_list = !$args->internal;
 939  
 940      if ( false === $args->label )
 941          $args->label = $post_status;
 942  
 943      if ( false === $args->label_count )
 944          $args->label_count = array( $args->label, $args->label );
 945  
 946      $wp_post_statuses[$post_status] = $args;
 947  
 948      return $args;
 949  }
 950  
 951  /**
 952   * Retrieve a post status object by name
 953   *
 954   * @package WordPress
 955   * @subpackage Post
 956   * @since 3.0.0
 957   * @uses $wp_post_statuses
 958   * @see register_post_status
 959   * @see get_post_statuses
 960   *
 961   * @param string $post_status The name of a registered post status
 962   * @return object A post status object
 963   */
 964  function get_post_status_object( $post_status ) {
 965      global $wp_post_statuses;
 966  
 967      if ( empty($wp_post_statuses[$post_status]) )
 968          return null;
 969  
 970      return $wp_post_statuses[$post_status];
 971  }
 972  
 973  /**
 974   * Get a list of all registered post status objects.
 975   *
 976   * @package WordPress
 977   * @subpackage Post
 978   * @since 3.0.0
 979   * @uses $wp_post_statuses
 980   * @see register_post_status
 981   * @see get_post_status_object
 982   *
 983   * @param array|string $args An array of key => value arguments to match against the post status objects.
 984   * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
 985   * @param string $operator The logical operation to perform. 'or' means only one element
 986   *  from the array needs to match; 'and' means all elements must match. The default is 'and'.
 987   * @return array A list of post status names or objects
 988   */
 989  function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
 990      global $wp_post_statuses;
 991  
 992      $field = ('names' == $output) ? 'name' : false;
 993  
 994      return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
 995  }
 996  
 997  /**
 998   * Whether the post type is hierarchical.
 999   *
1000   * A false return value might also mean that the post type does not exist.
1001   *
1002   * @since 3.0.0
1003   * @see get_post_type_object
1004   *
1005   * @param string $post_type Post type name
1006   * @return bool Whether post type is hierarchical.
1007   */
1008  function is_post_type_hierarchical( $post_type ) {
1009      if ( ! post_type_exists( $post_type ) )
1010          return false;
1011  
1012      $post_type = get_post_type_object( $post_type );
1013      return $post_type->hierarchical;
1014  }
1015  
1016  /**
1017   * Checks if a post type is registered.
1018   *
1019   * @since 3.0.0
1020   * @uses get_post_type_object()
1021   *
1022   * @param string $post_type Post type name
1023   * @return bool Whether post type is registered.
1024   */
1025  function post_type_exists( $post_type ) {
1026      return (bool) get_post_type_object( $post_type );
1027  }
1028  
1029  /**
1030   * Retrieve the post type of the current post or of a given post.
1031   *
1032   * @since 2.1.0
1033   *
1034   * @param int|object $post Optional. Post ID or post object. Default is the current post from the loop.
1035   * @return string|bool Post type on success, false on failure.
1036   */
1037  function get_post_type( $post = null ) {
1038      if ( $post = get_post( $post ) )
1039          return $post->post_type;
1040  
1041      return false;
1042  }
1043  
1044  /**
1045   * Retrieve a post type object by name
1046   *
1047   * @package WordPress
1048   * @subpackage Post
1049   * @since 3.0.0
1050   * @uses $wp_post_types
1051   * @see register_post_type
1052   * @see get_post_types
1053   *
1054   * @param string $post_type The name of a registered post type
1055   * @return object A post type object
1056   */
1057  function get_post_type_object( $post_type ) {
1058      global $wp_post_types;
1059  
1060      if ( empty($wp_post_types[$post_type]) )
1061          return null;
1062  
1063      return $wp_post_types[$post_type];
1064  }
1065  
1066  /**
1067   * Get a list of all registered post type objects.
1068   *
1069   * @package WordPress
1070   * @subpackage Post
1071   * @since 2.9.0
1072   * @uses $wp_post_types
1073   * @see register_post_type
1074   *
1075   * @param array|string $args An array of key => value arguments to match against the post type objects.
1076   * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
1077   * @param string $operator The logical operation to perform. 'or' means only one element
1078   *  from the array needs to match; 'and' means all elements must match. The default is 'and'.
1079   * @return array A list of post type names or objects
1080   */
1081  function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
1082      global $wp_post_types;
1083  
1084      $field = ('names' == $output) ? 'name' : false;
1085  
1086      return wp_filter_object_list($wp_post_types, $args, $operator, $field);
1087  }
1088  
1089  /**
1090   * Register a post type. Do not use before init.
1091   *
1092   * A function for creating or modifying a post type based on the
1093   * parameters given. The function will accept an array (second optional
1094   * parameter), along with a string for the post type name.
1095   *
1096   * Optional $args contents:
1097   *
1098   * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
1099   * - labels - An array of labels for this post type.
1100   *     * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones.
1101   *     * You can see accepted values in {@link get_post_type_labels()}.
1102   * - description - A short descriptive summary of what the post type is. Defaults to blank.
1103   * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users.
1104   *     * Defaults to false.
1105   *     * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are
1106   *       inherited from public, each does not rely on this relationship and controls a very specific intention.
1107   * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false.
1108   * - exclude_from_search - Whether to exclude posts with this post type from front end search results.
1109   *     * If not set, the opposite of public's current value is used.
1110   * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request().
1111   *     * ?post_type={post_type_key}
1112   *     * ?{post_type_key}={single_post_slug}
1113   *     * ?{post_type_query_var}={single_post_slug}
1114   *     * If not set, the default is inherited from public.
1115   * - show_ui - Whether to generate a default UI for managing this post type in the admin.
1116   *     * If not set, the default is inherited from public.
1117   * - show_in_menu - Where to show the post type in the admin menu.
1118   *     * If true, the post type is shown in its own top level menu.
1119   *     * If false, no menu is shown
1120   *     * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will
1121   *       be placed as a sub menu of that.
1122   *     * show_ui must be true.
1123   *     * If not set, the default is inherited from show_ui
1124   * - show_in_nav_menus - Makes this post type available for selection in navigation menus.
1125   *     * If not set, the default is inherited from public.
1126   * - show_in_admin_bar - Makes this post type available via the admin bar.
1127   *     * If not set, the default is inherited from show_in_menu
1128   * - menu_position - The position in the menu order the post type should appear.
1129   *     * show_in_menu must be true
1130   *     * Defaults to null, which places it at the bottom of its area.
1131   * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
1132   *     * Pass a base64-encoded SVG using a data URI, which will be colored to match the color scheme.
1133   *      This should begin with 'data:image/svg+xml;base64,'.
1134   *     * Pass the name of a Dashicons helper class to use a font icon, e.g. 'dashicons-piechart'.
1135   *     * Pass 'none' to leave div.wp-menu-image empty so an icon can be added via CSS.
1136   * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
1137   *     * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
1138   *       capabilities, e.g. array('story', 'stories').
1139   * - capabilities - Array of capabilities for this post type.
1140   *     * By default the capability_type is used as a base to construct capabilities.
1141   *     * You can see accepted values in {@link get_post_type_capabilities()}.
1142   * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
1143   * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
1144   *     * See {@link add_post_type_support()} for documentation.
1145   * - register_meta_box_cb - Provide a callback function that sets up the meta boxes
1146   *     for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
1147   * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
1148   *     * Default is no taxonomies.
1149   *     * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
1150   * - has_archive - True to enable post type archives. Default is false.
1151   *     * Will generate the proper rewrite rules if rewrite is enabled.
1152   * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
1153   *     * To prevent rewrite, set to false.
1154   *     * To specify rewrite rules, an array can be passed with any of these keys
1155   *         * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
1156   *         * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
1157   *         * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
1158   *         * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
1159   *         * 'ep_mask' => const Assign an endpoint mask.
1160   *             * If not specified and permalink_epmask is set, inherits from permalink_epmask.
1161   *             * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
1162   * - query_var - Sets the query_var key for this post type. Defaults to $post_type key
1163   *     * If false, a post type cannot be loaded at ?{query_var}={post_slug}
1164   *     * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
1165   * - can_export - Allows this post type to be exported. Defaults to true.
1166   * - delete_with_user - Whether to delete posts of this type when deleting a user.
1167   *     * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
1168   *     * If false, posts of this type belonging to the user will *not* be trashed or deleted.
1169   *     * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
1170   * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
1171   * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
1172   *
1173   * @since 2.9.0
1174   * @uses $wp_post_types Inserts new post type object into the list
1175   * @uses $wp_rewrite Gets default feeds
1176   * @uses $wp Adds query vars
1177   *
1178   * @param string $post_type Post type key, must not exceed 20 characters.
1179   * @param array|string $args See optional args description above.
1180   * @return object|WP_Error the registered post type object, or an error object.
1181   */
1182  function register_post_type( $post_type, $args = array() ) {
1183      global $wp_post_types, $wp_rewrite, $wp;
1184  
1185      if ( ! is_array( $wp_post_types ) )
1186          $wp_post_types = array();
1187  
1188      // Args prefixed with an underscore are reserved for internal use.
1189      $defaults = array(
1190          'labels'               => array(),
1191          'description'          => '',
1192          'public'               => false,
1193          'hierarchical'         => false,
1194          'exclude_from_search'  => null,
1195          'publicly_queryable'   => null,
1196          'show_ui'              => null,
1197          'show_in_menu'         => null,
1198          'show_in_nav_menus'    => null,
1199          'show_in_admin_bar'    => null,
1200          'menu_position'        => null,
1201          'menu_icon'            => null,
1202          'capability_type'      => 'post',
1203          'capabilities'         => array(),
1204          'map_meta_cap'         => null,
1205          'supports'             => array(),
1206          'register_meta_box_cb' => null,
1207          'taxonomies'           => array(),
1208          'has_archive'          => false,
1209          'rewrite'              => true,
1210          'query_var'            => true,
1211          'can_export'           => true,
1212          'delete_with_user'     => null,
1213          '_builtin'             => false,
1214          '_edit_link'           => 'post.php?post=%d',
1215      );
1216      $args = wp_parse_args( $args, $defaults );
1217      $args = (object) $args;
1218  
1219      $post_type = sanitize_key( $post_type );
1220      $args->name = $post_type;
1221  
1222      if ( strlen( $post_type ) > 20 )
1223          return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
1224  
1225      // If not set, default to the setting for public.
1226      if ( null === $args->publicly_queryable )
1227          $args->publicly_queryable = $args->public;
1228  
1229      // If not set, default to the setting for public.
1230      if ( null === $args->show_ui )
1231          $args->show_ui = $args->public;
1232  
1233      // If not set, default to the setting for show_ui.
1234      if ( null === $args->show_in_menu || ! $args->show_ui )
1235          $args->show_in_menu = $args->show_ui;
1236  
1237      // If not set, default to the whether the full UI is shown.
1238      if ( null === $args->show_in_admin_bar )
1239          $args->show_in_admin_bar = true === $args->show_in_menu;
1240  
1241      // If not set, default to the setting for public.
1242      if ( null === $args->show_in_nav_menus )
1243          $args->show_in_nav_menus = $args->public;
1244  
1245      // If not set, default to true if not public, false if public.
1246      if ( null === $args->exclude_from_search )
1247          $args->exclude_from_search = !$args->public;
1248  
1249      // Back compat with quirky handling in version 3.0. #14122
1250      if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1251          $args->map_meta_cap = true;
1252  
1253      // If not set, default to false.
1254      if ( null === $args->map_meta_cap )
1255          $args->map_meta_cap = false;
1256  
1257      $args->cap = get_post_type_capabilities( $args );
1258      unset( $args->capabilities );
1259  
1260      if ( is_array( $args->capability_type ) )
1261          $args->capability_type = $args->capability_type[0];
1262  
1263      if ( ! empty( $args->supports ) ) {
1264          add_post_type_support( $post_type, $args->supports );
1265          unset( $args->supports );
1266      } elseif ( false !== $args->supports ) {
1267          // Add default features
1268          add_post_type_support( $post_type, array( 'title', 'editor' ) );
1269      }
1270  
1271      if ( false !== $args->query_var && ! empty( $wp ) ) {
1272          if ( true === $args->query_var )
1273              $args->query_var = $post_type;
1274          else
1275              $args->query_var = sanitize_title_with_dashes( $args->query_var );
1276          $wp->add_query_var( $args->query_var );
1277      }
1278  
1279      if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
1280          if ( ! is_array( $args->rewrite ) )
1281              $args->rewrite = array();
1282          if ( empty( $args->rewrite['slug'] ) )
1283              $args->rewrite['slug'] = $post_type;
1284          if ( ! isset( $args->rewrite['with_front'] ) )
1285              $args->rewrite['with_front'] = true;
1286          if ( ! isset( $args->rewrite['pages'] ) )
1287              $args->rewrite['pages'] = true;
1288          if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1289              $args->rewrite['feeds'] = (bool) $args->has_archive;
1290          if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1291              if ( isset( $args->permalink_epmask ) )
1292                  $args->rewrite['ep_mask'] = $args->permalink_epmask;
1293              else
1294                  $args->rewrite['ep_mask'] = EP_PERMALINK;
1295          }
1296  
1297          if ( $args->hierarchical )
1298              add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
1299          else
1300              add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
1301  
1302          if ( $args->has_archive ) {
1303              $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1304              if ( $args->rewrite['with_front'] )
1305                  $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1306              else
1307                  $archive_slug = $wp_rewrite->root . $archive_slug;
1308  
1309              add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1310              if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1311                  $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1312                  add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1313                  add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1314              }
1315              if ( $args->rewrite['pages'] )
1316                  add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1317          }
1318  
1319          $permastruct_args = $args->rewrite;
1320          $permastruct_args['feed'] = $permastruct_args['feeds'];
1321          add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
1322      }
1323  
1324      if ( $args->register_meta_box_cb )
1325          add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
1326  
1327      $args->labels = get_post_type_labels( $args );
1328      $args->label = $args->labels->name;
1329  
1330      $wp_post_types[ $post_type ] = $args;
1331  
1332      add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1333  
1334      foreach ( $args->taxonomies as $taxonomy ) {
1335          register_taxonomy_for_object_type( $taxonomy, $post_type );
1336      }
1337  
1338      do_action( 'registered_post_type', $post_type, $args );
1339  
1340      return $args;
1341  }
1342  
1343  /**
1344   * Builds an object with all post type capabilities out of a post type object
1345   *
1346   * Post type capabilities use the 'capability_type' argument as a base, if the
1347   * capability is not set in the 'capabilities' argument array or if the
1348   * 'capabilities' argument is not supplied.
1349   *
1350   * The capability_type argument can optionally be registered as an array, with
1351   * the first value being singular and the second plural, e.g. array('story, 'stories')
1352   * Otherwise, an 's' will be added to the value for the plural form. After
1353   * registration, capability_type will always be a string of the singular value.
1354   *
1355   * By default, seven keys are accepted as part of the capabilities array:
1356   *
1357   * - edit_post, read_post, and delete_post are meta capabilities, which are then
1358   *   generally mapped to corresponding primitive capabilities depending on the
1359   *   context, which would be the post being edited/read/deleted and the user or
1360   *   role being checked. Thus these capabilities would generally not be granted
1361   *   directly to users or roles.
1362   *
1363   * - edit_posts - Controls whether objects of this post type can be edited.
1364   * - edit_others_posts - Controls whether objects of this type owned by other users
1365   *   can be edited. If the post type does not support an author, then this will
1366   *   behave like edit_posts.
1367   * - publish_posts - Controls publishing objects of this post type.
1368   * - read_private_posts - Controls whether private objects can be read.
1369   *
1370   * These four primitive capabilities are checked in core in various locations.
1371   * There are also seven other primitive capabilities which are not referenced
1372   * directly in core, except in map_meta_cap(), which takes the three aforementioned
1373   * meta capabilities and translates them into one or more primitive capabilities
1374   * that must then be checked against the user or role, depending on the context.
1375   *
1376   * - read - Controls whether objects of this post type can be read.
1377   * - delete_posts - Controls whether objects of this post type can be deleted.
1378   * - delete_private_posts - Controls whether private objects can be deleted.
1379   * - delete_published_posts - Controls whether published objects can be deleted.
1380   * - delete_others_posts - Controls whether objects owned by other users can be
1381   *   can be deleted. If the post type does not support an author, then this will
1382   *   behave like delete_posts.
1383   * - edit_private_posts - Controls whether private objects can be edited.
1384   * - edit_published_posts - Controls whether published objects can be edited.
1385   *
1386   * These additional capabilities are only used in map_meta_cap(). Thus, they are
1387   * only assigned by default if the post type is registered with the 'map_meta_cap'
1388   * argument set to true (default is false).
1389   *
1390   * @see map_meta_cap()
1391   * @since 3.0.0
1392   *
1393   * @param object $args Post type registration arguments
1394   * @return object object with all the capabilities as member variables
1395   */
1396  function get_post_type_capabilities( $args ) {
1397      if ( ! is_array( $args->capability_type ) )
1398          $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1399  
1400      // Singular base for meta capabilities, plural base for primitive capabilities.
1401      list( $singular_base, $plural_base ) = $args->capability_type;
1402  
1403      $default_capabilities = array(
1404          // Meta capabilities
1405          'edit_post'          => 'edit_'         . $singular_base,
1406          'read_post'          => 'read_'         . $singular_base,
1407          'delete_post'        => 'delete_'       . $singular_base,
1408          // Primitive capabilities used outside of map_meta_cap():
1409          'edit_posts'         => 'edit_'         . $plural_base,
1410          'edit_others_posts'  => 'edit_others_'  . $plural_base,
1411          'publish_posts'      => 'publish_'      . $plural_base,
1412          'read_private_posts' => 'read_private_' . $plural_base,
1413      );
1414  
1415      // Primitive capabilities used within map_meta_cap():
1416      if ( $args->map_meta_cap ) {
1417          $default_capabilities_for_mapping = array(
1418              'read'                   => 'read',
1419              'delete_posts'           => 'delete_'           . $plural_base,
1420              'delete_private_posts'   => 'delete_private_'   . $plural_base,
1421              'delete_published_posts' => 'delete_published_' . $plural_base,
1422              'delete_others_posts'    => 'delete_others_'    . $plural_base,
1423              'edit_private_posts'     => 'edit_private_'     . $plural_base,
1424              'edit_published_posts'   => 'edit_published_'   . $plural_base,
1425          );
1426          $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1427      }
1428  
1429      $capabilities = array_merge( $default_capabilities, $args->capabilities );
1430  
1431      // Post creation capability simply maps to edit_posts by default:
1432      if ( ! isset( $capabilities['create_posts'] ) )
1433          $capabilities['create_posts'] = $capabilities['edit_posts'];
1434  
1435      // Remember meta capabilities for future reference.
1436      if ( $args->map_meta_cap )
1437          _post_type_meta_capabilities( $capabilities );
1438  
1439      return (object) $capabilities;
1440  }
1441  
1442  /**
1443   * Stores or returns a list of post type meta caps for map_meta_cap().
1444   *
1445   * @since 3.1.0
1446   * @access private
1447   */
1448  function _post_type_meta_capabilities( $capabilities = null ) {
1449      static $meta_caps = array();
1450      if ( null === $capabilities )
1451          return $meta_caps;
1452      foreach ( $capabilities as $core => $custom ) {
1453          if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1454              $meta_caps[ $custom ] = $core;
1455      }
1456  }
1457  
1458  /**
1459   * Builds an object with all post type labels out of a post type object
1460   *
1461   * Accepted keys of the label array in the post type object:
1462   * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
1463   * - singular_name - name for one object of this post type. Default is Post/Page
1464   * - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code>
1465   * - add_new_item - Default is Add New Post/Add New Page
1466   * - edit_item - Default is Edit Post/Edit Page
1467   * - new_item - Default is New Post/New Page
1468   * - view_item - Default is View Post/View Page
1469   * - search_items - Default is Search Posts/Search Pages
1470   * - not_found - Default is No posts found/No pages found
1471   * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
1472   * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
1473   * - all_items - String for the submenu. Default is All Posts/All Pages
1474   * - menu_name - Default is the same as <code>name</code>
1475   *
1476   * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
1477   *
1478   * @since 3.0.0
1479   * @access private
1480   *
1481   * @param object $post_type_object
1482   * @return object object with all the labels as member variables
1483   */
1484  function get_post_type_labels( $post_type_object ) {
1485      $nohier_vs_hier_defaults = array(
1486          'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1487          'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1488          'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1489          'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1490          'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1491          'new_item' => array( __('New Post'), __('New Page') ),
1492          'view_item' => array( __('View Post'), __('View Page') ),
1493          'search_items' => array( __('Search Posts'), __('Search Pages') ),
1494          'not_found' => array( __('No posts found.'), __('No pages found.') ),
1495          'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1496          'parent_item_colon' => array( null, __('Parent Page:') ),
1497          'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
1498      );
1499      $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1500  
1501      $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1502  
1503      $post_type = $post_type_object->name;
1504      return apply_filters( "post_type_labels_{$post_type}", $labels );
1505  }
1506  
1507  /**
1508   * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
1509   *
1510   * @access private
1511   * @since 3.0.0
1512   */
1513  function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1514      $object->labels = (array) $object->labels;
1515  
1516      if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1517          $object->labels['name'] = $object->label;
1518  
1519      if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1520          $object->labels['singular_name'] = $object->labels['name'];
1521  
1522      if ( ! isset( $object->labels['name_admin_bar'] ) )
1523          $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1524  
1525      if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1526          $object->labels['menu_name'] = $object->labels['name'];
1527  
1528      if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1529          $object->labels['all_items'] = $object->labels['menu_name'];
1530  
1531      foreach ( $nohier_vs_hier_defaults as $key => $value )
1532              $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1533  
1534      $labels = array_merge( $defaults, $object->labels );
1535      return (object)$labels;
1536  }
1537  
1538  /**
1539   * Adds submenus for post types.
1540   *
1541   * @access private
1542   * @since 3.1.0
1543   */
1544  function _add_post_type_submenus() {
1545      foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1546          $ptype_obj = get_post_type_object( $ptype );
1547          // Submenus only.
1548          if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1549              continue;
1550          add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
1551      }
1552  }
1553  add_action( 'admin_menu', '_add_post_type_submenus' );
1554  
1555  /**
1556   * Register support of certain features for a post type.
1557   *
1558   * All features are directly associated with a functional area of the edit screen, such as the
1559   * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
1560   * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
1561   *
1562   * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
1563   * and the 'comments' feature dictates whether the comments count will show on the edit screen.
1564   *
1565   * @since 3.0.0
1566   * @param string $post_type The post type for which to add the feature
1567   * @param string|array $feature the feature being added, can be an array of feature strings or a single string
1568   */
1569  function add_post_type_support( $post_type, $feature ) {
1570      global $_wp_post_type_features;
1571  
1572      $features = (array) $feature;
1573      foreach ($features as $feature) {
1574          if ( func_num_args() == 2 )
1575              $_wp_post_type_features[$post_type][$feature] = true;
1576          else
1577              $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1578      }
1579  }
1580  
1581  /**
1582   * Remove support for a feature from a post type.
1583   *
1584   * @since 3.0.0
1585   * @param string $post_type The post type for which to remove the feature
1586   * @param string $feature The feature being removed
1587   */
1588  function remove_post_type_support( $post_type, $feature ) {
1589      global $_wp_post_type_features;
1590  
1591      if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
1592          unset( $_wp_post_type_features[$post_type][$feature] );
1593  }
1594  
1595  /**
1596   * Get all the post type features
1597   *
1598   * @since 3.4.0
1599   * @param string $post_type The post type
1600   * @return array
1601   */
1602  
1603  function get_all_post_type_supports( $post_type ) {
1604      global $_wp_post_type_features;
1605  
1606      if ( isset( $_wp_post_type_features[$post_type] ) )
1607          return $_wp_post_type_features[$post_type];
1608  
1609      return array();
1610  }
1611  
1612  /**
1613   * Checks a post type's support for a given feature
1614   *
1615   * @since 3.0.0
1616   * @param string $post_type The post type being checked
1617   * @param string $feature the feature being checked
1618   * @return boolean
1619   */
1620  
1621  function post_type_supports( $post_type, $feature ) {
1622      global $_wp_post_type_features;
1623  
1624      return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1625  }
1626  
1627  /**
1628   * Updates the post type for the post ID.
1629   *
1630   * The page or post cache will be cleaned for the post ID.
1631   *
1632   * @since 2.5.0
1633   *
1634   * @uses $wpdb
1635   *
1636   * @param int $post_id Post ID to change post type. Not actually optional.
1637   * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
1638   *  name a few.
1639   * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
1640   */
1641  function set_post_type( $post_id = 0, $post_type = 'post' ) {
1642      global $wpdb;
1643  
1644      $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1645      $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1646  
1647      clean_post_cache( $post_id );
1648  
1649      return $return;
1650  }
1651  
1652  /**
1653   * Retrieve list of latest posts or posts matching criteria.
1654   *
1655   * The defaults are as follows:
1656   *     'numberposts' - Default is 5. Total number of posts to retrieve.
1657   *     'offset' - Default is 0. See {@link WP_Query::query()} for more.
1658   *     'category' - What category to pull the posts from.
1659   *     'orderby' - Default is 'date', which orders based on post_date. How to order the posts.
1660   *     'order' - Default is 'DESC'. The order to retrieve the posts.
1661   *     'include' - See {@link WP_Query::query()} for more.
1662   *     'exclude' - See {@link WP_Query::query()} for more.
1663   *     'meta_key' - See {@link WP_Query::query()} for more.
1664   *     'meta_value' - See {@link WP_Query::query()} for more.
1665   *     'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
1666   *     'post_parent' - The parent of the post or post type.
1667   *     'post_status' - Default is 'publish'. Post status to retrieve.
1668   *
1669   * @since 1.2.0
1670   * @uses WP_Query::query() See for more default arguments and information.
1671   * @link http://codex.wordpress.org/Template_Tags/get_posts
1672   *
1673   * @param array $args Optional. Overrides defaults.
1674   * @return array List of posts.
1675   */
1676  function get_posts($args = null) {
1677      $defaults = array(
1678          'numberposts' => 5, 'offset' => 0,
1679          'category' => 0, 'orderby' => 'date',
1680          'order' => 'DESC', 'include' => array(),
1681          'exclude' => array(), 'meta_key' => '',
1682          'meta_value' =>'', 'post_type' => 'post',
1683          'suppress_filters' => true
1684      );
1685  
1686      $r = wp_parse_args( $args, $defaults );
1687      if ( empty( $r['post_status'] ) )
1688          $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1689      if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1690          $r['posts_per_page'] = $r['numberposts'];
1691      if ( ! empty($r['category']) )
1692          $r['cat'] = $r['category'];
1693      if ( ! empty($r['include']) ) {
1694          $incposts = wp_parse_id_list( $r['include'] );
1695          $r['posts_per_page'] = count($incposts);  // only the number of posts included
1696          $r['post__in'] = $incposts;
1697      } elseif ( ! empty($r['exclude']) )
1698          $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1699  
1700      $r['ignore_sticky_posts'] = true;
1701      $r['no_found_rows'] = true;
1702  
1703      $get_posts = new WP_Query;
1704      return $get_posts->query($r);
1705  
1706  }
1707  
1708  //
1709  // Post meta functions
1710  //
1711  
1712  /**
1713   * Add meta data field to a post.
1714   *
1715   * Post meta data is called "Custom Fields" on the Administration Screen.
1716   *
1717   * @since 1.5.0
1718   * @link http://codex.wordpress.org/Function_Reference/add_post_meta
1719   *
1720   * @param int $post_id Post ID.
1721   * @param string $meta_key Metadata name.
1722   * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1723   * @param bool $unique Optional, default is false. Whether the same key should not be added.
1724   * @return int|bool Meta ID on success, false on failure.
1725   */
1726  function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
1727      // make sure meta is added to the post, not a revision
1728      if ( $the_post = wp_is_post_revision($post_id) )
1729          $post_id = $the_post;
1730  
1731      return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1732  }
1733  
1734  /**
1735   * Remove metadata matching criteria from a post.
1736   *
1737   * You can match based on the key, or key and value. Removing based on key and
1738   * value, will keep from removing duplicate metadata with the same key. It also
1739   * allows removing all metadata matching key, if needed.
1740   *
1741   * @since 1.5.0
1742   * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
1743   *
1744   * @param int $post_id post ID
1745   * @param string $meta_key Metadata name.
1746   * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar.
1747   * @return bool True on success, false on failure.
1748   */
1749  function delete_post_meta($post_id, $meta_key, $meta_value = '') {
1750      // make sure meta is added to the post, not a revision
1751      if ( $the_post = wp_is_post_revision($post_id) )
1752          $post_id = $the_post;
1753  
1754      return delete_metadata('post', $post_id, $meta_key, $meta_value);
1755  }
1756  
1757  /**
1758   * Retrieve post meta field for a post.
1759   *
1760   * @since 1.5.0
1761   * @link http://codex.wordpress.org/Function_Reference/get_post_meta
1762   *
1763   * @param int $post_id Post ID.
1764   * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1765   * @param bool $single Whether to return a single value.
1766   * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1767   *  is true.
1768   */
1769  function get_post_meta($post_id, $key = '', $single = false) {
1770      return get_metadata('post', $post_id, $key, $single);
1771  }
1772  
1773  /**
1774   * Update post meta field based on post ID.
1775   *
1776   * Use the $prev_value parameter to differentiate between meta fields with the
1777   * same key and post ID.
1778   *
1779   * If the meta field for the post does not exist, it will be added.
1780   *
1781   * @since 1.5.0
1782   * @link http://codex.wordpress.org/Function_Reference/update_post_meta
1783   *
1784   * @param int $post_id Post ID.
1785   * @param string $meta_key Metadata key.
1786   * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
1787   * @param mixed $prev_value Optional. Previous value to check before removing.
1788   * @return bool True on success, false on failure.
1789   */
1790  function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
1791      // make sure meta is added to the post, not a revision
1792      if ( $the_post = wp_is_post_revision($post_id) )
1793          $post_id = $the_post;
1794  
1795      return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1796  }
1797  
1798  /**
1799   * Delete everything from post meta matching meta key.
1800   *
1801   * @since 2.3.0
1802   *
1803   * @param string $post_meta_key Key to search for when deleting.
1804   * @return bool Whether the post meta key was deleted from the database
1805   */
1806  function delete_post_meta_by_key($post_meta_key) {
1807      return delete_metadata( 'post', null, $post_meta_key, '', true );
1808  }
1809  
1810  /**
1811   * Retrieve post meta fields, based on post ID.
1812   *
1813   * The post meta fields are retrieved from the cache where possible,
1814   * so the function is optimized to be called more than once.
1815   *
1816   * @since 1.2.0
1817   * @link http://codex.wordpress.org/Function_Reference/get_post_custom
1818   *
1819   * @param int $post_id Post ID.
1820   * @return array
1821   */
1822  function get_post_custom( $post_id = 0 ) {
1823      $post_id = absint( $post_id );
1824      if ( ! $post_id )
1825          $post_id = get_the_ID();
1826  
1827      return get_post_meta( $post_id );
1828  }
1829  
1830  /**
1831   * Retrieve meta field names for a post.
1832   *
1833   * If there are no meta fields, then nothing (null) will be returned.
1834   *
1835   * @since 1.2.0
1836   * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
1837   *
1838   * @param int $post_id post ID
1839   * @return array|null Either array of the keys, or null if keys could not be retrieved.
1840   */
1841  function get_post_custom_keys( $post_id = 0 ) {
1842      $custom = get_post_custom( $post_id );
1843  
1844      if ( !is_array($custom) )
1845          return;
1846  
1847      if ( $keys = array_keys($custom) )
1848          return $keys;
1849  }
1850  
1851  /**
1852   * Retrieve values for a custom post field.
1853   *
1854   * The parameters must not be considered optional. All of the post meta fields
1855   * will be retrieved and only the meta field key values returned.
1856   *
1857   * @since 1.2.0
1858   * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
1859   *
1860   * @param string $key Meta field key.
1861   * @param int $post_id Post ID
1862   * @return array Meta field values.
1863   */
1864  function get_post_custom_values( $key = '', $post_id = 0 ) {
1865      if ( !$key )
1866          return null;
1867  
1868      $custom = get_post_custom($post_id);
1869  
1870      return isset($custom[$key]) ? $custom[$key] : null;
1871  }
1872  
1873  /**
1874   * Check if post is sticky.
1875   *
1876   * Sticky posts should remain at the top of The Loop. If the post ID is not
1877   * given, then The Loop ID for the current post will be used.
1878   *
1879   * @since 2.7.0
1880   *
1881   * @param int $post_id Optional. Post ID.
1882   * @return bool Whether post is sticky.
1883   */
1884  function is_sticky( $post_id = 0 ) {
1885      $post_id = absint( $post_id );
1886  
1887      if ( ! $post_id )
1888          $post_id = get_the_ID();
1889  
1890      $stickies = get_option( 'sticky_posts' );
1891  
1892      if ( ! is_array( $stickies ) )
1893          return false;
1894  
1895      if ( in_array( $post_id, $stickies ) )
1896          return true;
1897  
1898      return false;
1899  }
1900  
1901  /**
1902   * Sanitize every post field.
1903   *
1904   * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
1905   *
1906   * @since 2.3.0
1907   * @uses sanitize_post_field() Used to sanitize the fields.
1908   *
1909   * @param object|WP_Post|array $post The Post Object or Array
1910   * @param string $context Optional, default is 'display'. How to sanitize post fields.
1911   * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post)
1912   */
1913  function sanitize_post($post, $context = 'display') {
1914      if ( is_object($post) ) {
1915          // Check if post already filtered for this context
1916          if ( isset($post->filter) && $context == $post->filter )
1917              return $post;
1918          if ( !isset($post->ID) )
1919              $post->ID = 0;
1920          foreach ( array_keys(get_object_vars($post)) as $field )
1921              $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1922          $post->filter = $context;
1923      } else {
1924          // Check if post already filtered for this context
1925          if ( isset($post['filter']) && $context == $post['filter'] )
1926              return $post;
1927          if ( !isset($post['ID']) )
1928              $post['ID'] = 0;
1929          foreach ( array_keys($post) as $field )
1930              $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1931          $post['filter'] = $context;
1932      }
1933      return $post;
1934  }
1935  
1936  /**
1937   * Sanitize post field based on context.
1938   *
1939   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1940   * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1941   * when calling filters.
1942   *
1943   * @since 2.3.0
1944   * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
1945   *  $post_id if $context == 'edit' and field name prefix == 'post_'.
1946   *
1947   * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
1948   * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
1949   * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
1950   *
1951   * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
1952   *  other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
1953   * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
1954   *  'edit' and 'db' and field name prefix != 'post_'.
1955   *
1956   * @param string $field The Post Object field name.
1957   * @param mixed $value The Post Object value.
1958   * @param int $post_id Post ID.
1959   * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
1960   *               'attribute' and 'js'.
1961   * @return mixed Sanitized value.
1962   */
1963  function sanitize_post_field($field, $value, $post_id, $context) {
1964      $int_fields = array('ID', 'post_parent', 'menu_order');
1965      if ( in_array($field, $int_fields) )
1966          $value = (int) $value;
1967  
1968      // Fields which contain arrays of ints.
1969      $array_int_fields = array( 'ancestors' );
1970      if ( in_array($field, $array_int_fields) ) {
1971          $value = array_map( 'absint', $value);
1972          return $value;
1973      }
1974  
1975      if ( 'raw' == $context )
1976          return $value;
1977  
1978      $prefixed = false;
1979      if ( false !== strpos($field, 'post_') ) {
1980          $prefixed = true;
1981          $field_no_prefix = str_replace('post_', '', $field);
1982      }
1983  
1984      if ( 'edit' == $context ) {
1985          $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1986  
1987          if ( $prefixed ) {
1988              $value = apply_filters("edit_{$field}", $value, $post_id);
1989              // Old school
1990              $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
1991          } else {
1992              $value = apply_filters("edit_post_{$field}", $value, $post_id);
1993          }
1994  
1995          if ( in_array($field, $format_to_edit) ) {
1996              if ( 'post_content' == $field )
1997                  $value = format_to_edit($value, user_can_richedit());
1998              else
1999                  $value = format_to_edit($value);
2000          } else {
2001              $value = esc_attr($value);
2002          }
2003      } else if ( 'db' == $context ) {
2004          if ( $prefixed ) {
2005              $value = apply_filters("pre_{$field}", $value);
2006              $value = apply_filters("{$field_no_prefix}_save_pre", $value);
2007          } else {
2008              $value = apply_filters("pre_post_{$field}", $value);
2009              $value = apply_filters("{$field}_pre", $value);
2010          }
2011      } else {
2012          // Use display filters by default.
2013          if ( $prefixed )
2014              $value = apply_filters($field, $value, $post_id, $context);
2015          else
2016              $value = apply_filters("post_{$field}", $value, $post_id, $context);
2017      }
2018  
2019      if ( 'attribute' == $context )
2020          $value = esc_attr($value);
2021      else if ( 'js' == $context )
2022          $value = esc_js($value);
2023  
2024      return $value;
2025  }
2026  
2027  /**
2028   * Make a post sticky.
2029   *
2030   * Sticky posts should be displayed at the top of the front page.
2031   *
2032   * @since 2.7.0
2033   *
2034   * @param int $post_id Post ID.
2035   */
2036  function stick_post($post_id) {
2037      $stickies = get_option('sticky_posts');
2038  
2039      if ( !is_array($stickies) )
2040          $stickies = array($post_id);
2041  
2042      if ( ! in_array($post_id, $stickies) )
2043          $stickies[] = $post_id;
2044  
2045      update_option('sticky_posts', $stickies);
2046  }
2047  
2048  /**
2049   * Unstick a post.
2050   *
2051   * Sticky posts should be displayed at the top of the front page.
2052   *
2053   * @since 2.7.0
2054   *
2055   * @param int $post_id Post ID.
2056   */
2057  function unstick_post($post_id) {
2058      $stickies = get_option('sticky_posts');
2059  
2060      if ( !is_array($stickies) )
2061          return;
2062  
2063      if ( ! in_array($post_id, $stickies) )
2064          return;
2065  
2066      $offset = array_search($post_id, $stickies);
2067      if ( false === $offset )
2068          return;
2069  
2070      array_splice($stickies, $offset, 1);
2071  
2072      update_option('sticky_posts', $stickies);
2073  }
2074  
2075  /**
2076   * Count number of posts of a post type and if user has permissions to view.
2077   *
2078   * This function provides an efficient method of finding the amount of post's
2079   * type a blog has. Another method is to count the amount of items in
2080   * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2081   * when developing for 2.5+, use this function instead.
2082   *
2083   * The $perm parameter checks for 'readable' value and if the user can read
2084   * private posts, it will display that for the user that is signed in.
2085   *
2086   * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
2087   *
2088   * @since 2.5.0
2089   *
2090   * @param string $type Optional. Post type to retrieve count
2091   * @param string $perm Optional. 'readable' or empty.
2092   * @return object Number of posts for each status
2093   */
2094  function wp_count_posts( $type = 'post', $perm = '' ) {
2095      global $wpdb;
2096  
2097      if ( ! post_type_exists( $type ) )
2098          return new stdClass;
2099  
2100      $user = wp_get_current_user();
2101  
2102      $cache_key = 'posts-' . $type;
2103  
2104      $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2105      if ( 'readable' == $perm && is_user_logged_in() ) {
2106          $post_type_object = get_post_type_object($type);
2107          if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
2108              $cache_key .= '_' . $perm . '_' . $user->ID;
2109              $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
2110          }
2111      }
2112      $query .= ' GROUP BY post_status';
2113  
2114      $counts = wp_cache_get( $cache_key, 'counts' );
2115      if ( false === $counts ) {
2116          $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2117          $counts = array_fill_keys( get_post_stati(), 0 );
2118  
2119          foreach ( $results as $row )
2120              $counts[ $row['post_status'] ] = $row['num_posts'];
2121  
2122          $counts = (object) $counts;
2123          wp_cache_set( $cache_key, $counts, 'counts' );
2124      }
2125  
2126      /**
2127       * Modify returned post counts by status for the current post type.
2128       *
2129       * @since 3.7.0
2130       *
2131       * @param object $counts An object containing the current post_type's post counts by status.
2132       * @param string $type   The post type.
2133       * @param string $perm   The permission to determine if the posts are 'readable' by the current user.
2134       */
2135      return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2136  }
2137  
2138  /**
2139   * Count number of attachments for the mime type(s).
2140   *
2141   * If you set the optional mime_type parameter, then an array will still be
2142   * returned, but will only have the item you are looking for. It does not give
2143   * you the number of attachments that are children of a post. You can get that
2144   * by counting the number of children that post has.
2145   *
2146   * @since 2.5.0
2147   *
2148   * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
2149   * @return array Number of posts for each mime type.
2150   */
2151  function wp_count_attachments( $mime_type = '' ) {
2152      global $wpdb;
2153  
2154      $and = wp_post_mime_type_where( $mime_type );
2155      $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
2156  
2157      $counts = array();
2158      foreach( (array) $count as $row ) {
2159          $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2160      }
2161      $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2162  
2163      /**
2164       * Modify returned attachment counts by mime type.
2165       *
2166       * @since 3.7.0
2167       *
2168       * @param object $counts    An object containing the attachment counts by mime type.
2169       * @param string $mime_type The mime type pattern used to filter the attachments counted.
2170       */
2171      return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2172  }
2173  
2174  /**
2175   * Get default post mime types
2176   *
2177   * @since 2.9.0
2178   *
2179   * @return array
2180   */
2181  function get_post_mime_types() {
2182      $post_mime_types = array(    //    array( adj, noun )
2183          'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2184          'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2185          'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2186      );
2187  
2188      return apply_filters('post_mime_types', $post_mime_types);
2189  }
2190  
2191  /**
2192   * Check a MIME-Type against a list.
2193   *
2194   * If the wildcard_mime_types parameter is a string, it must be comma separated
2195   * list. If the real_mime_types is a string, it is also comma separated to
2196   * create the list.
2197   *
2198   * @since 2.5.0
2199   *
2200   * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
2201   *  flash (same as *flash*).
2202   * @param string|array $real_mime_types post_mime_type values
2203   * @return array array(wildcard=>array(real types))
2204   */
2205  function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
2206      $matches = array();
2207      if ( is_string($wildcard_mime_types) )
2208          $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
2209      if ( is_string($real_mime_types) )
2210          $real_mime_types = array_map('trim', explode(',', $real_mime_types));
2211      $wild = '[-._a-z0-9]*';
2212      foreach ( (array) $wildcard_mime_types as $type ) {
2213          $type = str_replace('*', $wild, $type);
2214          $patternses[1][$type] = "^$type$";
2215          if ( false === strpos($type, '/') ) {
2216              $patternses[2][$type] = "^$type/";
2217              $patternses[3][$type] = $type;
2218          }
2219      }
2220      asort($patternses);
2221      foreach ( $patternses as $patterns )
2222          foreach ( $patterns as $type => $pattern )
2223              foreach ( (array) $real_mime_types as $real )
2224                  if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
2225                      $matches[$type][] = $real;
2226      return $matches;
2227  }
2228  
2229  /**
2230   * Convert MIME types into SQL.
2231   *
2232   * @since 2.5.0
2233   *
2234   * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
2235   * @param string $table_alias Optional. Specify a table alias, if needed.
2236   * @return string The SQL AND clause for mime searching.
2237   */
2238  function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
2239      $where = '';
2240      $wildcards = array('', '%', '%/%');
2241      if ( is_string($post_mime_types) )
2242          $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2243      foreach ( (array) $post_mime_types as $mime_type ) {
2244          $mime_type = preg_replace('/\s/', '', $mime_type);
2245          $slashpos = strpos($mime_type, '/');
2246          if ( false !== $slashpos ) {
2247              $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2248              $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2249              if ( empty($mime_subgroup) )
2250                  $mime_subgroup = '*';
2251              else
2252                  $mime_subgroup = str_replace('/', '', $mime_subgroup);
2253              $mime_pattern = "$mime_group/$mime_subgroup";
2254          } else {
2255              $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2256              if ( false === strpos($mime_pattern, '*') )
2257                  $mime_pattern .= '/*';
2258          }
2259  
2260          $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2261  
2262          if ( in_array( $mime_type, $wildcards ) )
2263              return '';
2264  
2265          if ( false !== strpos($mime_pattern, '%') )
2266              $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2267          else
2268              $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2269      }
2270      if ( !empty($wheres) )
2271          $where = ' AND (' . join(' OR ', $wheres) . ') ';
2272      return $where;
2273  }
2274  
2275  /**
2276   * Trashes or deletes a post or page.
2277   *
2278   * When the post and page is permanently deleted, everything that is tied to it is deleted also.
2279   * This includes comments, post meta fields, and terms associated with the post.
2280   *
2281   * The post or page is moved to trash instead of permanently deleted unless trash is
2282   * disabled, item is already in the trash, or $force_delete is true.
2283   *
2284   * @since 1.0.0
2285   * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
2286   * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
2287   * @uses wp_delete_attachment() if post type is 'attachment'.
2288   * @uses wp_trash_post() if item should be trashed.
2289   *
2290   * @param int $postid Post ID.
2291   * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
2292   * @return mixed False on failure
2293   */
2294  function wp_delete_post( $postid = 0, $force_delete = false ) {
2295      global $wpdb;
2296  
2297      if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2298          return $post;
2299  
2300      if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2301              return wp_trash_post($postid);
2302  
2303      if ( $post->post_type == 'attachment' )
2304          return wp_delete_attachment( $postid, $force_delete );
2305  
2306      do_action('before_delete_post', $postid);
2307  
2308      delete_post_meta($postid,'_wp_trash_meta_status');
2309      delete_post_meta($postid,'_wp_trash_meta_time');
2310  
2311      wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2312  
2313      $parent_data = array( 'post_parent' => $post->post_parent );
2314      $parent_where = array( 'post_parent' => $postid );
2315  
2316      if ( is_post_type_hierarchical( $post->post_type ) ) {
2317          // Point children of this page to its parent, also clean the cache of affected children
2318          $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2319          $children = $wpdb->get_results( $children_query );
2320  
2321          $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2322      }
2323  
2324      // Do raw query. wp_get_post_revisions() is filtered
2325      $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2326      // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2327      foreach ( $revision_ids as $revision_id )
2328          wp_delete_post_revision( $revision_id );
2329  
2330      // Point all attachments to this post up one level
2331      $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2332  
2333      $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2334      foreach ( $comment_ids as $comment_id )
2335          wp_delete_comment( $comment_id, true );
2336  
2337      $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2338      foreach ( $post_meta_ids as $mid )
2339          delete_metadata_by_mid( 'post', $mid );
2340  
2341      do_action( 'delete_post', $postid );
2342      $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2343      if ( ! $result ) {
2344          return false;
2345      }
2346      do_action( 'deleted_post', $postid );
2347  
2348      clean_post_cache( $post );
2349  
2350      if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2351          foreach ( $children as $child )
2352              clean_post_cache( $child );
2353      }
2354  
2355      wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2356  
2357      do_action('after_delete_post', $postid);
2358  
2359      return $post;
2360  }
2361  
2362  /**
2363   * Resets the page_on_front, show_on_front, and page_for_post settings when a
2364   * linked page is deleted or trashed.
2365   *
2366   * Also ensures the post is no longer sticky.
2367   *
2368   * @access private
2369   * @since 3.7.0
2370   * @param $post_id
2371   */
2372  function _reset_front_page_settings_for_post( $post_id ) {
2373      $post = get_post( $post_id );
2374      if ( 'page' == $post->post_type ) {
2375           // If the page is defined in option page_on_front or post_for_posts,
2376          // adjust the corresponding options
2377          if ( get_option( 'page_on_front' ) == $post->ID ) {
2378              update_option( 'show_on_front', 'posts' );
2379              update_option( 'page_on_front', 0 );
2380          }
2381          if ( get_option( 'page_for_posts' ) == $post->ID ) {
2382              delete_option( 'page_for_posts', 0 );
2383          }
2384      }
2385      unstick_post( $post->ID );
2386  }
2387  add_action( 'before_delete_post', '_reset_front_page_settings_for_post' );
2388  add_action( 'wp_trash_post',      '_reset_front_page_settings_for_post' );
2389  
2390  /**
2391   * Moves a post or page to the Trash
2392   *
2393   * If trash is disabled, the post or page is permanently deleted.
2394   *
2395   * @since 2.9.0
2396   * @uses do_action() on 'trash_post' before trashing
2397   * @uses do_action() on 'trashed_post' after trashing
2398   * @uses wp_delete_post() if trash is disabled
2399   *
2400   * @param int $post_id Post ID.
2401   * @return mixed False on failure
2402   */
2403  function wp_trash_post($post_id = 0) {
2404      if ( !EMPTY_TRASH_DAYS )
2405          return wp_delete_post($post_id, true);
2406  
2407      if ( !$post = get_post($post_id, ARRAY_A) )
2408          return $post;
2409  
2410      if ( $post['post_status'] == 'trash' )
2411          return false;
2412  
2413      do_action('wp_trash_post', $post_id);
2414  
2415      add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2416      add_post_meta($post_id,'_wp_trash_meta_time', time());
2417  
2418      $post['post_status'] = 'trash';
2419      wp_insert_post($post);
2420  
2421      wp_trash_post_comments($post_id);
2422  
2423      do_action('trashed_post', $post_id);
2424  
2425      return $post;
2426  }
2427  
2428  /**
2429   * Restores a post or page from the Trash
2430   *
2431   * @since 2.9.0
2432   * @uses do_action() on 'untrash_post' before undeletion
2433   * @uses do_action() on 'untrashed_post' after undeletion
2434   *
2435   * @param int $post_id Post ID.
2436   * @return mixed False on failure
2437   */
2438  function wp_untrash_post($post_id = 0) {
2439      if ( !$post = get_post($post_id, ARRAY_A) )
2440          return $post;
2441  
2442      if ( $post['post_status'] != 'trash' )
2443          return false;
2444  
2445      do_action('untrash_post', $post_id);
2446  
2447      $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2448  
2449      $post['post_status'] = $post_status;
2450  
2451      delete_post_meta($post_id, '_wp_trash_meta_status');
2452      delete_post_meta($post_id, '_wp_trash_meta_time');
2453  
2454      wp_insert_post($post);
2455  
2456      wp_untrash_post_comments($post_id);
2457  
2458      do_action('untrashed_post', $post_id);
2459  
2460      return $post;
2461  }
2462  
2463  /**
2464   * Moves comments for a post to the trash
2465   *
2466   * @since 2.9.0
2467   * @uses do_action() on 'trash_post_comments' before trashing
2468   * @uses do_action() on 'trashed_post_comments' after trashing
2469   *
2470   * @param int|object $post Post ID or object.
2471   * @return mixed False on failure
2472   */
2473  function wp_trash_post_comments($post = null) {
2474      global $wpdb;
2475  
2476      $post = get_post($post);
2477      if ( empty($post) )
2478          return;
2479  
2480      $post_id = $post->ID;
2481  
2482      do_action('trash_post_comments', $post_id);
2483  
2484      $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2485      if ( empty($comments) )
2486          return;
2487  
2488      // Cache current status for each comment
2489      $statuses = array();
2490      foreach ( $comments as $comment )
2491          $statuses[$comment->comment_ID] = $comment->comment_approved;
2492      add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2493  
2494      // Set status for all comments to post-trashed
2495      $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2496  
2497      clean_comment_cache( array_keys($statuses) );
2498  
2499      do_action('trashed_post_comments', $post_id, $statuses);
2500  
2501      return $result;
2502  }
2503  
2504  /**
2505   * Restore comments for a post from the trash
2506   *
2507   * @since 2.9.0
2508   * @uses do_action() on 'untrash_post_comments' before trashing
2509   * @uses do_action() on 'untrashed_post_comments' after trashing
2510   *
2511   * @param int|object $post Post ID or object.
2512   * @return mixed False on failure
2513   */
2514  function wp_untrash_post_comments($post = null) {
2515      global $wpdb;
2516  
2517      $post = get_post($post);
2518      if ( empty($post) )
2519          return;
2520  
2521      $post_id = $post->ID;
2522  
2523      $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2524  
2525      if ( empty($statuses) )
2526          return true;
2527  
2528      do_action('untrash_post_comments', $post_id);
2529  
2530      // Restore each comment to its original status
2531      $group_by_status = array();
2532      foreach ( $statuses as $comment_id => $comment_status )
2533          $group_by_status[$comment_status][] = $comment_id;
2534  
2535      foreach ( $group_by_status as $status => $comments ) {
2536          // Sanity check. This shouldn't happen.
2537          if ( 'post-trashed' == $status )
2538              $status = '0';
2539          $comments_in = implode( "', '", $comments );
2540          $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
2541      }
2542  
2543      clean_comment_cache( array_keys($statuses) );
2544  
2545      delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2546  
2547      do_action('untrashed_post_comments', $post_id);
2548  }
2549  
2550  /**
2551   * Retrieve the list of categories for a post.
2552   *
2553   * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2554   * away from the complexity of the taxonomy layer.
2555   *
2556   * @since 2.1.0
2557   *
2558   * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
2559   *
2560   * @param int $post_id Optional. The Post ID.
2561   * @param array $args Optional. Overwrite the defaults.
2562   * @return array
2563   */
2564  function wp_get_post_categories( $post_id = 0, $args = array() ) {
2565      $post_id = (int) $post_id;
2566  
2567      $defaults = array('fields' => 'ids');
2568      $args = wp_parse_args( $args, $defaults );
2569  
2570      $cats = wp_get_object_terms($post_id, 'category', $args);
2571      return $cats;
2572  }
2573  
2574  /**
2575   * Retrieve the tags for a post.
2576   *
2577   * There is only one default for this function, called 'fields' and by default
2578   * is set to 'all'. There are other defaults that can be overridden in
2579   * {@link wp_get_object_terms()}.
2580   *
2581   * @package WordPress
2582   * @subpackage Post
2583   * @since 2.3.0
2584   *
2585   * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2586   *
2587   * @param int $post_id Optional. The Post ID
2588   * @param array $args Optional. Overwrite the defaults
2589   * @return array List of post tags.
2590   */
2591  function wp_get_post_tags( $post_id = 0, $args = array() ) {
2592      return wp_get_post_terms( $post_id, 'post_tag', $args);
2593  }
2594  
2595  /**
2596   * Retrieve the terms for a post.
2597   *
2598   * There is only one default for this function, called 'fields' and by default
2599   * is set to 'all'. There are other defaults that can be overridden in
2600   * {@link wp_get_object_terms()}.
2601   *
2602   * @package WordPress
2603   * @subpackage Post
2604   * @since 2.8.0
2605   *
2606   * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
2607   *
2608   * @param int $post_id Optional. The Post ID
2609   * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
2610   * @param array $args Optional. Overwrite the defaults
2611   * @return array List of post tags.
2612   */
2613  function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2614      $post_id = (int) $post_id;
2615  
2616      $defaults = array('fields' => 'all');
2617      $args = wp_parse_args( $args, $defaults );
2618  
2619      $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2620  
2621      return $tags;
2622  }
2623  
2624  /**
2625   * Retrieve number of recent posts.
2626   *
2627   * @since 1.0.0
2628   * @uses wp_parse_args()
2629   * @uses get_posts()
2630   *
2631   * @param string $deprecated Deprecated.
2632   * @param array $args Optional. Overrides defaults.
2633   * @param string $output Optional.
2634   * @return unknown.
2635   */
2636  function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2637  
2638      if ( is_numeric( $args ) ) {
2639          _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2640          $args = array( 'numberposts' => absint( $args ) );
2641      }
2642  
2643      // Set default arguments
2644      $defaults = array(
2645          'numberposts' => 10, 'offset' => 0,
2646          'category' => 0, 'orderby' => 'post_date',
2647          'order' => 'DESC', 'include' => '',
2648          'exclude' => '', 'meta_key' => '',
2649          'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2650          'suppress_filters' => true
2651      );
2652  
2653      $r = wp_parse_args( $args, $defaults );
2654  
2655      $results = get_posts( $r );
2656  
2657      // Backward compatibility. Prior to 3.1 expected posts to be returned in array
2658      if ( ARRAY_A == $output ){
2659          foreach( $results as $key => $result ) {
2660              $results[$key] = get_object_vars( $result );
2661          }
2662          return $results ? $results : array();
2663      }
2664  
2665      return $results ? $results : false;
2666  
2667  }
2668  
2669  /**
2670   * Insert or update a post.
2671   *
2672   * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2673   *
2674   * You can set the post date manually, by setting the values for 'post_date'
2675   * and 'post_date_gmt' keys. You can close the comments or open the comments by
2676   * setting the value for 'comment_status' key.
2677   *
2678   * @global wpdb $wpdb    WordPress database abstraction object.
2679   *
2680   * @since 1.0.0
2681   *
2682   * @param array $postarr {
2683   *     An array of elements that make up a post to update or insert.
2684   *
2685   *     @type int    'ID'                    The post ID. If equal to something other than 0, the post with that ID will
2686   *                                          be updated. Default 0.
2687   *     @type string 'post_status'           The post status. Default 'draft'.
2688   *     @type string 'post_type'             The post type. Default 'post'.
2689   *     @type int    'post_author'           The ID of the user who added the post. Default the current user ID.
2690   *     @type bool   'ping_status'           Whether the post can accept pings. Default value of 'default_ping_status' option.
2691   *     @type int    'post_parent'           Set this for the post it belongs to, if any. Default 0.
2692   *     @type int    'menu_order'            The order it is displayed. Default 0.
2693   *     @type string 'to_ping'               Space or carriage return-separated list of URLs to ping. Default empty string.
2694   *     @type string 'pinged'                Space or carriage return-separated list of URLs that have been pinged.
2695   *                                          Default empty string.
2696   *     @type string 'post_password          The password to access the post. Default empty string.
2697   *     @type string 'guid'                  Global Unique ID for referencing the post.
2698   *     @type string 'post_content_filtered' The filtered post content. Default empty string.
2699   *     @type string 'post_excerpt'          The post excerpt. Default empty string.
2700   * }
2701   * @param bool  $wp_error Optional. Allow return of WP_Error on failure.
2702   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2703   */
2704  function wp_insert_post( $postarr, $wp_error = false ) {
2705      global $wpdb;
2706  
2707      $user_id = get_current_user_id();
2708  
2709      $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id,
2710          'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2711          'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
2712          'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
2713          'post_content' => '', 'post_title' => '');
2714  
2715      $postarr = wp_parse_args($postarr, $defaults);
2716  
2717      unset( $postarr[ 'filter' ] );
2718  
2719      $postarr = sanitize_post($postarr, 'db');
2720  
2721      // export array as variables
2722      extract($postarr, EXTR_SKIP);
2723  
2724      // Are we updating or creating?
2725      $post_ID = 0;
2726      $update = false;
2727      if ( ! empty( $ID ) ) {
2728          $update = true;
2729  
2730          // Get the post ID and GUID
2731          $post_ID = $ID;
2732          $post_before = get_post( $post_ID );
2733          if ( is_null( $post_before ) ) {
2734              if ( $wp_error )
2735                  return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2736              return 0;
2737          }
2738  
2739          $guid = get_post_field( 'guid', $post_ID );
2740          $previous_status = get_post_field('post_status', $ID);
2741      } else {
2742          $previous_status = 'new';
2743      }
2744  
2745      $maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' )
2746          && post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' );
2747  
2748      if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2749          if ( $wp_error )
2750              return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2751          else
2752              return 0;
2753      }
2754  
2755      if ( empty($post_type) )
2756          $post_type = 'post';
2757  
2758      if ( empty($post_status) )
2759          $post_status = 'draft';
2760  
2761      if ( !empty($post_category) )
2762          $post_category = array_filter($post_category); // Filter out empty terms
2763  
2764      // Make sure we set a valid category.
2765      if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
2766          // 'post' requires at least one category.
2767          if ( 'post' == $post_type && 'auto-draft' != $post_status )
2768              $post_category = array( get_option('default_category') );
2769          else
2770              $post_category = array();
2771      }
2772  
2773      if ( empty($post_author) )
2774          $post_author = $user_id;
2775  
2776      // Don't allow contributors to set the post slug for pending review posts
2777      if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
2778          $post_name = '';
2779  
2780      // Create a valid post name. Drafts and pending posts are allowed to have an empty
2781      // post name.
2782      if ( empty($post_name) ) {
2783          if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2784              $post_name = sanitize_title($post_title);
2785          else
2786              $post_name = '';
2787      } else {
2788          // On updates, we need to check to see if it's using the old, fixed sanitization context.
2789          $check_name = sanitize_title( $post_name, '', 'old-save' );
2790          if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name )
2791              $post_name = $check_name;
2792          else // new post, or slug has changed.
2793              $post_name = sanitize_title($post_name);
2794      }
2795  
2796      // 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
2797      if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
2798          $post_date = current_time('mysql');
2799  
2800          // validate the date
2801          $mm = substr( $post_date, 5, 2 );
2802          $jj = substr( $post_date, 8, 2 );
2803          $aa = substr( $post_date, 0, 4 );
2804          $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
2805          if ( !$valid_date ) {
2806              if ( $wp_error )
2807                  return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
2808              else
2809                  return 0;
2810          }
2811  
2812      if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
2813          if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
2814              $post_date_gmt = get_gmt_from_date($post_date);
2815          else
2816              $post_date_gmt = '0000-00-00 00:00:00';
2817      }
2818  
2819      if ( $update || '0000-00-00 00:00:00' == $post_date ) {
2820          $post_modified     = current_time( 'mysql' );
2821          $post_modified_gmt = current_time( 'mysql', 1 );
2822      } else {
2823          $post_modified     = $post_date;
2824          $post_modified_gmt = $post_date_gmt;
2825      }
2826  
2827      if ( 'publish' == $post_status ) {
2828          $now = gmdate('Y-m-d H:i:59');
2829          if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
2830              $post_status = 'future';
2831      } elseif( 'future' == $post_status ) {
2832          $now = gmdate('Y-m-d H:i:59');
2833          if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
2834              $post_status = 'publish';
2835      }
2836  
2837      if ( empty($comment_status) ) {
2838          if ( $update )
2839              $comment_status = 'closed';
2840          else
2841              $comment_status = get_option('default_comment_status');
2842      }
2843      if ( empty($ping_status) )
2844          $ping_status = get_option('default_ping_status');
2845  
2846      if ( isset($to_ping) )
2847          $to_ping = sanitize_trackback_urls( $to_ping );
2848      else
2849          $to_ping = '';
2850  
2851      if ( ! isset($pinged) )
2852          $pinged = '';
2853  
2854      if ( isset($post_parent) )
2855          $post_parent = (int) $post_parent;
2856      else
2857          $post_parent = 0;
2858  
2859      // Check the post_parent to see if it will cause a hierarchy loop
2860      $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
2861  
2862      if ( isset($menu_order) )
2863          $menu_order = (int) $menu_order;
2864      else
2865          $menu_order = 0;
2866  
2867      if ( !isset($post_password) || 'private' == $post_status )
2868          $post_password = '';
2869  
2870      $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2871  
2872      // expected_slashed (everything!)
2873      $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' ) );
2874      $data = apply_filters('wp_insert_post_data', $data, $postarr);
2875      $data = wp_unslash( $data );
2876      $where = array( 'ID' => $post_ID );
2877  
2878      if ( $update ) {
2879          do_action( 'pre_post_update', $post_ID, $data );
2880          if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
2881              if ( $wp_error )
2882                  return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
2883              else
2884                  return 0;
2885          }
2886      } else {
2887          if ( isset($post_mime_type) )
2888              $data['post_mime_type'] = wp_unslash( $post_mime_type ); // This isn't in the update
2889          // If there is a suggested ID, use it if not already present
2890          if ( !empty($import_id) ) {
2891              $import_id = (int) $import_id;
2892              if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2893                  $data['ID'] = $import_id;
2894              }
2895          }
2896          if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
2897              if ( $wp_error )
2898                  return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
2899              else
2900                  return 0;
2901          }
2902          $post_ID = (int) $wpdb->insert_id;
2903  
2904          // use the newly generated $post_ID
2905          $where = array( 'ID' => $post_ID );
2906      }
2907  
2908      if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
2909          $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
2910          $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
2911      }
2912  
2913      if ( is_object_in_taxonomy($post_type, 'category') )
2914          wp_set_post_categories( $post_ID, $post_category );
2915  
2916      if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
2917          wp_set_post_tags( $post_ID, $tags_input );
2918  
2919      // new-style support for all custom taxonomies
2920      if ( !empty($tax_input) ) {
2921          foreach ( $tax_input as $taxonomy => $tags ) {
2922              $taxonomy_obj = get_taxonomy($taxonomy);
2923              if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
2924                  $tags = array_filter($tags);
2925              if ( current_user_can($taxonomy_obj->cap->assign_terms) )
2926                  wp_set_post_terms( $post_ID, $tags, $taxonomy );
2927          }
2928      }
2929  
2930      $current_guid = get_post_field( 'guid', $post_ID );
2931  
2932      // Set GUID
2933      if ( !$update && '' == $current_guid )
2934          $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
2935  
2936      clean_post_cache( $post_ID );
2937  
2938      $post = get_post($post_ID);
2939  
2940      if ( !empty($page_template) && 'page' == $data['post_type'] ) {
2941          $post->page_template = $page_template;
2942          $page_templates = wp_get_theme()->get_page_templates();
2943          if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) {
2944              if ( $wp_error )
2945                  return new WP_Error('invalid_page_template', __('The page template is invalid.'));
2946              else
2947                  return 0;
2948          }
2949          update_post_meta($post_ID, '_wp_page_template',  $page_template);
2950      }
2951  
2952      wp_transition_post_status($data['post_status'], $previous_status, $post);
2953  
2954      if ( $update ) {
2955          do_action('edit_post', $post_ID, $post);
2956          $post_after = get_post($post_ID);
2957          do_action( 'post_updated', $post_ID, $post_after, $post_before);
2958      }
2959  
2960      do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
2961      do_action( 'save_post', $post_ID, $post, $update );
2962      do_action( 'wp_insert_post', $post_ID, $post, $update );
2963  
2964      return $post_ID;
2965  }
2966  
2967  /**
2968   * Update a post with new post data.
2969   *
2970   * The date does not have to be set for drafts. You can set the date and it will
2971   * not be overridden.
2972   *
2973   * @since 1.0.0
2974   *
2975   * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
2976   * @param bool $wp_error Optional. Allow return of WP_Error on failure.
2977   * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
2978   */
2979  function wp_update_post( $postarr = array(), $wp_error = false ) {
2980      if ( is_object($postarr) ) {
2981          // non-escaped post was passed
2982          $postarr = get_object_vars($postarr);
2983          $postarr = wp_slash($postarr);
2984      }
2985  
2986      // First, get all of the original fields
2987      $post = get_post($postarr['ID'], ARRAY_A);
2988  
2989      if ( is_null( $post ) ) {
2990          if ( $wp_error )
2991              return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2992          return 0;
2993      }
2994  
2995      // Escape data pulled from DB.
2996      $post = wp_slash($post);
2997  
2998      // Passed post category list overwrites existing category list if not empty.
2999      if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3000               && 0 != count($postarr['post_category']) )
3001          $post_cats = $postarr['post_category'];
3002      else
3003          $post_cats = $post['post_category'];
3004  
3005      // Drafts shouldn't be assigned a date unless explicitly done so by the user
3006      if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3007               ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3008          $clear_date = true;
3009      else
3010          $clear_date = false;
3011  
3012      // Merge old and new fields with new fields overwriting old ones.
3013      $postarr = array_merge($post, $postarr);
3014      $postarr['post_category'] = $post_cats;
3015      if ( $clear_date ) {
3016          $postarr['post_date'] = current_time('mysql');
3017          $postarr['post_date_gmt'] = '';
3018      }
3019  
3020      if ($postarr['post_type'] == 'attachment')
3021          return wp_insert_attachment($postarr);
3022  
3023      return wp_insert_post( $postarr, $wp_error );
3024  }
3025  
3026  /**
3027   * Publish a post by transitioning the post status.
3028   *
3029   * @since 2.1.0
3030   * @uses $wpdb
3031   * @uses do_action() Calls 'edit_post', 'save_post_{$post_type}', 'save_post' and 'wp_insert_post' on post_id and post data.
3032   *
3033   * @param int|object $post Post ID or object.
3034   */
3035  function wp_publish_post( $post ) {
3036      global $wpdb;
3037  
3038      if ( ! $post = get_post( $post ) )
3039          return;
3040  
3041      if ( 'publish' == $post->post_status )
3042          return;
3043  
3044      $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3045  
3046      clean_post_cache( $post->ID );
3047  
3048      $old_status = $post->post_status;
3049      $post->post_status = 'publish';
3050      wp_transition_post_status( 'publish', $old_status, $post );
3051  
3052      do_action( 'edit_post', $post->ID, $post );
3053      do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3054      do_action( 'save_post', $post->ID, $post, true );
3055      do_action( 'wp_insert_post', $post->ID, $post, true );
3056  }
3057  
3058  /**
3059   * Publish future post and make sure post ID has future post status.
3060   *
3061   * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3062   * from publishing drafts, etc.
3063   *
3064   * @since 2.5.0
3065   *
3066   * @param int $post_id Post ID.
3067   * @return null Nothing is returned. Which can mean that no action is required or post was published.
3068   */
3069  function check_and_publish_future_post($post_id) {
3070  
3071      $post = get_post($post_id);
3072  
3073      if ( empty($post) )
3074          return;
3075  
3076      if ( 'future' != $post->post_status )
3077          return;
3078  
3079      $time = strtotime( $post->post_date_gmt . ' GMT' );
3080  
3081      if ( $time > time() ) { // Uh oh, someone jumped the gun!
3082          wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3083          wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3084          return;
3085      }
3086  
3087      return wp_publish_post($post_id);
3088  }
3089  
3090  /**
3091   * Computes a unique slug for the post, when given the desired slug and some post details.
3092   *
3093   * @since 2.8.0
3094   *
3095   * @global wpdb $wpdb
3096   * @global WP_Rewrite $wp_rewrite
3097   * @param string $slug the desired slug (post_name)
3098   * @param integer $post_ID
3099   * @param string $post_status no uniqueness checks are made if the post is still draft or pending
3100   * @param string $post_type
3101   * @param integer $post_parent
3102   * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3103   */
3104  function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3105      if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3106          return $slug;
3107  
3108      global $wpdb, $wp_rewrite;
3109  
3110      $original_slug = $slug;
3111  
3112      $feeds = $wp_rewrite->feeds;
3113      if ( ! is_array( $feeds ) )
3114          $feeds = array();
3115  
3116      $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
3117      if ( 'attachment' == $post_type ) {
3118          // Attachment slugs must be unique across all types.
3119          $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3120          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3121  
3122          if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3123              $suffix = 2;
3124              do {
3125                  $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3126                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3127                  $suffix++;
3128              } while ( $post_name_check );
3129              $slug = $alt_post_name;
3130          }
3131      } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
3132          if ( 'nav_menu_item' == $post_type )
3133              return $slug;
3134          // Page slugs must be unique within their own trees. Pages are in a separate
3135          // namespace than posts so page slugs are allowed to overlap post slugs.
3136          $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
3137          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
3138  
3139          if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )  || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
3140              $suffix = 2;
3141              do {
3142                  $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3143                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
3144                  $suffix++;
3145              } while ( $post_name_check );
3146              $slug = $alt_post_name;
3147          }
3148      } else {
3149          // Post slugs must be unique across all posts.
3150          $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3151          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3152  
3153          if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3154              $suffix = 2;
3155              do {
3156                  $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3157                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3158                  $suffix++;
3159              } while ( $post_name_check );
3160              $slug = $alt_post_name;
3161          }
3162      }
3163  
3164      return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3165  }
3166  
3167  /**
3168   * Truncates a post slug.
3169   *
3170   * @since 3.6.0
3171   * @access private
3172   * @uses utf8_uri_encode() Makes sure UTF-8 characters are properly cut and encoded.
3173   *
3174   * @param string $slug The slug to truncate.
3175   * @param int $length Max length of the slug.
3176   * @return string The truncated slug.
3177   */
3178  function _truncate_post_slug( $slug, $length = 200 ) {
3179      if ( strlen( $slug ) > $length ) {
3180          $decoded_slug = urldecode( $slug );
3181          if ( $decoded_slug === $slug )
3182              $slug = substr( $slug, 0, $length );
3183          else
3184              $slug = utf8_uri_encode( $decoded_slug, $length );
3185      }
3186  
3187      return rtrim( $slug, '-' );
3188  }
3189  
3190  /**
3191   * Adds tags to a post.
3192   *
3193   * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
3194   *
3195   * @package WordPress
3196   * @subpackage Post
3197   * @since 2.3.0
3198   *
3199   * @param int $post_id Post ID
3200   * @param string $tags The tags to set for the post, separated by commas.
3201   * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
3202   */
3203  function wp_add_post_tags($post_id = 0, $tags = '') {
3204      return wp_set_post_tags($post_id, $tags, true);
3205  }
3206  
3207  /**
3208   * Set the tags for a post.
3209   *
3210   * @since 2.3.0
3211   * @uses wp_set_object_terms() Sets the tags for the post.
3212   *
3213   * @param int $post_id Post ID.
3214   * @param string $tags The tags to set for the post, separated by commas.
3215   * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3216   * @return mixed Array of affected term IDs. WP_Error or false on failure.
3217   */
3218  function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3219      return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3220  }
3221  
3222  /**
3223   * Set the terms for a post.
3224   *
3225   * @since 2.8.0
3226   * @uses wp_set_object_terms() Sets the tags for the post.
3227   *
3228   * @param int $post_id Post ID.
3229   * @param string $tags The tags to set for the post, separated by commas.
3230   * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'.
3231   * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
3232   * @return mixed Array of affected term IDs. WP_Error or false on failure.
3233   */
3234  function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3235      $post_id = (int) $post_id;
3236  
3237      if ( !$post_id )
3238          return false;
3239  
3240      if ( empty($tags) )
3241          $tags = array();
3242  
3243      if ( ! is_array( $tags ) ) {
3244          $comma = _x( ',', 'tag delimiter' );
3245          if ( ',' !== $comma )
3246              $tags = str_replace( $comma, ',', $tags );
3247          $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3248      }
3249  
3250      // Hierarchical taxonomies must always pass IDs rather than names so that children with the same
3251      // names but different parents aren't confused.
3252      if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3253          $tags = array_unique( array_map( 'intval', $tags ) );
3254      }
3255  
3256      return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3257  }
3258  
3259  /**
3260   * Set categories for a post.
3261   *
3262   * If the post categories parameter is not set, then the default category is
3263   * going used.
3264   *
3265   * @since 2.1.0
3266   *
3267   * @param int $post_ID Post ID.
3268   * @param array|int $post_categories Optional. List of categories or ID of category.
3269   * @param bool $append If true, don't delete existing categories, just add on. If false, replace the categories with the new categories.
3270   * @return bool|mixed
3271   */
3272  function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3273      $post_ID = (int) $post_ID;
3274      $post_type = get_post_type( $post_ID );
3275      $post_status = get_post_status( $post_ID );
3276      // If $post_categories isn't already an array, make it one:
3277      $post_categories = (array) $post_categories;
3278      if ( empty( $post_categories ) ) {
3279          if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3280              $post_categories = array( get_option('default_category') );
3281              $append = false;
3282          } else {
3283              $post_categories = array();
3284          }
3285      } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
3286          return true;
3287      }
3288  
3289      return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3290  }
3291  
3292  /**
3293   * Transition the post status of a post.
3294   *
3295   * Calls hooks to transition post status.
3296   *
3297   * The first is 'transition_post_status' with new status, old status, and post data.
3298   *
3299   * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
3300   * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
3301   * post data.
3302   *
3303   * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
3304   * parameter and POSTTYPE is post_type post data.
3305   *
3306   * @since 2.3.0
3307   * @link http://codex.wordpress.org/Post_Status_Transitions
3308   *
3309   * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
3310   *  $post if there is a status change.
3311   * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
3312   * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
3313   *
3314   * @param string $new_status Transition to this post status.
3315   * @param string $old_status Previous post status.
3316   * @param object $post Post data.
3317   */
3318  function wp_transition_post_status($new_status, $old_status, $post) {
3319      do_action('transition_post_status', $new_status, $old_status, $post);
3320      do_action("{$old_status}_to_{$new_status}", $post);
3321      do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
3322  }
3323  
3324  //
3325  // Trackback and ping functions
3326  //
3327  
3328  /**
3329   * Add a URL to those already pung.
3330   *
3331   * @since 1.5.0
3332   * @uses $wpdb
3333   *
3334   * @param int $post_id Post ID.
3335   * @param string $uri Ping URI.
3336   * @return int How many rows were updated.
3337   */
3338  function add_ping($post_id, $uri) {
3339      global $wpdb;
3340      $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3341      $pung = trim($pung);
3342      $pung = preg_split('/\s/', $pung);
3343      $pung[] = $uri;
3344      $new = implode("\n", $pung);
3345      $new = apply_filters('add_ping', $new);
3346      // expected_slashed ($new)
3347      $new = wp_unslash($new);
3348      return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3349  }
3350  
3351  /**
3352   * Retrieve enclosures already enclosed for a post.
3353   *
3354   * @since 1.5.0
3355   *
3356   * @param int $post_id Post ID.
3357   * @return array List of enclosures
3358   */
3359  function get_enclosed($post_id) {
3360      $custom_fields = get_post_custom( $post_id );
3361      $pung = array();
3362      if ( !is_array( $custom_fields ) )
3363          return $pung;
3364  
3365      foreach ( $custom_fields as $key => $val ) {
3366          if ( 'enclosure' != $key || !is_array( $val ) )
3367              continue;
3368          foreach( $val as $enc ) {
3369              $enclosure = explode( "\n", $enc );
3370              $pung[] = trim( $enclosure[ 0 ] );
3371          }
3372      }
3373      $pung = apply_filters('get_enclosed', $pung, $post_id);
3374      return $pung;
3375  }
3376  
3377  /**
3378   * Retrieve URLs already pinged for a post.
3379   *
3380   * @since 1.5.0
3381   * @uses $wpdb
3382   *
3383   * @param int $post_id Post ID.
3384   * @return array
3385   */
3386  function get_pung($post_id) {
3387      global $wpdb;
3388      $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3389      $pung = trim($pung);
3390      $pung = preg_split('/\s/', $pung);
3391      $pung = apply_filters('get_pung', $pung);
3392      return $pung;
3393  }
3394  
3395  /**
3396   * Retrieve URLs that need to be pinged.
3397   *
3398   * @since 1.5.0
3399   * @uses $wpdb
3400   *
3401   * @param int $post_id Post ID
3402   * @return array
3403   */
3404  function get_to_ping($post_id) {
3405      global $wpdb;
3406      $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
3407      $to_ping = sanitize_trackback_urls( $to_ping );
3408      $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
3409      $to_ping = apply_filters('get_to_ping',  $to_ping);
3410      return $to_ping;
3411  }
3412  
3413  /**
3414   * Do trackbacks for a list of URLs.
3415   *
3416   * @since 1.0.0
3417   *
3418   * @param string $tb_list Comma separated list of URLs
3419   * @param int $post_id Post ID
3420   */
3421  function trackback_url_list($tb_list, $post_id) {
3422      if ( ! empty( $tb_list ) ) {
3423          // get post data
3424          $postdata = get_post($post_id, ARRAY_A);
3425  
3426          // import postdata as variables
3427          extract($postdata, EXTR_SKIP);
3428  
3429          // form an excerpt
3430          $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
3431  
3432          if (strlen($excerpt) > 255) {
3433              $excerpt = substr($excerpt,0,252) . '&hellip;';
3434          }
3435  
3436          $trackback_urls = explode(',', $tb_list);
3437          foreach( (array) $trackback_urls as $tb_url) {
3438              $tb_url = trim($tb_url);
3439              trackback($tb_url, wp_unslash($post_title), $excerpt, $post_id);
3440          }
3441      }
3442  }
3443  
3444  //
3445  // Page functions
3446  //
3447  
3448  /**
3449   * Get a list of page IDs.
3450   *
3451   * @since 2.0.0
3452   * @uses $wpdb
3453   *
3454   * @return array List of page IDs.
3455   */
3456  function get_all_page_ids() {
3457      global $wpdb;
3458  
3459      $page_ids = wp_cache_get('all_page_ids', 'posts');
3460      if ( ! is_array( $page_ids ) ) {
3461          $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
3462          wp_cache_add('all_page_ids', $page_ids, 'posts');
3463      }
3464  
3465      return $page_ids;
3466  }
3467  
3468  /**
3469   * Retrieves page data given a page ID or page object.
3470   *
3471   * Use get_post() instead of get_page().
3472   *
3473   * @since 1.5.1
3474   * @deprecated 3.5.0
3475   *
3476   * @param mixed $page Page object or page ID. Passed by reference.
3477   * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
3478   * @param string $filter How the return value should be filtered.
3479   * @return WP_Post|null WP_Post on success or null on failure
3480   */
3481  function get_page( $page, $output = OBJECT, $filter = 'raw') {
3482      return get_post( $page, $output, $filter );
3483  }
3484  
3485  /**
3486   * Retrieves a page given its path.
3487   *
3488   * @since 2.1.0
3489   * @uses $wpdb
3490   *
3491   * @param string $page_path Page path
3492   * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3493   * @param string $post_type Optional. Post type. Default page.
3494   * @return WP_Post|null WP_Post on success or null on failure
3495   */
3496  function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
3497      global $wpdb;
3498  
3499      $page_path = rawurlencode(urldecode($page_path));
3500      $page_path = str_replace('%2F', '/', $page_path);
3501      $page_path = str_replace('%20', ' ', $page_path);
3502      $parts = explode( '/', trim( $page_path, '/' ) );
3503      $parts = esc_sql( $parts );
3504      $parts = array_map( 'sanitize_title_for_query', $parts );
3505  
3506      $in_string = "'". implode( "','", $parts ) . "'";
3507      $post_type_sql = esc_sql( $post_type );
3508      $pages = $wpdb->get_results( "SELECT ID, post_name, post_parent, post_type FROM $wpdb->posts WHERE post_name IN ($in_string) AND (post_type = '$post_type_sql' OR post_type = 'attachment')", OBJECT_K );
3509  
3510      $revparts = array_reverse( $parts );
3511  
3512      $foundid = 0;
3513      foreach ( (array) $pages as $page ) {
3514          if ( $page->post_name == $revparts[0] ) {
3515              $count = 0;
3516              $p = $page;
3517              while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
3518                  $count++;
3519                  $parent = $pages[ $p->post_parent ];
3520                  if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
3521                      break;
3522                  $p = $parent;
3523              }
3524  
3525              if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
3526                  $foundid = $page->ID;
3527                  if ( $page->post_type == $post_type )
3528                      break;
3529              }
3530          }
3531      }
3532  
3533      if ( $foundid )
3534          return get_post( $foundid, $output );
3535  
3536      return null;
3537  }
3538  
3539  /**
3540   * Retrieve a page given its title.
3541   *
3542   * @since 2.1.0
3543   * @uses $wpdb
3544   *
3545   * @param string $page_title Page title
3546   * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
3547   * @param string $post_type Optional. Post type. Default page.
3548   * @return WP_Post|null WP_Post on success or null on failure
3549   */
3550  function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
3551      global $wpdb;
3552      $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
3553      if ( $page )
3554          return get_post( $page, $output );
3555  
3556      return null;
3557  }
3558  
3559  /**
3560   * Retrieve child pages from list of pages matching page ID.
3561   *
3562   * Matches against the pages parameter against the page ID. Also matches all
3563   * children for the same to retrieve all children of a page. Does not make any
3564   * SQL queries to get the children.
3565   *
3566   * @since 1.5.1
3567   *
3568   * @param int $page_id Page ID.
3569   * @param array $pages List of pages' objects.
3570   * @return array
3571   */
3572  function get_page_children($page_id, $pages) {
3573      $page_list = array();
3574      foreach ( (array) $pages as $page ) {
3575          if ( $page->post_parent == $page_id ) {
3576              $page_list[] = $page;
3577              if ( $children = get_page_children($page->ID, $pages) )
3578                  $page_list = array_merge($page_list, $children);
3579          }
3580      }
3581      return $page_list;
3582  }
3583  
3584  /**
3585   * Order the pages with children under parents in a flat list.
3586   *
3587   * It uses auxiliary structure to hold parent-children relationships and
3588   * runs in O(N) complexity
3589   *
3590   * @since 2.0.0
3591   *
3592   * @param array $pages Posts array.
3593   * @param int $page_id Parent page ID.
3594   * @return array A list arranged by hierarchy. Children immediately follow their parents.
3595   */
3596  function get_page_hierarchy( &$pages, $page_id = 0 ) {
3597      if ( empty( $pages ) ) {
3598          $result = array();
3599          return $result;
3600      }
3601  
3602      $children = array();
3603      foreach ( (array) $pages as $p ) {
3604          $parent_id = intval( $p->post_parent );
3605          $children[ $parent_id ][] = $p;
3606      }
3607  
3608      $result = array();
3609      _page_traverse_name( $page_id, $children, $result );
3610  
3611      return $result;
3612  }
3613  
3614  /**
3615   * function to traverse and return all the nested children post names of a root page.
3616   * $children contains parent-children relations
3617   *
3618   * @since 2.9.0
3619   */
3620  function _page_traverse_name( $page_id, &$children, &$result ){
3621      if ( isset( $children[ $page_id ] ) ){
3622          foreach( (array)$children[ $page_id ] as $child ) {
3623              $result[ $child->ID ] = $child->post_name;
3624              _page_traverse_name( $child->ID, $children, $result );
3625          }
3626      }
3627  }
3628  
3629  /**
3630   * Builds URI for a page.
3631   *
3632   * Sub pages will be in the "directory" under the parent page post name.
3633   *
3634   * @since 1.5.0
3635   *
3636   * @param mixed $page Page object or page ID.
3637   * @return string|false Page URI, false on error.
3638   */
3639  function get_page_uri( $page ) {
3640      $page = get_post( $page );
3641  
3642      if ( ! $page )
3643          return false;
3644  
3645      $uri = $page->post_name;
3646  
3647      foreach ( $page->ancestors as $parent ) {
3648          $uri = get_post( $parent )->post_name . '/' . $uri;
3649      }
3650  
3651      return $uri;
3652  }
3653  
3654  /**
3655   * Retrieve a list of pages.
3656   *
3657   * @global wpdb $wpdb WordPress database abstraction object
3658   *
3659   * @since 1.5.0
3660   *
3661   * @param mixed $args {
3662   *     Array or string of arguments. Optional.
3663   *
3664   *     @type int    'child_of'     Page ID to return child and grandchild pages of. Default 0, or no restriction.
3665   *     @type string 'sort_order'   How to sort retrieved pages.
3666   *                                 Default 'ASC'. Accepts 'ASC', 'DESC'.
3667   *     @type string 'sort_column'  What columns to sort pages by, comma-separated.
3668   *                                 Default 'post_title'. Accepts 'post_author', 'post_date', 'post_title', 'post_name',
3669   *                                 'post_modified', 'post_modified_gmt', 'menu_order', 'post_parent', 'ID', 'rand',
3670   *                                 'comment_count'. 'post_' can be omitted for any values that start with it.
3671   *     @type bool   'hierarchical' Whether to return pages hierarchically. Default true.
3672   *     @type array  'exclude'      Array of page IDs to exclude.
3673   *     @type array  'include'      Array of page IDs to include. Cannot be used with 'child_of', 'parent', 'exclude',
3674   *                                 'meta_key', 'meta_value', or 'hierarchical'.
3675   *     @type string 'meta_key'     Only include pages with this meta key.
3676   *     @type string 'meta_value'   Only include pages with this meta value.
3677   *     @type string 'authors'      A comma-separated list of author IDs.
3678   *     @type int    'parent'       Page ID to return direct children of. 'hierarchical' must be false.
3679   *                                 Default -1, or no restriction.
3680   *     @type int    'exclude_tree' Remove all children of the given ID from returned pages.
3681   *     @type int    'number'       The number of pages to return. Default 0, or all pages.
3682   *     @type int    'offset'       The number of pages to skip before returning. Requires 'number'.
3683   *                                 Default 0.
3684   *     @type string 'post_type'    The post type to query.
3685   *                                 Default 'page'.
3686   *     @type string 'post_status'  A comma-separated list of post status types to include.
3687   *                                 Default 'publish'.
3688   * }
3689   * @return array List of pages matching defaults or $args.
3690   */
3691  function get_pages( $args = array() ) {
3692      global $wpdb;
3693  
3694      $pages = false;
3695  
3696      $defaults = array(
3697          'child_of' => 0, 'sort_order' => 'ASC',
3698          'sort_column' => 'post_title', 'hierarchical' => 1,
3699          'exclude' => array(), 'include' => array(),
3700          'meta_key' => '', 'meta_value' => '',
3701          'authors' => '', 'parent' => -1, 'exclude_tree' => '',
3702          'number' => '', 'offset' => 0,
3703          'post_type' => 'page', 'post_status' => 'publish',
3704      );
3705  
3706      $r = wp_parse_args( $args, $defaults );
3707      extract( $r, EXTR_SKIP );
3708      $number = (int) $number;
3709      $offset = (int) $offset;
3710  
3711      // Make sure the post type is hierarchical
3712      $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
3713      if ( !in_array( $post_type, $hierarchical_post_types ) )
3714          return $pages;
3715  
3716      if ( $parent > 0 && ! $child_of )
3717          $hierarchical = false;
3718  
3719      // Make sure we have a valid post status
3720      if ( !is_array( $post_status ) )
3721          $post_status = explode( ',', $post_status );
3722      if ( array_diff( $post_status, get_post_stati() ) )
3723          return $pages;
3724  
3725      // $args can be whatever, only use the args defined in defaults to compute the key
3726      $key = md5( serialize( compact(array_keys($defaults)) ) );
3727      $last_changed = wp_cache_get( 'last_changed', 'posts' );
3728      if ( ! $last_changed ) {
3729          $last_changed = microtime();
3730          wp_cache_set( 'last_changed', $last_changed, 'posts' );
3731      }
3732  
3733      $cache_key = "get_pages:$key:$last_changed";
3734      if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
3735          // Convert to WP_Post instances
3736          $pages = array_map( 'get_post', $cache );
3737          $pages = apply_filters('get_pages', $pages, $r);
3738          return $pages;
3739      }
3740  
3741      if ( !is_array($cache) )
3742          $cache = array();
3743  
3744      $inclusions = '';
3745      if ( ! empty( $include ) ) {
3746          $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
3747          $parent = -1;
3748          $exclude = '';
3749          $meta_key = '';
3750          $meta_value = '';
3751          $hierarchical = false;
3752          $incpages = wp_parse_id_list( $include );
3753          if ( ! empty( $incpages ) )
3754              $inclusions = ' AND ID IN (' . implode( ',', $incpages ) .  ')';
3755      }
3756  
3757      $exclusions = '';
3758      if ( ! empty( $exclude ) ) {
3759          $expages = wp_parse_id_list( $exclude );
3760          if ( ! empty( $expages ) )
3761              $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) .  ')';
3762      }
3763  
3764      $author_query = '';
3765      if (!empty($authors)) {
3766          $post_authors = preg_split('/[\s,]+/',$authors);
3767  
3768          if ( ! empty( $post_authors ) ) {
3769              foreach ( $post_authors as $post_author ) {
3770                  //Do we have an author id or an author login?
3771                  if ( 0 == intval($post_author) ) {
3772                      $post_author = get_user_by('login', $post_author);
3773                      if ( empty($post_author) )
3774                          continue;
3775                      if ( empty($post_author->ID) )
3776                          continue;
3777                      $post_author = $post_author->ID;
3778                  }
3779  
3780                  if ( '' == $author_query )
3781                      $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
3782                  else
3783                      $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
3784              }
3785              if ( '' != $author_query )
3786                  $author_query = " AND ($author_query)";
3787          }
3788      }
3789  
3790      $join = '';
3791      $where = "$exclusions $inclusions ";
3792      if ( '' !== $meta_key || '' !== $meta_value ) {
3793          $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
3794  
3795          // meta_key and meta_value might be slashed
3796          $meta_key = wp_unslash($meta_key);
3797          $meta_value = wp_unslash($meta_value);
3798          if ( '' !== $meta_key )
3799              $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
3800          if ( '' !== $meta_value )
3801              $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
3802  
3803      }
3804  
3805      if ( is_array( $parent ) ) {
3806          $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
3807          if ( ! empty( $post_parent__in ) )
3808              $where .= " AND post_parent IN ($post_parent__in)";
3809      } elseif ( $parent >= 0 ) {
3810          $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
3811      }
3812  
3813      if ( 1 == count( $post_status ) ) {
3814          $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
3815      } else {
3816          $post_status = implode( "', '", $post_status );
3817          $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
3818      }
3819  
3820      $orderby_array = array();
3821      $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
3822                            'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
3823                            'ID', 'rand', 'comment_count');
3824      foreach ( explode( ',', $sort_column ) as $orderby ) {
3825          $orderby = trim( $orderby );
3826          if ( !in_array( $orderby, $allowed_keys ) )
3827              continue;
3828  
3829          switch ( $orderby ) {
3830              case 'menu_order':
3831                  break;
3832              case 'ID':
3833                  $orderby = "$wpdb->posts.ID";
3834                  break;
3835              case 'rand':
3836                  $orderby = 'RAND()';
3837                  break;
3838              case 'comment_count':
3839                  $orderby = "$wpdb->posts.comment_count";
3840                  break;
3841              default:
3842                  if ( 0 === strpos( $orderby, 'post_' ) )
3843                      $orderby = "$wpdb->posts." . $orderby;
3844                  else
3845                      $orderby = "$wpdb->posts.post_" . $orderby;
3846          }
3847  
3848          $orderby_array[] = $orderby;
3849  
3850      }
3851      $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
3852  
3853      $sort_order = strtoupper( $sort_order );
3854      if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
3855          $sort_order = 'ASC';
3856  
3857      $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
3858      $query .= $author_query;
3859      $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
3860  
3861      if ( !empty($number) )
3862          $query .= ' LIMIT ' . $offset . ',' . $number;
3863  
3864      $pages = $wpdb->get_results($query);
3865  
3866      if ( empty($pages) ) {
3867          $pages = apply_filters('get_pages', array(), $r);
3868          return $pages;
3869      }
3870  
3871      // Sanitize before caching so it'll only get done once
3872      $num_pages = count($pages);
3873      for ($i = 0; $i < $num_pages; $i++) {
3874          $pages[$i] = sanitize_post($pages[$i], 'raw');
3875      }
3876  
3877      // Update cache.
3878      update_post_cache( $pages );
3879  
3880      if ( $child_of || $hierarchical )
3881          $pages = get_page_children($child_of, $pages);
3882  
3883      if ( !empty($exclude_tree) ) {
3884          $exclude = (int) $exclude_tree;
3885          $children = get_page_children($exclude, $pages);
3886          $excludes = array();
3887          foreach ( $children as $child )
3888              $excludes[] = $child->ID;
3889          $excludes[] = $exclude;
3890          $num_pages = count($pages);
3891          for ( $i = 0; $i < $num_pages; $i++ ) {
3892              if ( in_array($pages[$i]->ID, $excludes) )
3893                  unset($pages[$i]);
3894          }
3895      }
3896  
3897      $page_structure = array();
3898      foreach ( $pages as $page )
3899          $page_structure[] = $page->ID;
3900  
3901      wp_cache_set( $cache_key, $page_structure, 'posts' );
3902  
3903      // Convert to WP_Post instances
3904      $pages = array_map( 'get_post', $pages );
3905  
3906      $pages = apply_filters('get_pages', $pages, $r);
3907  
3908      return $pages;
3909  }
3910  
3911  //
3912  // Attachment functions
3913  //
3914  
3915  /**
3916   * Check if the attachment URI is local one and is really an attachment.
3917   *
3918   * @since 2.0.0
3919   *
3920   * @param string $url URL to check
3921   * @return bool True on success, false on failure.
3922   */
3923  function is_local_attachment($url) {
3924      if (strpos($url, home_url()) === false)
3925          return false;
3926      if (strpos($url, home_url('/?attachment_id=')) !== false)
3927          return true;
3928      if ( $id = url_to_postid($url) ) {
3929          $post = get_post($id);
3930          if ( 'attachment' == $post->post_type )
3931              return true;
3932      }
3933      return false;
3934  }
3935  
3936  /**
3937   * Insert an attachment.
3938   *
3939   * If you set the 'ID' in the $object parameter, it will mean that you are
3940   * updating and attempt to update the attachment. You can also set the
3941   * attachment name or title by setting the key 'post_name' or 'post_title'.
3942   *
3943   * You can set the dates for the attachment manually by setting the 'post_date'
3944   * and 'post_date_gmt' keys' values.
3945   *
3946   * By default, the comments will use the default settings for whether the
3947   * comments are allowed. You can close them manually or keep them open by
3948   * setting the value for the 'comment_status' key.
3949   *
3950   * The $object parameter can have the following:
3951   *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
3952   *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
3953   *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
3954   *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
3955   *                       can accept pings.
3956   *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
3957   *                       to, if any.
3958   *     'menu_order'    - Default is 0. The order it is displayed.
3959   *     'to_ping'       - Whether to ping.
3960   *     'pinged'        - Default is empty string.
3961   *     'post_password' - Default is empty string. The password to access the attachment.
3962   *     'guid'          - Global Unique ID for referencing the attachment.
3963   *     'post_content_filtered' - Attachment post content filtered.
3964   *     'post_excerpt'  - Attachment excerpt.
3965   *
3966   * @since 2.0.0
3967   * @uses $wpdb
3968   * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
3969   * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
3970   *
3971   * @param string|array $object Arguments to override defaults.
3972   * @param string $file Optional filename.
3973   * @param int $parent Parent post ID.
3974   * @return int Attachment ID.
3975   */
3976  function wp_insert_attachment($object, $file = false, $parent = 0) {
3977      global $wpdb;
3978  
3979      $user_id = get_current_user_id();
3980  
3981      $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id,
3982          'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '',
3983          'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '', 'post_content' => '',
3984          'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
3985  
3986      $object = wp_parse_args($object, $defaults);
3987      if ( !empty($parent) )
3988          $object['post_parent'] = $parent;
3989  
3990      unset( $object[ 'filter' ] );
3991  
3992      $object = sanitize_post($object, 'db');
3993  
3994      // export array as variables
3995      extract($object, EXTR_SKIP);
3996  
3997      if ( empty($post_author) )
3998          $post_author = $user_id;
3999  
4000      $post_type = 'attachment';
4001  
4002      if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
4003          $post_status = 'inherit';
4004  
4005      if ( !empty($post_category) )
4006          $post_category = array_filter($post_category); // Filter out empty terms
4007  
4008      // Make sure we set a valid category.
4009      if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
4010          $post_category = array();
4011      }
4012  
4013      // Are we updating or creating?
4014      if ( !empty($ID) ) {
4015          $update = true;
4016          $post_ID = (int) $ID;
4017      } else {
4018          $update = false;
4019          $post_ID = 0;
4020      }
4021  
4022      // Create a valid post name.
4023      if ( empty($post_name) )
4024          $post_name = sanitize_title($post_title);
4025      else
4026          $post_name = sanitize_title($post_name);
4027  
4028      // expected_slashed ($post_name)
4029      $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
4030  
4031      if ( empty($post_date) )
4032          $post_date = current_time('mysql');
4033      if ( empty($post_date_gmt) )
4034          $post_date_gmt = current_time('mysql', 1);
4035  
4036      if ( empty($post_modified) )
4037          $post_modified = $post_date;
4038      if ( empty($post_modified_gmt) )
4039          $post_modified_gmt = $post_date_gmt;
4040  
4041      if ( empty($comment_status) ) {
4042          if ( $update )
4043              $comment_status = 'closed';
4044          else
4045              $comment_status = get_option('default_comment_status');
4046      }
4047      if ( empty($ping_status) )
4048          $ping_status = get_option('default_ping_status');
4049  
4050      if ( isset($to_ping) )
4051          $to_ping = preg_replace('|\s+|', "\n", $to_ping);
4052      else
4053          $to_ping = '';
4054  
4055      if ( isset($post_parent) )
4056          $post_parent = (int) $post_parent;
4057      else
4058          $post_parent = 0;
4059  
4060      if ( isset($menu_order) )
4061          $menu_order = (int) $menu_order;
4062      else
4063          $menu_order = 0;
4064  
4065      if ( !isset($post_password) )
4066          $post_password = '';
4067  
4068      if ( ! isset($pinged) )
4069          $pinged = '';
4070  
4071      // expected_slashed (everything!)
4072      $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' ) );
4073      $data = wp_unslash( $data );
4074  
4075      if ( $update ) {
4076          $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
4077      } else {
4078          // If there is a suggested ID, use it if not already present
4079          if ( !empty($import_id) ) {
4080              $import_id = (int) $import_id;
4081              if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
4082                  $data['ID'] = $import_id;
4083              }
4084          }
4085  
4086          $wpdb->insert( $wpdb->posts, $data );
4087          $post_ID = (int) $wpdb->insert_id;
4088      }
4089  
4090      if ( empty($post_name) ) {
4091          $post_name = sanitize_title($post_title, $post_ID);
4092          $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
4093      }
4094  
4095      if ( is_object_in_taxonomy($post_type, 'category') )
4096          wp_set_post_categories( $post_ID, $post_category );
4097  
4098      if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
4099          wp_set_post_tags( $post_ID, $tags_input );
4100  
4101      // support for all custom taxonomies
4102      if ( !empty($tax_input) ) {
4103          foreach ( $tax_input as $taxonomy => $tags ) {
4104              $taxonomy_obj = get_taxonomy($taxonomy);
4105              if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
4106                  $tags = array_filter($tags);
4107              if ( current_user_can($taxonomy_obj->cap->assign_terms) )
4108                  wp_set_post_terms( $post_ID, $tags, $taxonomy );
4109          }
4110      }
4111  
4112      if ( $file )
4113          update_attached_file( $post_ID, $file );
4114  
4115      clean_post_cache( $post_ID );
4116  
4117      if ( ! empty( $context ) )
4118          add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
4119  
4120      if ( $update) {
4121          do_action('edit_attachment', $post_ID);
4122      } else {
4123          do_action('add_attachment', $post_ID);
4124      }
4125  
4126      return $post_ID;
4127  }
4128  
4129  /**
4130   * Trashes or deletes an attachment.
4131   *
4132   * When an attachment is permanently deleted, the file will also be removed.
4133   * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4134   * with the attachment (except the main post).
4135   *
4136   * The attachment is moved to the trash instead of permanently deleted unless trash
4137   * for media is disabled, item is already in the trash, or $force_delete is true.
4138   *
4139   * @since 2.0.0
4140   * @uses $wpdb
4141   * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
4142   *
4143   * @param int $post_id Attachment ID.
4144   * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
4145   * @return mixed False on failure. Post data on success.
4146   */
4147  function wp_delete_attachment( $post_id, $force_delete = false ) {
4148      global $wpdb;
4149  
4150      if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4151          return $post;
4152  
4153      if ( 'attachment' != $post->post_type )
4154          return false;
4155  
4156      if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4157          return wp_trash_post( $post_id );
4158  
4159      delete_post_meta($post_id, '_wp_trash_meta_status');
4160      delete_post_meta($post_id, '_wp_trash_meta_time');
4161  
4162      $meta = wp_get_attachment_metadata( $post_id );
4163      $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4164      $file = get_attached_file( $post_id );
4165  
4166      $intermediate_sizes = array();
4167      foreach ( get_intermediate_image_sizes() as $size ) {
4168          if ( $intermediate = image_get_intermediate_size( $post_id, $size ) )
4169              $intermediate_sizes[] = $intermediate;
4170      }
4171  
4172      if ( is_multisite() )
4173          delete_transient( 'dirsize_cache' );
4174  
4175      do_action('delete_attachment', $post_id);
4176  
4177      wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4178      wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4179  
4180      delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts.
4181  
4182      $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4183      foreach ( $comment_ids as $comment_id )
4184          wp_delete_comment( $comment_id, true );
4185  
4186      $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4187      foreach ( $post_meta_ids as $mid )
4188          delete_metadata_by_mid( 'post', $mid );
4189  
4190      do_action( 'delete_post', $post_id );
4191      $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4192      if ( ! $result ) {
4193          return false;
4194      }
4195      do_action( 'deleted_post', $post_id );
4196  
4197      $uploadpath = wp_upload_dir();
4198  
4199      if ( ! empty($meta['thumb']) ) {
4200          // Don't delete the thumb if another attachment uses it
4201          if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id)) ) {
4202              $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4203              /** This filter is documented in wp-admin/custom-header.php */
4204              $thumbfile = apply_filters('wp_delete_file', $thumbfile);
4205              @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4206          }
4207      }
4208  
4209      // remove intermediate and backup images if there are any
4210      foreach ( $intermediate_sizes as $intermediate ) {
4211          /** This filter is documented in wp-admin/custom-header.php */
4212          $intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] );
4213          @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
4214      }
4215  
4216      if ( is_array($backup_sizes) ) {
4217          foreach ( $backup_sizes as $size ) {
4218              $del_file = path_join( dirname($meta['file']), $size['file'] );
4219              /** This filter is documented in wp-admin/custom-header.php */
4220              $del_file = apply_filters('wp_delete_file', $del_file);
4221              @ unlink( path_join($uploadpath['basedir'], $del_file) );
4222          }
4223      }
4224  
4225      /** This filter is documented in wp-admin/custom-header.php */
4226      $file = apply_filters('wp_delete_file', $file);
4227  
4228      if ( ! empty($file) )
4229          @ unlink($file);
4230  
4231      clean_post_cache( $post );
4232  
4233      return $post;
4234  }
4235  
4236  /**
4237   * Retrieve attachment meta field for attachment ID.
4238   *
4239   * @since 2.1.0
4240   *
4241   * @param int $post_id Attachment ID
4242   * @param bool $unfiltered Optional, default is false. If true, filters are not run.
4243   * @return string|bool Attachment meta field. False on failure.
4244   */
4245  function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4246      $post_id = (int) $post_id;
4247      if ( !$post = get_post( $post_id ) )
4248          return false;
4249  
4250      $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4251  
4252      if ( $unfiltered )
4253          return $data;
4254  
4255      return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4256  }
4257  
4258  /**
4259   * Update metadata for an attachment.
4260   *
4261   * @since 2.1.0
4262   *
4263   * @param int $post_id Attachment ID.
4264   * @param array $data Attachment data.
4265   * @return int
4266   */
4267  function wp_update_attachment_metadata( $post_id, $data ) {
4268      $post_id = (int) $post_id;
4269      if ( !$post = get_post( $post_id ) )
4270          return false;
4271  
4272      if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4273          return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4274      else
4275          return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4276  }
4277  
4278  /**
4279   * Retrieve the URL for an attachment.
4280   *
4281   * @since 2.1.0
4282   *
4283   * @param int $post_id Attachment ID.
4284   * @return string
4285   */
4286  function wp_get_attachment_url( $post_id = 0 ) {
4287      $post_id = (int) $post_id;
4288      if ( !$post = get_post( $post_id ) )
4289          return false;
4290  
4291      if ( 'attachment' != $post->post_type )
4292          return false;
4293  
4294      $url = '';
4295      if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
4296          if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
4297              if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
4298                  $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
4299              elseif ( false !== strpos($file, 'wp-content/uploads') )
4300                  $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
4301              else
4302                  $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
4303          }
4304      }
4305  
4306      if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recommended to rely upon this.
4307          $url = get_the_guid( $post->ID );
4308  
4309      $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4310  
4311      if ( empty( $url ) )
4312          return false;
4313  
4314      return $url;
4315  }
4316  
4317  /**
4318   * Retrieve thumbnail for an attachment.
4319   *
4320   * @since 2.1.0
4321   *
4322   * @param int $post_id Attachment ID.
4323   * @return mixed False on failure. Thumbnail file path on success.
4324   */
4325  function wp_get_attachment_thumb_file( $post_id = 0 ) {
4326      $post_id = (int) $post_id;
4327      if ( !$post = get_post( $post_id ) )
4328          return false;
4329      if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
4330          return false;
4331  
4332      $file = get_attached_file( $post->ID );
4333  
4334      if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
4335          return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
4336      return false;
4337  }
4338  
4339  /**
4340   * Retrieve URL for an attachment thumbnail.
4341   *
4342   * @since 2.1.0
4343   *
4344   * @param int $post_id Attachment ID
4345   * @return string|bool False on failure. Thumbnail URL on success.
4346   */
4347  function wp_get_attachment_thumb_url( $post_id = 0 ) {
4348      $post_id = (int) $post_id;
4349      if ( !$post = get_post( $post_id ) )
4350          return false;
4351      if ( !$url = wp_get_attachment_url( $post->ID ) )
4352          return false;
4353  
4354      $sized = image_downsize( $post_id, 'thumbnail' );
4355      if ( $sized )
4356          return $sized[0];
4357  
4358      if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
4359          return false;
4360  
4361      $url = str_replace(basename($url), basename($thumb), $url);
4362  
4363      return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
4364  }
4365  
4366  /**
4367   * Check if the attachment is an image.
4368   *
4369   * @since 2.1.0
4370   *
4371   * @param int $post_id Attachment ID
4372   * @return bool
4373   */
4374  function wp_attachment_is_image( $post_id = 0 ) {
4375      $post_id = (int) $post_id;
4376      if ( !$post = get_post( $post_id ) )
4377          return false;
4378  
4379      if ( !$file = get_attached_file( $post->ID ) )
4380          return false;
4381  
4382      $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
4383  
4384      $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
4385  
4386      if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
4387          return true;
4388      return false;
4389  }
4390  
4391  /**
4392   * Retrieve the icon for a MIME type.
4393   *
4394   * @since 2.1.0
4395   *
4396   * @param string|int $mime MIME type or attachment ID.
4397   * @return string|bool
4398   */
4399  function wp_mime_type_icon( $mime = 0 ) {
4400      if ( !is_numeric($mime) )
4401          $icon = wp_cache_get("mime_type_icon_$mime");
4402  
4403      $post_id = 0;
4404      if ( empty($icon) ) {
4405          $post_mimes = array();
4406          if ( is_numeric($mime) ) {
4407              $mime = (int) $mime;
4408              if ( $post = get_post( $mime ) ) {
4409                  $post_id = (int) $post->ID;
4410                  $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
4411                  if ( !empty($ext) ) {
4412                      $post_mimes[] = $ext;
4413                      if ( $ext_type = wp_ext2type( $ext ) )
4414                          $post_mimes[] = $ext_type;
4415                  }
4416                  $mime = $post->post_mime_type;
4417              } else {
4418                  $mime = 0;
4419              }
4420          } else {
4421              $post_mimes[] = $mime;
4422          }
4423  
4424          $icon_files = wp_cache_get('icon_files');
4425  
4426          if ( !is_array($icon_files) ) {
4427              $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
4428              $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
4429              $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
4430              $icon_files = array();
4431              while ( $dirs ) {
4432                  $keys = array_keys( $dirs );
4433                  $dir = array_shift( $keys );
4434                  $uri = array_shift($dirs);
4435                  if ( $dh = opendir($dir) ) {
4436                      while ( false !== $file = readdir($dh) ) {
4437                          $file = basename($file);
4438                          if ( substr($file, 0, 1) == '.' )
4439                              continue;
4440                          if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
4441                              if ( is_dir("$dir/$file") )
4442                                  $dirs["$dir/$file"] = "$uri/$file";
4443                              continue;
4444                          }
4445                          $icon_files["$dir/$file"] = "$uri/$file";
4446                      }
4447                      closedir($dh);
4448                  }
4449              }
4450              wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
4451          }
4452  
4453          // Icon basename - extension = MIME wildcard
4454          foreach ( $icon_files as $file => $uri )
4455              $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
4456  
4457          if ( ! empty($mime) ) {
4458              $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
4459              $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
4460              $post_mimes[] = str_replace('/', '_', $mime);
4461          }
4462  
4463          $matches = wp_match_mime_types(array_keys($types), $post_mimes);
4464          $matches['default'] = array('default');
4465  
4466          foreach ( $matches as $match => $wilds ) {
4467              if ( isset($types[$wilds[0]])) {
4468                  $icon = $types[$wilds[0]];
4469                  if ( !is_numeric($mime) )
4470                      wp_cache_add("mime_type_icon_$mime", $icon);
4471                  break;
4472              }
4473          }
4474      }
4475  
4476      return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
4477  }
4478  
4479  /**
4480   * Checked for changed slugs for published post objects and save the old slug.
4481   *
4482   * The function is used when a post object of any type is updated,
4483   * by comparing the current and previous post objects.
4484   *
4485   * If the slug was changed and not already part of the old slugs then it will be
4486   * added to the post meta field ('_wp_old_slug') for storing old slugs for that
4487   * post.
4488   *
4489   * The most logically usage of this function is redirecting changed post objects, so
4490   * that those that linked to an changed post will be redirected to the new post.
4491   *
4492   * @since 2.1.0
4493   *
4494   * @param int $post_id Post ID.
4495   * @param object $post The Post Object
4496   * @param object $post_before The Previous Post Object
4497   * @return int Same as $post_id
4498   */
4499  function wp_check_for_changed_slugs($post_id, $post, $post_before) {
4500      // dont bother if it hasnt changed
4501      if ( $post->post_name == $post_before->post_name )
4502          return;
4503  
4504      // we're only concerned with published, non-hierarchical objects
4505      if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
4506          return;
4507  
4508      $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
4509  
4510      // if we haven't added this old slug before, add it now
4511      if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
4512          add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
4513  
4514      // if the new slug was used previously, delete it from the list
4515      if ( in_array($post->post_name, $old_slugs) )
4516          delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
4517  }
4518  
4519  /**
4520   * Retrieve the private post SQL based on capability.
4521   *
4522   * This function provides a standardized way to appropriately select on the
4523   * post_status of a post type. The function will return a piece of SQL code
4524   * that can be added to a WHERE clause; this SQL is constructed to allow all
4525   * published posts, and all private posts to which the user has access.
4526   *
4527   * @since 2.2.0
4528   *
4529   * @param string $post_type currently only supports 'post' or 'page'.
4530   * @return string SQL code that can be added to a where clause.
4531   */
4532  function get_private_posts_cap_sql( $post_type ) {
4533      return get_posts_by_author_sql( $post_type, false );
4534  }
4535  
4536  /**
4537   * Retrieve the post SQL based on capability, author, and type.
4538   *
4539   * @see get_private_posts_cap_sql() for full description.
4540   *
4541   * @since 3.0.0
4542   * @param string $post_type Post type.
4543   * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
4544   * @param int $post_author Optional. Query posts having a single author ID.
4545   * @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user.  Default is false.
4546   * @return string SQL WHERE code that can be added to a query.
4547   */
4548  function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
4549      global $wpdb;
4550  
4551      // Private posts
4552      $post_type_obj = get_post_type_object( $post_type );
4553      if ( ! $post_type_obj )
4554          return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
4555  
4556      // This hook is deprecated. Why you'd want to use it, I dunno.
4557      if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) )
4558          $cap = $post_type_obj->cap->read_private_posts;
4559  
4560      if ( $full ) {
4561          if ( null === $post_author ) {
4562              $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
4563          } else {
4564              $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
4565          }
4566      } else {
4567          $sql = '';
4568      }
4569  
4570      $sql .= "(post_status = 'publish'";
4571  
4572      // Only need to check the cap if $public_only is false
4573      if ( false === $public_only ) {
4574          if ( current_user_can( $cap ) ) {
4575              // Does the user have the capability to view private posts? Guess so.
4576              $sql .= " OR post_status = 'private'";
4577          } elseif ( is_user_logged_in() ) {
4578              // Users can view their own private posts.
4579              $id = get_current_user_id();
4580              if ( null === $post_author || ! $full ) {
4581                  $sql .= " OR post_status = 'private' AND post_author = $id";
4582              } elseif ( $id == (int) $post_author ) {
4583                  $sql .= " OR post_status = 'private'";
4584              } // else none
4585          } // else none
4586      }
4587  
4588      $sql .= ')';
4589  
4590      return $sql;
4591  }
4592  
4593  /**
4594   * Retrieve the date that the last post was published.
4595   *
4596   * The server timezone is the default and is the difference between GMT and
4597   * server time. The 'blog' value is the date when the last post was posted. The
4598   * 'gmt' is when the last post was posted in GMT formatted date.
4599   *
4600   * @since 0.71
4601   *
4602   * @uses apply_filters() Calls 'get_lastpostdate' filter
4603   *
4604   * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4605   * @return string The date of the last post.
4606   */
4607  function get_lastpostdate($timezone = 'server') {
4608      return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
4609  }
4610  
4611  /**
4612   * Retrieve last post modified date depending on timezone.
4613   *
4614   * The server timezone is the default and is the difference between GMT and
4615   * server time. The 'blog' value is just when the last post was modified. The
4616   * 'gmt' is when the last post was modified in GMT time.
4617   *
4618   * @since 1.2.0
4619   * @uses apply_filters() Calls 'get_lastpostmodified' filter
4620   *
4621   * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4622   * @return string The date the post was last modified.
4623   */
4624  function get_lastpostmodified($timezone = 'server') {
4625      $lastpostmodified = _get_last_post_time( $timezone, 'modified' );
4626  
4627      $lastpostdate = get_lastpostdate($timezone);
4628      if ( $lastpostdate > $lastpostmodified )
4629          $lastpostmodified = $lastpostdate;
4630  
4631      return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
4632  }
4633  
4634  /**
4635   * Retrieve latest post date data based on timezone.
4636   *
4637   * @access private
4638   * @since 3.1.0
4639   *
4640   * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
4641   * @param string $field Field to check. Can be 'date' or 'modified'.
4642   * @return string The date.
4643   */
4644  function _get_last_post_time( $timezone, $field ) {
4645      global $wpdb;
4646  
4647      if ( !in_array( $field, array( 'date', 'modified' ) ) )
4648          return false;
4649  
4650      $timezone = strtolower( $timezone );
4651  
4652      $key = "lastpost{$field}:$timezone";
4653  
4654      $date = wp_cache_get( $key, 'timeinfo' );
4655  
4656      if ( !$date ) {
4657          $add_seconds_server = date('Z');
4658  
4659          $post_types = get_post_types( array( 'public' => true ) );
4660          array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
4661          $post_types = "'" . implode( "', '", $post_types ) . "'";
4662  
4663          switch ( $timezone ) {
4664              case 'gmt':
4665                  $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
4666                  break;
4667              case 'blog':
4668                  $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
4669                  break;
4670              case 'server':
4671                  $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
4672                  break;
4673          }
4674  
4675          if ( $date )
4676              wp_cache_set( $key, $date, 'timeinfo' );
4677      }
4678  
4679      return $date;
4680  }
4681  
4682  /**
4683   * Updates posts in cache.
4684   *
4685   * @package WordPress
4686   * @subpackage Cache
4687   * @since 1.5.1
4688   *
4689   * @param array $posts Array of post objects
4690   */
4691  function update_post_cache( &$posts ) {
4692      if ( ! $posts )
4693          return;
4694  
4695      foreach ( $posts as $post )
4696          wp_cache_add( $post->ID, $post, 'posts' );
4697  }
4698  
4699  /**
4700   * Will clean the post in the cache.
4701   *
4702   * Cleaning means delete from the cache of the post. Will call to clean the term
4703   * object cache associated with the post ID.
4704   *
4705   * This function not run if $_wp_suspend_cache_invalidation is not empty. See
4706   * wp_suspend_cache_invalidation().
4707   *
4708   * @package WordPress
4709   * @subpackage Cache
4710   * @since 2.0.0
4711   *
4712   * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
4713   *
4714   * @param int|object $post Post ID or object to remove from the cache
4715   */
4716  function clean_post_cache( $post ) {
4717      global $_wp_suspend_cache_invalidation, $wpdb;
4718  
4719      if ( ! empty( $_wp_suspend_cache_invalidation ) )
4720          return;
4721  
4722      $post = get_post( $post );
4723      if ( empty( $post ) )
4724          return;
4725  
4726      wp_cache_delete( $post->ID, 'posts' );
4727      wp_cache_delete( $post->ID, 'post_meta' );
4728  
4729      clean_object_term_cache( $post->ID, $post->post_type );
4730  
4731      wp_cache_delete( 'wp_get_archives', 'general' );
4732  
4733      do_action( 'clean_post_cache', $post->ID, $post );
4734  
4735      if ( is_post_type_hierarchical( $post->post_type ) )
4736          wp_cache_delete( 'get_pages', 'posts' );
4737  
4738      if ( 'page' == $post->post_type ) {
4739          wp_cache_delete( 'all_page_ids', 'posts' );
4740          do_action( 'clean_page_cache', $post->ID );
4741      }
4742  
4743      wp_cache_set( 'last_changed', microtime(), 'posts' );
4744  }
4745  
4746  /**
4747   * Call major cache updating functions for list of Post objects.
4748   *
4749   * @package WordPress
4750   * @subpackage Cache
4751   * @since 1.5.0
4752   *
4753   * @uses update_post_cache()
4754   * @uses update_object_term_cache()
4755   * @uses update_postmeta_cache()
4756   *
4757   * @param array $posts Array of Post objects
4758   * @param string $post_type The post type of the posts in $posts. Default is 'post'.
4759   * @param bool $update_term_cache Whether to update the term cache. Default is true.
4760   * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
4761   */
4762  function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
4763      // No point in doing all this work if we didn't match any posts.
4764      if ( !$posts )
4765          return;
4766  
4767      update_post_cache($posts);
4768  
4769      $post_ids = array();
4770      foreach ( $posts as $post )
4771          $post_ids[] = $post->ID;
4772  
4773      if ( ! $post_type )
4774          $post_type = 'any';
4775  
4776      if ( $update_term_cache ) {
4777          if ( is_array($post_type) ) {
4778              $ptypes = $post_type;
4779          } elseif ( 'any' == $post_type ) {
4780              // Just use the post_types in the supplied posts.
4781              foreach ( $posts as $post )
4782                  $ptypes[] = $post->post_type;
4783              $ptypes = array_unique($ptypes);
4784          } else {
4785              $ptypes = array($post_type);
4786          }
4787  
4788          if ( ! empty($ptypes) )
4789              update_object_term_cache($post_ids, $ptypes);
4790      }
4791  
4792      if ( $update_meta_cache )
4793          update_postmeta_cache($post_ids);
4794  }
4795  
4796  /**
4797   * Updates metadata cache for list of post IDs.
4798   *
4799   * Performs SQL query to retrieve the metadata for the post IDs and updates the
4800   * metadata cache for the posts. Therefore, the functions, which call this
4801   * function, do not need to perform SQL queries on their own.
4802   *
4803   * @package WordPress
4804   * @subpackage Cache
4805   * @since 2.1.0
4806   *
4807   * @param array $post_ids List of post IDs.
4808   * @return bool|array Returns false if there is nothing to update or an array of metadata.
4809   */
4810  function update_postmeta_cache($post_ids) {
4811      return update_meta_cache('post', $post_ids);
4812  }
4813  
4814  /**
4815   * Will clean the attachment in the cache.
4816   *
4817   * Cleaning means delete from the cache. Optionally will clean the term
4818   * object cache associated with the attachment ID.
4819   *
4820   * This function will not run if $_wp_suspend_cache_invalidation is not empty. See
4821   * wp_suspend_cache_invalidation().
4822   *
4823   * @package WordPress
4824   * @subpackage Cache
4825   * @since 3.0.0
4826   *
4827   * @uses do_action() Calls 'clean_attachment_cache' on $id.
4828   *
4829   * @param int $id The attachment ID in the cache to clean
4830   * @param bool $clean_terms optional. Whether to clean terms cache
4831   */
4832  function clean_attachment_cache($id, $clean_terms = false) {
4833      global $_wp_suspend_cache_invalidation;
4834  
4835      if ( !empty($_wp_suspend_cache_invalidation) )
4836          return;
4837  
4838      $id = (int) $id;
4839  
4840      wp_cache_delete($id, 'posts');
4841      wp_cache_delete($id, 'post_meta');
4842  
4843      if ( $clean_terms )
4844          clean_object_term_cache($id, 'attachment');
4845  
4846      do_action('clean_attachment_cache', $id);
4847  }
4848  
4849  //
4850  // Hooks
4851  //
4852  
4853  /**
4854   * Hook for managing future post transitions to published.
4855   *
4856   * @since 2.3.0
4857   * @access private
4858   * @uses $wpdb
4859   * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
4860   * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
4861   *
4862   * @param string $new_status New post status
4863   * @param string $old_status Previous post status
4864   * @param object $post Object type containing the post information
4865   */
4866  function _transition_post_status($new_status, $old_status, $post) {
4867      global $wpdb;
4868  
4869      if ( $old_status != 'publish' && $new_status == 'publish' ) {
4870          // Reset GUID if transitioning to publish and it is empty
4871          if ( '' == get_the_guid($post->ID) )
4872              $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
4873          do_action('private_to_published', $post->ID);  // Deprecated, use private_to_publish
4874      }
4875  
4876      // If published posts changed clear the lastpostmodified cache
4877      if ( 'publish' == $new_status || 'publish' == $old_status) {
4878          foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
4879              wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
4880              wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
4881          }
4882      }
4883  
4884      // Always clears the hook in case the post status bounced from future to draft.
4885      wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
4886  }
4887  
4888  /**
4889   * Hook used to schedule publication for a post marked for the future.
4890   *
4891   * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
4892   *
4893   * @since 2.3.0
4894   * @access private
4895   *
4896   * @param int $deprecated Not used. Can be set to null. Never implemented.
4897   *   Not marked as deprecated with _deprecated_argument() as it conflicts with
4898   *   wp_transition_post_status() and the default filter for _future_post_hook().
4899   * @param object $post Object type containing the post information
4900   */
4901  function _future_post_hook( $deprecated, $post ) {
4902      wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
4903      wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
4904  }
4905  
4906  /**
4907   * Hook to schedule pings and enclosures when a post is published.
4908   *
4909   * @since 2.3.0
4910   * @access private
4911   * @uses XMLRPC_REQUEST and WP_IMPORTING constants.
4912   * @uses do_action() Calls 'xmlrpc_publish_post' on post ID if XMLRPC_REQUEST is defined.
4913   *
4914   * @param int $post_id The ID in the database table of the post being published
4915   */
4916  function _publish_post_hook($post_id) {
4917      if ( defined('XMLRPC_REQUEST') )
4918          do_action('xmlrpc_publish_post', $post_id);
4919  
4920      if ( defined('WP_IMPORTING') )
4921          return;
4922  
4923      if ( get_option('default_pingback_flag') )
4924          add_post_meta( $post_id, '_pingme', '1' );
4925      add_post_meta( $post_id, '_encloseme', '1' );
4926  
4927      wp_schedule_single_event(time(), 'do_pings');
4928  }
4929  
4930  /**
4931   * Returns the post's parent's post_ID
4932   *
4933   * @since 3.1.0
4934   *
4935   * @param int $post_id
4936   *
4937   * @return int|bool false on error
4938   */
4939  function wp_get_post_parent_id( $post_ID ) {
4940      $post = get_post( $post_ID );
4941      if ( !$post || is_wp_error( $post ) )
4942          return false;
4943      return (int) $post->post_parent;
4944  }
4945  
4946  /**
4947   * Checks the given subset of the post hierarchy for hierarchy loops.
4948   * Prevents loops from forming and breaks those that it finds.
4949   *
4950   * Attached to the wp_insert_post_parent filter.
4951   *
4952   * @since 3.1.0
4953   * @uses wp_find_hierarchy_loop()
4954   *
4955   * @param int $post_parent ID of the parent for the post we're checking.
4956   * @param int $post_ID ID of the post we're checking.
4957   *
4958   * @return int The new post_parent for the post.
4959   */
4960  function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
4961      // Nothing fancy here - bail
4962      if ( !$post_parent )
4963          return 0;
4964  
4965      // New post can't cause a loop
4966      if ( empty( $post_ID ) )
4967          return $post_parent;
4968  
4969      // Can't be its own parent
4970      if ( $post_parent == $post_ID )
4971          return 0;
4972  
4973      // Now look for larger loops
4974  
4975      if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
4976          return $post_parent; // No loop
4977  
4978      // Setting $post_parent to the given value causes a loop
4979      if ( isset( $loop[$post_ID] ) )
4980          return 0;
4981  
4982      // There's a loop, but it doesn't contain $post_ID. Break the loop.
4983      foreach ( array_keys( $loop ) as $loop_member )
4984          wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
4985  
4986      return $post_parent;
4987  }
4988  
4989  /**
4990   * Sets a post thumbnail.
4991   *
4992   * @since 3.1.0
4993   *
4994   * @param int|object $post Post ID or object where thumbnail should be attached.
4995   * @param int $thumbnail_id Thumbnail to attach.
4996   * @return bool True on success, false on failure.
4997   */
4998  function set_post_thumbnail( $post, $thumbnail_id ) {
4999      $post = get_post( $post );
5000      $thumbnail_id = absint( $thumbnail_id );
5001      if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
5002          if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
5003              return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
5004          else
5005              return delete_post_meta( $post->ID, '_thumbnail_id' );
5006      }
5007      return false;
5008  }
5009  
5010  /**
5011   * Removes a post thumbnail.
5012   *
5013   * @since 3.3.0
5014   *
5015   * @param int|object $post Post ID or object where thumbnail should be removed from.
5016   * @return bool True on success, false on failure.
5017   */
5018  function delete_post_thumbnail( $post ) {
5019      $post = get_post( $post );
5020      if ( $post )
5021          return delete_post_meta( $post->ID, '_thumbnail_id' );
5022      return false;
5023  }
5024  
5025  /**
5026   * Deletes auto-drafts for new posts that are > 7 days old
5027   *
5028   * @since 3.4.0
5029   */
5030  function wp_delete_auto_drafts() {
5031      global $wpdb;
5032  
5033      // Cleanup old auto-drafts more than 7 days old
5034      $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
5035      foreach ( (array) $old_posts as $delete )
5036          wp_delete_post( $delete, true ); // Force delete
5037  }
5038  
5039  /**
5040   * Update the custom taxonomies' term counts when a post's status is changed. For example, default posts term counts (for custom taxonomies) don't include private / draft posts.
5041   *
5042   * @access private
5043   * @param string $new_status
5044   * @param string $old_status
5045   * @param object $post
5046   * @since 3.3.0
5047   */
5048  function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
5049      // Update counts for the post's terms.
5050      foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
5051          $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
5052          wp_update_term_count( $tt_ids, $taxonomy );
5053      }
5054  }
5055  
5056  /**
5057   * Adds any posts from the given ids to the cache that do not already exist in cache
5058   *
5059   * @since 3.4.0
5060   *
5061   * @access private
5062   *
5063   * @param array $post_ids ID list
5064   * @param bool $update_term_cache Whether to update the term cache. Default is true.
5065   * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
5066   */
5067  function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
5068      global $wpdb;
5069  
5070      $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
5071      if ( !empty( $non_cached_ids ) ) {
5072          $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
5073  
5074          update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
5075      }
5076  }


Generated: Tue Mar 25 01:41:18 2014 WordPress honlapkészítés: online1.hu