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