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