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