[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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

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