[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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