[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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