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