[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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