[ Index ]

PHP Cross Reference of WordPress

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