[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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