[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Core Post API
   4   *
   5   * @package WordPress
   6   * @subpackage Post
   7   */
   8  
   9  //
  10  // Post Type registration.
  11  //
  12  
  13  /**
  14   * Creates the initial post types when 'init' action is fired.
  15   *
  16   * See {@see 'init'}.
  17   *
  18   * @since 2.9.0
  19   */
  20  function create_initial_post_types() {
  21      WP_Post_Type::reset_default_labels();
  22  
  23      register_post_type(
  24          'post',
  25          array(
  26              'labels'                => array(
  27                  'name_admin_bar' => _x( 'Post', 'add new from admin bar' ),
  28              ),
  29              'public'                => true,
  30              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
  31              '_edit_link'            => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  32              'capability_type'       => 'post',
  33              'map_meta_cap'          => true,
  34              'menu_position'         => 5,
  35              'menu_icon'             => 'dashicons-admin-post',
  36              'hierarchical'          => false,
  37              'rewrite'               => false,
  38              'query_var'             => false,
  39              'delete_with_user'      => true,
  40              'supports'              => array(
  41                  'title',
  42                  'editor' => array( 'notes' => true ),
  43                  'author',
  44                  'thumbnail',
  45                  'excerpt',
  46                  'trackbacks',
  47                  'custom-fields',
  48                  'comments',
  49                  'revisions',
  50                  'post-formats',
  51              ),
  52              'show_in_rest'          => true,
  53              'rest_base'             => 'posts',
  54              'rest_controller_class' => 'WP_REST_Posts_Controller',
  55          )
  56      );
  57  
  58      register_post_type(
  59          'page',
  60          array(
  61              'labels'                => array(
  62                  'name_admin_bar' => _x( 'Page', 'add new from admin bar' ),
  63              ),
  64              'public'                => true,
  65              'publicly_queryable'    => false,
  66              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
  67              '_edit_link'            => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  68              'capability_type'       => 'page',
  69              'map_meta_cap'          => true,
  70              'menu_position'         => 20,
  71              'menu_icon'             => 'dashicons-admin-page',
  72              'hierarchical'          => true,
  73              'rewrite'               => false,
  74              'query_var'             => false,
  75              'delete_with_user'      => true,
  76              'supports'              => array(
  77                  'title',
  78                  'editor' => array( 'notes' => true ),
  79                  'author',
  80                  'thumbnail',
  81                  'page-attributes',
  82                  'custom-fields',
  83                  'comments',
  84                  'revisions',
  85              ),
  86              'show_in_rest'          => true,
  87              'rest_base'             => 'pages',
  88              'rest_controller_class' => 'WP_REST_Posts_Controller',
  89          )
  90      );
  91  
  92      register_post_type(
  93          'attachment',
  94          array(
  95              'labels'                => array(
  96                  'name'           => _x( 'Media', 'post type general name' ),
  97                  'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
  98                  'add_new'        => __( 'Add Media File' ),
  99                  'add_new_item'   => __( 'Add Media File' ),
 100                  'edit_item'      => __( 'Edit Media' ),
 101                  'view_item'      => ( '1' === get_option( 'wp_attachment_pages_enabled' ) ) ? __( 'View Attachment Page' ) : __( 'View Media File' ),
 102                  'attributes'     => __( 'Attachment Attributes' ),
 103              ),
 104              'public'                => true,
 105              'show_ui'               => true,
 106              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 107              '_edit_link'            => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
 108              'capability_type'       => 'post',
 109              'capabilities'          => array(
 110                  'create_posts' => 'upload_files',
 111              ),
 112              'map_meta_cap'          => true,
 113              'menu_icon'             => 'dashicons-admin-media',
 114              'hierarchical'          => false,
 115              'rewrite'               => false,
 116              'query_var'             => false,
 117              'show_in_nav_menus'     => false,
 118              'delete_with_user'      => true,
 119              'supports'              => array( 'title', 'author', 'comments' ),
 120              'show_in_rest'          => true,
 121              'rest_base'             => 'media',
 122              'rest_controller_class' => 'WP_REST_Attachments_Controller',
 123          )
 124      );
 125      add_post_type_support( 'attachment:audio', 'thumbnail' );
 126      add_post_type_support( 'attachment:video', 'thumbnail' );
 127  
 128      register_post_type(
 129          'revision',
 130          array(
 131              'labels'           => array(
 132                  'name'          => __( 'Revisions' ),
 133                  'singular_name' => __( 'Revision' ),
 134              ),
 135              'public'           => false,
 136              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 137              '_edit_link'       => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
 138              'capability_type'  => 'post',
 139              'map_meta_cap'     => true,
 140              'hierarchical'     => false,
 141              'rewrite'          => false,
 142              'query_var'        => false,
 143              'can_export'       => false,
 144              'delete_with_user' => true,
 145              'supports'         => array( 'author' ),
 146          )
 147      );
 148  
 149      register_post_type(
 150          'nav_menu_item',
 151          array(
 152              'labels'                => array(
 153                  'name'          => __( 'Navigation Menu Items' ),
 154                  'singular_name' => __( 'Navigation Menu Item' ),
 155              ),
 156              'public'                => false,
 157              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 158              'hierarchical'          => false,
 159              'rewrite'               => false,
 160              'delete_with_user'      => false,
 161              'query_var'             => false,
 162              'map_meta_cap'          => true,
 163              'capability_type'       => array( 'edit_theme_options', 'edit_theme_options' ),
 164              'capabilities'          => array(
 165                  // Meta Capabilities.
 166                  'edit_post'              => 'edit_post',
 167                  'read_post'              => 'read_post',
 168                  'delete_post'            => 'delete_post',
 169                  // Primitive Capabilities.
 170                  'edit_posts'             => 'edit_theme_options',
 171                  'edit_others_posts'      => 'edit_theme_options',
 172                  'delete_posts'           => 'edit_theme_options',
 173                  'publish_posts'          => 'edit_theme_options',
 174                  'read_private_posts'     => 'edit_theme_options',
 175                  'read'                   => 'read',
 176                  'delete_private_posts'   => 'edit_theme_options',
 177                  'delete_published_posts' => 'edit_theme_options',
 178                  'delete_others_posts'    => 'edit_theme_options',
 179                  'edit_private_posts'     => 'edit_theme_options',
 180                  'edit_published_posts'   => 'edit_theme_options',
 181              ),
 182              'show_in_rest'          => true,
 183              'rest_base'             => 'menu-items',
 184              'rest_controller_class' => 'WP_REST_Menu_Items_Controller',
 185          )
 186      );
 187  
 188      register_post_type(
 189          'custom_css',
 190          array(
 191              'labels'           => array(
 192                  'name'          => __( 'Custom CSS' ),
 193                  'singular_name' => __( 'Custom CSS' ),
 194              ),
 195              'public'           => false,
 196              'hierarchical'     => false,
 197              'rewrite'          => false,
 198              'query_var'        => false,
 199              'delete_with_user' => false,
 200              'can_export'       => true,
 201              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 202              'supports'         => array( 'title', 'revisions' ),
 203              'capabilities'     => array(
 204                  'delete_posts'           => 'edit_theme_options',
 205                  'delete_post'            => 'edit_theme_options',
 206                  'delete_published_posts' => 'edit_theme_options',
 207                  'delete_private_posts'   => 'edit_theme_options',
 208                  'delete_others_posts'    => 'edit_theme_options',
 209                  'edit_post'              => 'edit_css',
 210                  'edit_posts'             => 'edit_css',
 211                  'edit_others_posts'      => 'edit_css',
 212                  'edit_published_posts'   => 'edit_css',
 213                  'read_post'              => 'read',
 214                  'read_private_posts'     => 'read',
 215                  'publish_posts'          => 'edit_theme_options',
 216              ),
 217          )
 218      );
 219  
 220      register_post_type(
 221          'customize_changeset',
 222          array(
 223              'labels'           => array(
 224                  'name'               => _x( 'Changesets', 'post type general name' ),
 225                  'singular_name'      => _x( 'Changeset', 'post type singular name' ),
 226                  'add_new'            => __( 'Add Changeset' ),
 227                  'add_new_item'       => __( 'Add Changeset' ),
 228                  'new_item'           => __( 'New Changeset' ),
 229                  'edit_item'          => __( 'Edit Changeset' ),
 230                  'view_item'          => __( 'View Changeset' ),
 231                  'all_items'          => __( 'All Changesets' ),
 232                  'search_items'       => __( 'Search Changesets' ),
 233                  'not_found'          => __( 'No changesets found.' ),
 234                  'not_found_in_trash' => __( 'No changesets found in Trash.' ),
 235              ),
 236              'public'           => false,
 237              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 238              'map_meta_cap'     => true,
 239              'hierarchical'     => false,
 240              'rewrite'          => false,
 241              'query_var'        => false,
 242              'can_export'       => false,
 243              'delete_with_user' => false,
 244              'supports'         => array( 'title', 'author' ),
 245              'capability_type'  => 'customize_changeset',
 246              'capabilities'     => array(
 247                  'create_posts'           => 'customize',
 248                  'delete_others_posts'    => 'customize',
 249                  'delete_post'            => 'customize',
 250                  'delete_posts'           => 'customize',
 251                  'delete_private_posts'   => 'customize',
 252                  'delete_published_posts' => 'customize',
 253                  'edit_others_posts'      => 'customize',
 254                  'edit_post'              => 'customize',
 255                  'edit_posts'             => 'customize',
 256                  'edit_private_posts'     => 'customize',
 257                  'edit_published_posts'   => 'do_not_allow',
 258                  'publish_posts'          => 'customize',
 259                  'read'                   => 'read',
 260                  'read_post'              => 'customize',
 261                  'read_private_posts'     => 'customize',
 262              ),
 263          )
 264      );
 265  
 266      register_post_type(
 267          'oembed_cache',
 268          array(
 269              'labels'           => array(
 270                  'name'          => __( 'oEmbed Responses' ),
 271                  'singular_name' => __( 'oEmbed Response' ),
 272              ),
 273              'public'           => false,
 274              'hierarchical'     => false,
 275              'rewrite'          => false,
 276              'query_var'        => false,
 277              'delete_with_user' => false,
 278              'can_export'       => false,
 279              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 280              'supports'         => array(),
 281          )
 282      );
 283  
 284      register_post_type(
 285          'user_request',
 286          array(
 287              'labels'           => array(
 288                  'name'          => __( 'User Requests' ),
 289                  'singular_name' => __( 'User Request' ),
 290              ),
 291              'public'           => false,
 292              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 293              'hierarchical'     => false,
 294              'rewrite'          => false,
 295              'query_var'        => false,
 296              'can_export'       => false,
 297              'delete_with_user' => false,
 298              'supports'         => array(),
 299          )
 300      );
 301  
 302      register_post_type(
 303          'wp_block',
 304          array(
 305              'labels'                => array(
 306                  'name'                     => _x( 'Patterns', 'post type general name' ),
 307                  'singular_name'            => _x( 'Pattern', 'post type singular name' ),
 308                  'add_new'                  => __( 'Add Pattern' ),
 309                  'add_new_item'             => __( 'Add Pattern' ),
 310                  'new_item'                 => __( 'New Pattern' ),
 311                  'edit_item'                => __( 'Edit Block Pattern' ),
 312                  'view_item'                => __( 'View Pattern' ),
 313                  'view_items'               => __( 'View Patterns' ),
 314                  'all_items'                => __( 'All Patterns' ),
 315                  'search_items'             => __( 'Search Patterns' ),
 316                  'not_found'                => __( 'No patterns found.' ),
 317                  'not_found_in_trash'       => __( 'No patterns found in Trash.' ),
 318                  'filter_items_list'        => __( 'Filter patterns list' ),
 319                  'items_list_navigation'    => __( 'Patterns list navigation' ),
 320                  'items_list'               => __( 'Patterns list' ),
 321                  'item_published'           => __( 'Pattern published.' ),
 322                  'item_published_privately' => __( 'Pattern published privately.' ),
 323                  'item_reverted_to_draft'   => __( 'Pattern reverted to draft.' ),
 324                  'item_scheduled'           => __( 'Pattern scheduled.' ),
 325                  'item_updated'             => __( 'Pattern updated.' ),
 326              ),
 327              'public'                => false,
 328              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 329              'show_ui'               => true,
 330              'show_in_menu'          => false,
 331              'rewrite'               => false,
 332              'show_in_rest'          => true,
 333              'rest_base'             => 'blocks',
 334              'rest_controller_class' => 'WP_REST_Blocks_Controller',
 335              'capability_type'       => 'block',
 336              'capabilities'          => array(
 337                  // You need to be able to edit posts, in order to read blocks in their raw form.
 338                  'read'                   => 'edit_posts',
 339                  // You need to be able to publish posts, in order to create blocks.
 340                  'create_posts'           => 'publish_posts',
 341                  'edit_posts'             => 'edit_posts',
 342                  'edit_published_posts'   => 'edit_published_posts',
 343                  'delete_published_posts' => 'delete_published_posts',
 344                  // Enables trashing draft posts as well.
 345                  'delete_posts'           => 'delete_posts',
 346                  'edit_others_posts'      => 'edit_others_posts',
 347                  'delete_others_posts'    => 'delete_others_posts',
 348              ),
 349              'map_meta_cap'          => true,
 350              'supports'              => array(
 351                  'title',
 352                  'excerpt',
 353                  'editor',
 354                  'revisions',
 355                  'custom-fields',
 356              ),
 357          )
 358      );
 359  
 360      $template_edit_link = 'site-editor.php?' . build_query(
 361          array(
 362              'p'      => '/%s/%s',
 363              'canvas' => 'edit',
 364          )
 365      );
 366  
 367      register_post_type(
 368          'wp_template',
 369          array(
 370              'labels'                          => array(
 371                  'name'                  => _x( 'Templates', 'post type general name' ),
 372                  'singular_name'         => _x( 'Template', 'post type singular name' ),
 373                  'add_new'               => __( 'Add Template' ),
 374                  'add_new_item'          => __( 'Add Template' ),
 375                  'new_item'              => __( 'New Template' ),
 376                  'edit_item'             => __( 'Edit Template' ),
 377                  'view_item'             => __( 'View Template' ),
 378                  'all_items'             => __( 'Templates' ),
 379                  'search_items'          => __( 'Search Templates' ),
 380                  'parent_item_colon'     => __( 'Parent Template:' ),
 381                  'not_found'             => __( 'No templates found.' ),
 382                  'not_found_in_trash'    => __( 'No templates found in Trash.' ),
 383                  'archives'              => __( 'Template archives' ),
 384                  'insert_into_item'      => __( 'Insert into template' ),
 385                  'uploaded_to_this_item' => __( 'Uploaded to this template' ),
 386                  'filter_items_list'     => __( 'Filter templates list' ),
 387                  'items_list_navigation' => __( 'Templates list navigation' ),
 388                  'items_list'            => __( 'Templates list' ),
 389                  'item_updated'          => __( 'Template updated.' ),
 390              ),
 391              'description'                     => __( 'Templates to include in your theme.' ),
 392              'public'                          => false,
 393              '_builtin'                        => true, /* internal use only. don't use this when registering your own post type. */
 394              '_edit_link'                      => $template_edit_link, /* internal use only. don't use this when registering your own post type. */
 395              'has_archive'                     => false,
 396              'show_ui'                         => false,
 397              'show_in_menu'                    => false,
 398              'show_in_rest'                    => true,
 399              'rewrite'                         => false,
 400              'rest_base'                       => 'templates',
 401              'rest_controller_class'           => 'WP_REST_Templates_Controller',
 402              'autosave_rest_controller_class'  => 'WP_REST_Template_Autosaves_Controller',
 403              'revisions_rest_controller_class' => 'WP_REST_Template_Revisions_Controller',
 404              'late_route_registration'         => true,
 405              'capability_type'                 => array( 'template', 'templates' ),
 406              'capabilities'                    => array(
 407                  'create_posts'           => 'edit_theme_options',
 408                  'delete_posts'           => 'edit_theme_options',
 409                  'delete_others_posts'    => 'edit_theme_options',
 410                  'delete_private_posts'   => 'edit_theme_options',
 411                  'delete_published_posts' => 'edit_theme_options',
 412                  'edit_posts'             => 'edit_theme_options',
 413                  'edit_others_posts'      => 'edit_theme_options',
 414                  'edit_private_posts'     => 'edit_theme_options',
 415                  'edit_published_posts'   => 'edit_theme_options',
 416                  'publish_posts'          => 'edit_theme_options',
 417                  'read'                   => 'edit_theme_options',
 418                  'read_private_posts'     => 'edit_theme_options',
 419              ),
 420              'map_meta_cap'                    => true,
 421              'supports'                        => array(
 422                  'title',
 423                  'slug',
 424                  'excerpt',
 425                  'editor',
 426                  'revisions',
 427                  'author',
 428              ),
 429          )
 430      );
 431  
 432      register_post_type(
 433          'wp_template_part',
 434          array(
 435              'labels'                          => array(
 436                  'name'                  => _x( 'Template Parts', 'post type general name' ),
 437                  'singular_name'         => _x( 'Template Part', 'post type singular name' ),
 438                  'add_new'               => __( 'Add Template Part' ),
 439                  'add_new_item'          => __( 'Add Template Part' ),
 440                  'new_item'              => __( 'New Template Part' ),
 441                  'edit_item'             => __( 'Edit Template Part' ),
 442                  'view_item'             => __( 'View Template Part' ),
 443                  'all_items'             => __( 'Template Parts' ),
 444                  'search_items'          => __( 'Search Template Parts' ),
 445                  'parent_item_colon'     => __( 'Parent Template Part:' ),
 446                  'not_found'             => __( 'No template parts found.' ),
 447                  'not_found_in_trash'    => __( 'No template parts found in Trash.' ),
 448                  'archives'              => __( 'Template part archives' ),
 449                  'insert_into_item'      => __( 'Insert into template part' ),
 450                  'uploaded_to_this_item' => __( 'Uploaded to this template part' ),
 451                  'filter_items_list'     => __( 'Filter template parts list' ),
 452                  'items_list_navigation' => __( 'Template parts list navigation' ),
 453                  'items_list'            => __( 'Template parts list' ),
 454                  'item_updated'          => __( 'Template part updated.' ),
 455              ),
 456              'description'                     => __( 'Template parts to include in your templates.' ),
 457              'public'                          => false,
 458              '_builtin'                        => true, /* internal use only. don't use this when registering your own post type. */
 459              '_edit_link'                      => $template_edit_link, /* internal use only. don't use this when registering your own post type. */
 460              'has_archive'                     => false,
 461              'show_ui'                         => false,
 462              'show_in_menu'                    => false,
 463              'show_in_rest'                    => true,
 464              'rewrite'                         => false,
 465              'rest_base'                       => 'template-parts',
 466              'rest_controller_class'           => 'WP_REST_Templates_Controller',
 467              'autosave_rest_controller_class'  => 'WP_REST_Template_Autosaves_Controller',
 468              'revisions_rest_controller_class' => 'WP_REST_Template_Revisions_Controller',
 469              'late_route_registration'         => true,
 470              'map_meta_cap'                    => true,
 471              'capabilities'                    => array(
 472                  'create_posts'           => 'edit_theme_options',
 473                  'delete_posts'           => 'edit_theme_options',
 474                  'delete_others_posts'    => 'edit_theme_options',
 475                  'delete_private_posts'   => 'edit_theme_options',
 476                  'delete_published_posts' => 'edit_theme_options',
 477                  'edit_posts'             => 'edit_theme_options',
 478                  'edit_others_posts'      => 'edit_theme_options',
 479                  'edit_private_posts'     => 'edit_theme_options',
 480                  'edit_published_posts'   => 'edit_theme_options',
 481                  'publish_posts'          => 'edit_theme_options',
 482                  'read'                   => 'edit_theme_options',
 483                  'read_private_posts'     => 'edit_theme_options',
 484              ),
 485              'supports'                        => array(
 486                  'title',
 487                  'slug',
 488                  'excerpt',
 489                  'editor',
 490                  'revisions',
 491                  'author',
 492              ),
 493          )
 494      );
 495  
 496      register_post_type(
 497          'wp_global_styles',
 498          array(
 499              'label'                           => _x( 'Global Styles', 'post type general name' ),
 500              'description'                     => __( 'Global styles to include in themes.' ),
 501              'public'                          => false,
 502              '_builtin'                        => true, /* internal use only. don't use this when registering your own post type. */
 503              '_edit_link'                      => '/site-editor.php?canvas=edit', /* internal use only. don't use this when registering your own post type. */
 504              'show_ui'                         => false,
 505              'show_in_rest'                    => true,
 506              'rewrite'                         => false,
 507              'rest_base'                       => 'global-styles',
 508              'rest_controller_class'           => 'WP_REST_Global_Styles_Controller',
 509              'revisions_rest_controller_class' => 'WP_REST_Global_Styles_Revisions_Controller',
 510              'late_route_registration'         => true,
 511              'capabilities'                    => array(
 512                  'read'                   => 'edit_posts',
 513                  'create_posts'           => 'edit_theme_options',
 514                  'edit_posts'             => 'edit_theme_options',
 515                  'edit_published_posts'   => 'edit_theme_options',
 516                  'delete_published_posts' => 'edit_theme_options',
 517                  'edit_others_posts'      => 'edit_theme_options',
 518                  'delete_others_posts'    => 'edit_theme_options',
 519              ),
 520              'map_meta_cap'                    => true,
 521              'supports'                        => array(
 522                  'title',
 523                  'editor',
 524                  'revisions',
 525              ),
 526          )
 527      );
 528      // Disable autosave endpoints for global styles.
 529      remove_post_type_support( 'wp_global_styles', 'autosave' );
 530  
 531      $navigation_post_edit_link = 'site-editor.php?' . build_query(
 532          array(
 533              'p'      => '/wp_navigation/%s',
 534              'canvas' => 'edit',
 535          )
 536      );
 537  
 538      register_post_type(
 539          'wp_navigation',
 540          array(
 541              'labels'                => array(
 542                  'name'                  => _x( 'Navigation Menus', 'post type general name' ),
 543                  'singular_name'         => _x( 'Navigation Menu', 'post type singular name' ),
 544                  'add_new'               => __( 'Add Navigation Menu' ),
 545                  'add_new_item'          => __( 'Add Navigation Menu' ),
 546                  'new_item'              => __( 'New Navigation Menu' ),
 547                  'edit_item'             => __( 'Edit Navigation Menu' ),
 548                  'view_item'             => __( 'View Navigation Menu' ),
 549                  'all_items'             => __( 'Navigation Menus' ),
 550                  'search_items'          => __( 'Search Navigation Menus' ),
 551                  'parent_item_colon'     => __( 'Parent Navigation Menu:' ),
 552                  'not_found'             => __( 'No Navigation Menu found.' ),
 553                  'not_found_in_trash'    => __( 'No Navigation Menu found in Trash.' ),
 554                  'archives'              => __( 'Navigation Menu archives' ),
 555                  'insert_into_item'      => __( 'Insert into Navigation Menu' ),
 556                  'uploaded_to_this_item' => __( 'Uploaded to this Navigation Menu' ),
 557                  'filter_items_list'     => __( 'Filter Navigation Menu list' ),
 558                  'items_list_navigation' => __( 'Navigation Menus list navigation' ),
 559                  'items_list'            => __( 'Navigation Menus list' ),
 560                  'item_updated'          => __( 'Navigation Menu updated.' ),
 561              ),
 562              'description'           => __( 'Navigation menus that can be inserted into your site.' ),
 563              'public'                => false,
 564              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 565              '_edit_link'            => $navigation_post_edit_link, /* internal use only. don't use this when registering your own post type. */
 566              'has_archive'           => false,
 567              'show_ui'               => true,
 568              'show_in_menu'          => false,
 569              'show_in_admin_bar'     => false,
 570              'show_in_rest'          => true,
 571              'rewrite'               => false,
 572              'map_meta_cap'          => true,
 573              'capabilities'          => array(
 574                  'edit_others_posts'      => 'edit_theme_options',
 575                  'delete_posts'           => 'edit_theme_options',
 576                  'publish_posts'          => 'edit_theme_options',
 577                  'create_posts'           => 'edit_theme_options',
 578                  'read_private_posts'     => 'edit_theme_options',
 579                  'delete_private_posts'   => 'edit_theme_options',
 580                  'delete_published_posts' => 'edit_theme_options',
 581                  'delete_others_posts'    => 'edit_theme_options',
 582                  'edit_private_posts'     => 'edit_theme_options',
 583                  'edit_published_posts'   => 'edit_theme_options',
 584                  'edit_posts'             => 'edit_theme_options',
 585              ),
 586              'rest_base'             => 'navigation',
 587              'rest_controller_class' => 'WP_REST_Posts_Controller',
 588              'supports'              => array(
 589                  'title',
 590                  'editor',
 591                  'revisions',
 592              ),
 593          )
 594      );
 595  
 596      register_post_type(
 597          'wp_font_family',
 598          array(
 599              'labels'                => array(
 600                  'name'          => __( 'Font Families' ),
 601                  'singular_name' => __( 'Font Family' ),
 602              ),
 603              'public'                => false,
 604              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 605              'hierarchical'          => false,
 606              'capabilities'          => array(
 607                  'read'                   => 'edit_theme_options',
 608                  'read_private_posts'     => 'edit_theme_options',
 609                  'create_posts'           => 'edit_theme_options',
 610                  'publish_posts'          => 'edit_theme_options',
 611                  'edit_posts'             => 'edit_theme_options',
 612                  'edit_others_posts'      => 'edit_theme_options',
 613                  'edit_published_posts'   => 'edit_theme_options',
 614                  'delete_posts'           => 'edit_theme_options',
 615                  'delete_others_posts'    => 'edit_theme_options',
 616                  'delete_published_posts' => 'edit_theme_options',
 617              ),
 618              'map_meta_cap'          => true,
 619              'query_var'             => false,
 620              'rewrite'               => false,
 621              'show_in_rest'          => true,
 622              'rest_base'             => 'font-families',
 623              'rest_controller_class' => 'WP_REST_Font_Families_Controller',
 624              'supports'              => array( 'title' ),
 625          )
 626      );
 627  
 628      register_post_type(
 629          'wp_font_face',
 630          array(
 631              'labels'                => array(
 632                  'name'          => __( 'Font Faces' ),
 633                  'singular_name' => __( 'Font Face' ),
 634              ),
 635              'public'                => false,
 636              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 637              'hierarchical'          => false,
 638              'capabilities'          => array(
 639                  'read'                   => 'edit_theme_options',
 640                  'read_private_posts'     => 'edit_theme_options',
 641                  'create_posts'           => 'edit_theme_options',
 642                  'publish_posts'          => 'edit_theme_options',
 643                  'edit_posts'             => 'edit_theme_options',
 644                  'edit_others_posts'      => 'edit_theme_options',
 645                  'edit_published_posts'   => 'edit_theme_options',
 646                  'delete_posts'           => 'edit_theme_options',
 647                  'delete_others_posts'    => 'edit_theme_options',
 648                  'delete_published_posts' => 'edit_theme_options',
 649              ),
 650              'map_meta_cap'          => true,
 651              'query_var'             => false,
 652              'rewrite'               => false,
 653              'show_in_rest'          => true,
 654              'rest_base'             => 'font-families/(?P<font_family_id>[\d]+)/font-faces',
 655              'rest_controller_class' => 'WP_REST_Font_Faces_Controller',
 656              'supports'              => array( 'title' ),
 657          )
 658      );
 659  
 660      register_post_status(
 661          'publish',
 662          array(
 663              'label'       => _x( 'Published', 'post status' ),
 664              'public'      => true,
 665              '_builtin'    => true, /* internal use only. */
 666              /* translators: %s: Number of published posts. */
 667              'label_count' => _n_noop(
 668                  'Published <span class="count">(%s)</span>',
 669                  'Published <span class="count">(%s)</span>'
 670              ),
 671          )
 672      );
 673  
 674      register_post_status(
 675          'future',
 676          array(
 677              'label'       => _x( 'Scheduled', 'post status' ),
 678              'protected'   => true,
 679              '_builtin'    => true, /* internal use only. */
 680              /* translators: %s: Number of scheduled posts. */
 681              'label_count' => _n_noop(
 682                  'Scheduled <span class="count">(%s)</span>',
 683                  'Scheduled <span class="count">(%s)</span>'
 684              ),
 685          )
 686      );
 687  
 688      register_post_status(
 689          'draft',
 690          array(
 691              'label'         => _x( 'Draft', 'post status' ),
 692              'protected'     => true,
 693              '_builtin'      => true, /* internal use only. */
 694              /* translators: %s: Number of draft posts. */
 695              'label_count'   => _n_noop(
 696                  'Draft <span class="count">(%s)</span>',
 697                  'Drafts <span class="count">(%s)</span>'
 698              ),
 699              'date_floating' => true,
 700          )
 701      );
 702  
 703      register_post_status(
 704          'pending',
 705          array(
 706              'label'         => _x( 'Pending', 'post status' ),
 707              'protected'     => true,
 708              '_builtin'      => true, /* internal use only. */
 709              /* translators: %s: Number of pending posts. */
 710              'label_count'   => _n_noop(
 711                  'Pending <span class="count">(%s)</span>',
 712                  'Pending <span class="count">(%s)</span>'
 713              ),
 714              'date_floating' => true,
 715          )
 716      );
 717  
 718      register_post_status(
 719          'private',
 720          array(
 721              'label'       => _x( 'Private', 'post status' ),
 722              'private'     => true,
 723              '_builtin'    => true, /* internal use only. */
 724              /* translators: %s: Number of private posts. */
 725              'label_count' => _n_noop(
 726                  'Private <span class="count">(%s)</span>',
 727                  'Private <span class="count">(%s)</span>'
 728              ),
 729          )
 730      );
 731  
 732      register_post_status(
 733          'trash',
 734          array(
 735              'label'                     => _x( 'Trash', 'post status' ),
 736              'internal'                  => true,
 737              '_builtin'                  => true, /* internal use only. */
 738              /* translators: %s: Number of trashed posts. */
 739              'label_count'               => _n_noop(
 740                  'Trash <span class="count">(%s)</span>',
 741                  'Trash <span class="count">(%s)</span>'
 742              ),
 743              'show_in_admin_status_list' => true,
 744          )
 745      );
 746  
 747      register_post_status(
 748          'auto-draft',
 749          array(
 750              'label'         => 'auto-draft',
 751              'internal'      => true,
 752              '_builtin'      => true, /* internal use only. */
 753              'date_floating' => true,
 754          )
 755      );
 756  
 757      register_post_status(
 758          'inherit',
 759          array(
 760              'label'               => 'inherit',
 761              'internal'            => true,
 762              '_builtin'            => true, /* internal use only. */
 763              'exclude_from_search' => false,
 764          )
 765      );
 766  
 767      register_post_status(
 768          'request-pending',
 769          array(
 770              'label'               => _x( 'Pending', 'request status' ),
 771              'internal'            => true,
 772              '_builtin'            => true, /* internal use only. */
 773              /* translators: %s: Number of pending requests. */
 774              'label_count'         => _n_noop(
 775                  'Pending <span class="count">(%s)</span>',
 776                  'Pending <span class="count">(%s)</span>'
 777              ),
 778              'exclude_from_search' => false,
 779          )
 780      );
 781  
 782      register_post_status(
 783          'request-confirmed',
 784          array(
 785              'label'               => _x( 'Confirmed', 'request status' ),
 786              'internal'            => true,
 787              '_builtin'            => true, /* internal use only. */
 788              /* translators: %s: Number of confirmed requests. */
 789              'label_count'         => _n_noop(
 790                  'Confirmed <span class="count">(%s)</span>',
 791                  'Confirmed <span class="count">(%s)</span>'
 792              ),
 793              'exclude_from_search' => false,
 794          )
 795      );
 796  
 797      register_post_status(
 798          'request-failed',
 799          array(
 800              'label'               => _x( 'Failed', 'request status' ),
 801              'internal'            => true,
 802              '_builtin'            => true, /* internal use only. */
 803              /* translators: %s: Number of failed requests. */
 804              'label_count'         => _n_noop(
 805                  'Failed <span class="count">(%s)</span>',
 806                  'Failed <span class="count">(%s)</span>'
 807              ),
 808              'exclude_from_search' => false,
 809          )
 810      );
 811  
 812      register_post_status(
 813          'request-completed',
 814          array(
 815              'label'               => _x( 'Completed', 'request status' ),
 816              'internal'            => true,
 817              '_builtin'            => true, /* internal use only. */
 818              /* translators: %s: Number of completed requests. */
 819              'label_count'         => _n_noop(
 820                  'Completed <span class="count">(%s)</span>',
 821                  'Completed <span class="count">(%s)</span>'
 822              ),
 823              'exclude_from_search' => false,
 824          )
 825      );
 826  }
 827  
 828  /**
 829   * Retrieves attached file path based on attachment ID.
 830   *
 831   * By default the path will go through the {@see 'get_attached_file'} filter, but
 832   * passing `true` to the `$unfiltered` argument will return the file path unfiltered.
 833   *
 834   * The function works by retrieving the `_wp_attached_file` post meta value.
 835   * This is a convenience function to prevent looking up the meta name and provide
 836   * a mechanism for sending the attached filename through a filter.
 837   *
 838   * @since 2.0.0
 839   *
 840   * @param int  $attachment_id Attachment ID.
 841   * @param bool $unfiltered    Optional. Whether to skip the {@see 'get_attached_file'} filter.
 842   *                            Default false.
 843   * @return string|false The file path to where the attached file should be, false otherwise.
 844   */
 845  function get_attached_file( $attachment_id, $unfiltered = false ) {
 846      $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
 847  
 848      // If the file is relative, prepend upload dir.
 849      if ( $file && ! str_starts_with( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) ) {
 850          $uploads = wp_get_upload_dir();
 851          if ( false === $uploads['error'] ) {
 852              $file = $uploads['basedir'] . "/$file";
 853          }
 854      }
 855  
 856      if ( $unfiltered ) {
 857          return $file;
 858      }
 859  
 860      /**
 861       * Filters the attached file based on the given ID.
 862       *
 863       * @since 2.1.0
 864       *
 865       * @param string|false $file          The file path to where the attached file should be, false otherwise.
 866       * @param int          $attachment_id Attachment ID.
 867       */
 868      return apply_filters( 'get_attached_file', $file, $attachment_id );
 869  }
 870  
 871  /**
 872   * Updates attachment file path based on attachment ID.
 873   *
 874   * Used to update the file path of the attachment, which uses post meta name
 875   * `_wp_attached_file` to store the path of the attachment.
 876   *
 877   * @since 2.1.0
 878   *
 879   * @param int    $attachment_id Attachment ID.
 880   * @param string $file          File path for the attachment.
 881   * @return int|bool Meta ID if the `_wp_attached_file` key didn't exist for the attachment.
 882   *                  True on successful update, false on failure or if the `$file` value passed
 883   *                  to the function is the same as the one that is already in the database.
 884   */
 885  function update_attached_file( $attachment_id, $file ) {
 886      if ( ! get_post( $attachment_id ) ) {
 887          return false;
 888      }
 889  
 890      /**
 891       * Filters the path to the attached file to update.
 892       *
 893       * @since 2.1.0
 894       *
 895       * @param string $file          Path to the attached file to update.
 896       * @param int    $attachment_id Attachment ID.
 897       */
 898      $file = apply_filters( 'update_attached_file', $file, $attachment_id );
 899  
 900      $file = _wp_relative_upload_path( $file );
 901      if ( $file ) {
 902          return update_post_meta( $attachment_id, '_wp_attached_file', $file );
 903      } else {
 904          return delete_post_meta( $attachment_id, '_wp_attached_file' );
 905      }
 906  }
 907  
 908  /**
 909   * Returns relative path to an uploaded file.
 910   *
 911   * The path is relative to the current upload dir.
 912   *
 913   * @since 2.9.0
 914   * @access private
 915   *
 916   * @param string $path Full path to the file.
 917   * @return string Relative path on success, unchanged path on failure.
 918   */
 919  function _wp_relative_upload_path( $path ) {
 920      $new_path = $path;
 921  
 922      $uploads = wp_get_upload_dir();
 923      if ( str_starts_with( $new_path, $uploads['basedir'] ) ) {
 924              $new_path = str_replace( $uploads['basedir'], '', $new_path );
 925              $new_path = ltrim( $new_path, '/' );
 926      }
 927  
 928      /**
 929       * Filters the relative path to an uploaded file.
 930       *
 931       * @since 2.9.0
 932       *
 933       * @param string $new_path Relative path to the file.
 934       * @param string $path     Full path to the file.
 935       */
 936      return apply_filters( '_wp_relative_upload_path', $new_path, $path );
 937  }
 938  
 939  /**
 940   * Retrieves all children of the post parent ID.
 941   *
 942   * Normally, without any enhancements, the children would apply to pages. In the
 943   * context of the inner workings of WordPress, pages, posts, and attachments
 944   * share the same table, so therefore the functionality could apply to any one
 945   * of them. It is then noted that while this function does not work on posts, it
 946   * does not mean that it won't work on posts. It is recommended that you know
 947   * what context you wish to retrieve the children of.
 948   *
 949   * Attachments may also be made the child of a post, so if that is an accurate
 950   * statement (which needs to be verified), it would then be possible to get
 951   * all of the attachments for a post. Attachments have since changed since
 952   * version 2.5, so this is most likely inaccurate, but serves generally as an
 953   * example of what is possible.
 954   *
 955   * The arguments listed as defaults are for this function and also of the
 956   * get_posts() function. The arguments are combined with the get_children defaults
 957   * and are then passed to the get_posts() function, which accepts additional arguments.
 958   * You can replace the defaults in this function, listed below and the additional
 959   * arguments listed in the get_posts() function.
 960   *
 961   * The 'post_parent' is the most important argument and important attention
 962   * needs to be paid to the $args parameter. If you pass either an object or an
 963   * integer (number), then just the 'post_parent' is grabbed and everything else
 964   * is lost. If you don't specify any arguments, then it is assumed that you are
 965   * in The Loop and the post parent will be grabbed for from the current post.
 966   *
 967   * The 'post_parent' argument is the ID to get the children. The 'numberposts'
 968   * is the amount of posts to retrieve that has a default of '-1', which is
 969   * used to get all of the posts. Giving a number higher than 0 will only
 970   * retrieve that amount of posts.
 971   *
 972   * The 'post_type' and 'post_status' arguments can be used to choose what
 973   * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
 974   * post types are 'post', 'pages', and 'attachments'. The 'post_status'
 975   * argument will accept any post status within the write administration panels.
 976   *
 977   * @since 2.0.0
 978   *
 979   * @see get_posts()
 980   * @todo Check validity of description.
 981   *
 982   * @global WP_Post $post Global post object.
 983   *
 984   * @param mixed  $args   Optional. User defined arguments for replacing the defaults. Default empty.
 985   * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 986   *                       correspond to a WP_Post object, an associative array, or a numeric array,
 987   *                       respectively. Default OBJECT.
 988   * @return WP_Post[]|array[]|int[] Array of post objects, arrays, or IDs, depending on `$output`.
 989   *
 990   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
 991   * @phpstan-return (
 992   *     $args is array{ fields: 'ids', ... } ? int[] : (
 993   *         $output is 'ARRAY_A' ? array<int, non-empty-array<string, mixed>> : (
 994   *             $output is 'ARRAY_N' ? array<int, non-empty-array<int, mixed>> : WP_Post[]
 995   *         )
 996   *     )
 997   * )
 998   */
 999  function get_children( $args = '', $output = OBJECT ) {
1000      $kids = array();
1001      if ( empty( $args ) ) {
1002          if ( isset( $GLOBALS['post'] ) ) {
1003              $args = array( 'post_parent' => (int) $GLOBALS['post']->post_parent );
1004          } else {
1005              return $kids;
1006          }
1007      } elseif ( is_object( $args ) ) {
1008          $args = array( 'post_parent' => (int) $args->post_parent );
1009      } elseif ( is_numeric( $args ) ) {
1010          $args = array( 'post_parent' => (int) $args );
1011      }
1012  
1013      $defaults = array(
1014          'numberposts' => -1,
1015          'post_type'   => 'any',
1016          'post_status' => 'any',
1017          'post_parent' => 0,
1018      );
1019  
1020      $parsed_args = wp_parse_args( $args, $defaults );
1021  
1022      $children = get_posts( $parsed_args );
1023  
1024      if ( ! $children ) {
1025          return $kids;
1026      }
1027  
1028      if ( ! empty( $parsed_args['fields'] ) ) {
1029          return $children;
1030      }
1031  
1032      update_post_cache( $children );
1033  
1034      foreach ( $children as $key => $child ) {
1035          $kids[ $child->ID ] = $children[ $key ];
1036      }
1037  
1038      if ( OBJECT === $output ) {
1039          return $kids;
1040      } elseif ( ARRAY_A === $output ) {
1041          $weeuns = array();
1042          foreach ( (array) $kids as $kid ) {
1043              /** @var non-empty-array<string, mixed> $vars */
1044              $vars               = get_object_vars( $kids[ $kid->ID ] );
1045              $weeuns[ $kid->ID ] = $vars;
1046          }
1047          return $weeuns;
1048      } elseif ( ARRAY_N === $output ) {
1049          $babes = array();
1050          foreach ( (array) $kids as $kid ) {
1051              /** @var non-empty-array<string, mixed> $vars */
1052              $vars              = get_object_vars( $kids[ $kid->ID ] );
1053              $babes[ $kid->ID ] = array_values( $vars );
1054          }
1055          return $babes;
1056      } else {
1057          return $kids;
1058      }
1059  }
1060  
1061  /**
1062   * Gets extended entry info (<!--more-->).
1063   *
1064   * There should not be any space after the second dash and before the word
1065   * 'more'. There can be text or space(s) after the word 'more', but won't be
1066   * referenced.
1067   *
1068   * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
1069   * the `<!--more-->`. The 'extended' key has the content after the
1070   * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
1071   *
1072   * @since 1.0.0
1073   *
1074   * @param string $post Post content.
1075   * @return string[] {
1076   *     Extended entry info.
1077   *
1078   *     @type string $main      Content before the more tag.
1079   *     @type string $extended  Content after the more tag.
1080   *     @type string $more_text Custom read more text, or empty string.
1081   * }
1082   */
1083  function get_extended( $post ) {
1084      // Match the new style more links.
1085      if ( preg_match( '/<!--more(.*?)?-->/', $post, $matches ) ) {
1086          list($main, $extended) = explode( $matches[0], $post, 2 );
1087          $more_text             = $matches[1];
1088      } else {
1089          $main      = $post;
1090          $extended  = '';
1091          $more_text = '';
1092      }
1093  
1094      // Leading and trailing whitespace.
1095      $main      = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $main );
1096      $extended  = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $extended );
1097      $more_text = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $more_text );
1098  
1099      return array(
1100          'main'      => $main,
1101          'extended'  => $extended,
1102          'more_text' => $more_text,
1103      );
1104  }
1105  
1106  /**
1107   * Retrieves post data given a post ID or post object.
1108   *
1109   * See sanitize_post() for optional $filter values. Also, the parameter
1110   * `$post`, must be given as a variable, since it is passed by reference.
1111   *
1112   * @since 1.5.1
1113   *
1114   * @global WP_Post $post Global post object.
1115   *
1116   * @param int|object|null  $post   Optional. Post ID or post object. `null`, `false`, `0` and other PHP falsey values
1117   *                                 return the current global post inside the loop. A numerically valid post ID that
1118   *                                 points to a non-existent post returns `null`. Defaults to global $post.
1119   * @param string           $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
1120   *                                 correspond to a WP_Post object, an associative array, or a numeric array,
1121   *                                 respectively. Default OBJECT.
1122   * @param string           $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
1123   *                                 or 'display'. Default 'raw'.
1124   * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
1125   *                            When $output is OBJECT, a `WP_Post` instance is returned.
1126   *
1127   * @phpstan-param int|numeric-string|WP_Post|null $post
1128   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
1129   * @phpstan-param 'raw'|'edit'|'db'|'display' $filter
1130   * @phpstan-return (
1131   *     $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : (
1132   *         $output is 'ARRAY_N' ? non-empty-array<int, mixed>|null : (
1133   *             WP_Post|null
1134   *         )
1135   *     )
1136   * )
1137   */
1138  function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
1139      if ( empty( $post ) && isset( $GLOBALS['post'] ) ) {
1140          $post = $GLOBALS['post'];
1141      }
1142  
1143      if ( $post instanceof WP_Post ) {
1144          $_post = $post;
1145      } elseif ( is_object( $post ) ) {
1146          /** @var stdClass $post */
1147          if ( empty( $post->filter ) ) {
1148              $_post = sanitize_post( $post, 'raw' );
1149              $_post = new WP_Post( $_post );
1150          } elseif ( 'raw' === $post->filter ) {
1151              $_post = new WP_Post( $post );
1152          } elseif ( isset( $post->ID ) ) {
1153              $_post = WP_Post::get_instance( (int) $post->ID );
1154          } else {
1155              $_post = null;
1156          }
1157      } elseif ( is_numeric( $post ) ) {
1158          $_post = WP_Post::get_instance( (int) $post );
1159      } else {
1160          $_post = null;
1161      }
1162  
1163      if ( ! $_post ) {
1164          return null;
1165      }
1166  
1167      $_post = $_post->filter( $filter );
1168      if ( ! $_post ) {
1169          return null;
1170      }
1171  
1172      if ( ARRAY_A === $output ) {
1173          return $_post->to_array();
1174      } elseif ( ARRAY_N === $output ) {
1175          return array_values( $_post->to_array() );
1176      }
1177  
1178      return $_post;
1179  }
1180  
1181  /**
1182   * Retrieves the IDs of the ancestors of a post.
1183   *
1184   * @since 2.5.0
1185   *
1186   * @param int|WP_Post $post Post ID or post object.
1187   * @return int[] Array of ancestor IDs or empty array if there are none.
1188   * @phpstan-return list<non-negative-int>
1189   */
1190  function get_post_ancestors( $post ) {
1191      $post = get_post( $post );
1192  
1193      if ( ! $post || empty( $post->post_parent ) || $post->post_parent === $post->ID ) {
1194          return array();
1195      }
1196  
1197      $ancestors = array();
1198  
1199      $id          = $post->post_parent;
1200      $ancestors[] = $id;
1201  
1202      while ( $ancestor = get_post( $id ) ) {
1203          // Loop detection: If the ancestor has been seen before, break.
1204          if ( empty( $ancestor->post_parent ) || $ancestor->post_parent === $post->ID
1205              || in_array( $ancestor->post_parent, $ancestors, true )
1206          ) {
1207              break;
1208          }
1209  
1210          $id          = $ancestor->post_parent;
1211          $ancestors[] = $id;
1212      }
1213  
1214      return $ancestors;
1215  }
1216  
1217  /**
1218   * Retrieves data from a post field based on Post ID.
1219   *
1220   * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
1221   * etc and based off of the post object property or key names.
1222   *
1223   * The context values are based off of the taxonomy filter functions and
1224   * supported values are found within those functions.
1225   *
1226   * @since 2.3.0
1227   * @since 4.5.0 The `$post` parameter was made optional.
1228   *
1229   * @see sanitize_post_field()
1230   *
1231   * @param string      $field   Post field name.
1232   * @param int|WP_Post $post    Optional. Post ID or post object. Defaults to global $post.
1233   * @param string      $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
1234   *                             or 'display'. Default 'display'.
1235   * @return int|string|int[] The value of the post field on success, empty string on failure.
1236   *
1237   * @phpstan-param 'raw'|'edit'|'db'|'display' $context
1238   * @phpstan-return (
1239   *     $field is 'ID'|'post_parent'|'menu_order' ? int|'' : (
1240   *         $field is 'ancestors' ? non-negative-int[]|'' : string
1241   *     )
1242   * )
1243   */
1244  function get_post_field( $field, $post = null, $context = 'display' ) {
1245      $post = get_post( $post );
1246  
1247      if ( ! $post ) {
1248          return '';
1249      }
1250  
1251      if ( ! isset( $post->$field ) ) {
1252          return '';
1253      }
1254  
1255      return sanitize_post_field( $field, $post->$field, $post->ID, $context );
1256  }
1257  
1258  /**
1259   * Retrieves the mime type of an attachment based on the ID.
1260   *
1261   * This function can be used with any post type, but it makes more sense with
1262   * attachments.
1263   *
1264   * @since 2.0.0
1265   *
1266   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
1267   * @return string|false The mime type on success, false on failure.
1268   */
1269  function get_post_mime_type( $post = null ) {
1270      $post = get_post( $post );
1271  
1272      if ( is_object( $post ) ) {
1273          return $post->post_mime_type;
1274      }
1275  
1276      return false;
1277  }
1278  
1279  /**
1280   * Retrieves the post status based on the post ID.
1281   *
1282   * If the post ID is of an attachment, then the parent post status will be given
1283   * instead.
1284   *
1285   * @since 2.0.0
1286   *
1287   * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
1288   * @return string|false Post status on success, false on failure.
1289   */
1290  function get_post_status( $post = null ) {
1291      // Normalize the post object if necessary, skip normalization if called from get_sample_permalink().
1292      if ( ! $post instanceof WP_Post || ! isset( $post->filter ) || 'sample' !== $post->filter ) {
1293          $post = get_post( $post );
1294      }
1295  
1296      if ( ! is_object( $post ) ) {
1297          return false;
1298      }
1299  
1300      $post_status = $post->post_status;
1301  
1302      if (
1303          'attachment' === $post->post_type &&
1304          'inherit' === $post_status
1305      ) {
1306          if (
1307              0 === $post->post_parent ||
1308              ! get_post( $post->post_parent ) ||
1309              $post->ID === $post->post_parent
1310          ) {
1311              // Unattached attachments with inherit status are assumed to be published.
1312              $post_status = 'publish';
1313          } elseif ( 'trash' === get_post_status( $post->post_parent ) ) {
1314              // Get parent status prior to trashing.
1315              $post_status = get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
1316  
1317              if ( ! $post_status ) {
1318                  // Assume publish as above.
1319                  $post_status = 'publish';
1320              }
1321          } else {
1322              $post_status = get_post_status( $post->post_parent );
1323          }
1324      } elseif (
1325          'attachment' === $post->post_type &&
1326          ! in_array( $post_status, array( 'private', 'trash', 'auto-draft' ), true )
1327      ) {
1328          /*
1329           * Ensure uninherited attachments have a permitted status either 'private', 'trash', 'auto-draft'.
1330           * This is to match the logic in wp_insert_post().
1331           *
1332           * Note: 'inherit' is excluded from this check as it is resolved to the parent post's
1333           * status in the logic block above.
1334           */
1335          $post_status = 'publish';
1336      }
1337  
1338      /**
1339       * Filters the post status.
1340       *
1341       * @since 4.4.0
1342       * @since 5.7.0 The attachment post type is now passed through this filter.
1343       *
1344       * @param string  $post_status The post status.
1345       * @param WP_Post $post        The post object.
1346       */
1347      return apply_filters( 'get_post_status', $post_status, $post );
1348  }
1349  
1350  /**
1351   * Retrieves all of the WordPress supported post statuses.
1352   *
1353   * Posts have a limited set of valid status values, this provides the
1354   * post_status values and descriptions.
1355   *
1356   * @since 2.5.0
1357   *
1358   * @return string[] Array of post status labels keyed by their status.
1359   */
1360  function get_post_statuses() {
1361      $status = array(
1362          'draft'   => __( 'Draft' ),
1363          'pending' => __( 'Pending Review' ),
1364          'private' => __( 'Private' ),
1365          'publish' => __( 'Published' ),
1366      );
1367  
1368      return $status;
1369  }
1370  
1371  /**
1372   * Retrieves all of the WordPress support page statuses.
1373   *
1374   * Pages have a limited set of valid status values, this provides the
1375   * post_status values and descriptions.
1376   *
1377   * @since 2.5.0
1378   *
1379   * @return string[] Array of page status labels keyed by their status.
1380   */
1381  function get_page_statuses() {
1382      $status = array(
1383          'draft'   => __( 'Draft' ),
1384          'private' => __( 'Private' ),
1385          'publish' => __( 'Published' ),
1386      );
1387  
1388      return $status;
1389  }
1390  
1391  /**
1392   * Returns statuses for privacy requests.
1393   *
1394   * @since 4.9.6
1395   * @access private
1396   *
1397   * @return string[] Array of privacy request status labels keyed by their status.
1398   */
1399  function _wp_privacy_statuses() {
1400      return array(
1401          'request-pending'   => _x( 'Pending', 'request status' ),      // Pending confirmation from user.
1402          'request-confirmed' => _x( 'Confirmed', 'request status' ),    // User has confirmed the action.
1403          'request-failed'    => _x( 'Failed', 'request status' ),       // User failed to confirm the action.
1404          'request-completed' => _x( 'Completed', 'request status' ),    // Admin has handled the request.
1405      );
1406  }
1407  
1408  /**
1409   * Registers a post status. Do not use before init.
1410   *
1411   * A simple function for creating or modifying a post status based on the
1412   * parameters given. The function will accept an array (second optional
1413   * parameter), along with a string for the post status name.
1414   *
1415   * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
1416   *
1417   * @since 3.0.0
1418   *
1419   * @global stdClass[] $wp_post_statuses Inserts new post status object into the list
1420   *
1421   * @param string       $post_status Name of the post status.
1422   * @param array|string $args {
1423   *     Optional. Array or string of post status arguments.
1424   *
1425   *     @type bool|string $label                     A descriptive name for the post status marked
1426   *                                                  for translation. Defaults to value of $post_status.
1427   *     @type array|false $label_count               Nooped plural text from _n_noop() to provide the singular
1428   *                                                  and plural forms of the label for counts. Default false
1429   *                                                  which means the `$label` argument will be used for both
1430   *                                                  the singular and plural forms of this label.
1431   *     @type bool        $exclude_from_search       Whether to exclude posts with this post status
1432   *                                                  from search results. Default is value of $internal.
1433   *     @type bool        $_builtin                  Whether the status is built-in. Core-use only.
1434   *                                                  Default false.
1435   *     @type bool        $public                    Whether posts of this status should be shown
1436   *                                                  in the front end of the site. Default false.
1437   *     @type bool        $internal                  Whether the status is for internal use only.
1438   *                                                  Default false.
1439   *     @type bool        $protected                 Whether posts with this status should be protected.
1440   *                                                  Default false.
1441   *     @type bool        $private                   Whether posts with this status should be private.
1442   *                                                  Default false.
1443   *     @type bool        $publicly_queryable        Whether posts with this status should be publicly-
1444   *                                                  queryable. Default is value of $public.
1445   *     @type bool        $show_in_admin_all_list    Whether to include posts in the edit listing for
1446   *                                                  their post type. Default is the opposite value
1447   *                                                  of $internal.
1448   *     @type bool        $show_in_admin_status_list Show in the list of statuses with post counts at
1449   *                                                  the top of the edit listings,
1450   *                                                  e.g. All (12) | Published (9) | My Custom Status (2)
1451   *                                                  Default is the opposite value of $internal.
1452   *     @type bool        $date_floating             Whether the post has a floating creation date.
1453   *                                                  Default to false.
1454   * }
1455   * @return object
1456   *
1457   * @phpstan-param lowercase-string&non-falsy-string $post_status
1458   */
1459  function register_post_status( $post_status, $args = array() ) {
1460      global $wp_post_statuses;
1461  
1462      if ( ! is_array( $wp_post_statuses ) ) {
1463          $wp_post_statuses = array();
1464      }
1465  
1466      // Args prefixed with an underscore are reserved for internal use.
1467      $defaults = array(
1468          'label'                     => false,
1469          'label_count'               => false,
1470          'exclude_from_search'       => null,
1471          '_builtin'                  => false,
1472          'public'                    => null,
1473          'internal'                  => null,
1474          'protected'                 => null,
1475          'private'                   => null,
1476          'publicly_queryable'        => null,
1477          'show_in_admin_status_list' => null,
1478          'show_in_admin_all_list'    => null,
1479          'date_floating'             => null,
1480      );
1481      $args     = wp_parse_args( $args, $defaults );
1482      $args     = (object) $args;
1483  
1484      $post_status = sanitize_key( $post_status );
1485      $args->name  = $post_status;
1486  
1487      // Set various defaults.
1488      if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private ) {
1489          $args->internal = true;
1490      }
1491  
1492      $args->public                    ??= false;
1493      $args->private                   ??= false;
1494      $args->protected                 ??= false;
1495      $args->internal                  ??= false;
1496      $args->publicly_queryable        ??= $args->public;
1497      $args->exclude_from_search       ??= $args->internal;
1498      $args->show_in_admin_all_list    ??= ! $args->internal;
1499      $args->show_in_admin_status_list ??= ! $args->internal;
1500      $args->date_floating             ??= false;
1501  
1502      if ( false === $args->label ) {
1503          $args->label = $post_status;
1504      }
1505  
1506      if ( false === $args->label_count ) {
1507          // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralSingular,WordPress.WP.I18n.NonSingularStringLiteralPlural
1508          $args->label_count = _n_noop( $args->label, $args->label ); // @phpstan-ignore argument.type, argument.type (The label is a runtime value, so there is nothing to extract for translation.)
1509      }
1510  
1511      $wp_post_statuses[ $post_status ] = $args;
1512  
1513      return $args;
1514  }
1515  
1516  /**
1517   * Retrieves a post status object by name.
1518   *
1519   * @since 3.0.0
1520   *
1521   * @see register_post_status()
1522   *
1523   * @global stdClass[] $wp_post_statuses List of post statuses.
1524   *
1525   * @param string $post_status The name of a registered post status.
1526   * @return stdClass|null A post status object.
1527   */
1528  function get_post_status_object( $post_status ) {
1529      global $wp_post_statuses;
1530  
1531      if ( ! is_string( $post_status ) || empty( $wp_post_statuses[ $post_status ] ) ) {
1532          return null;
1533      }
1534  
1535      return $wp_post_statuses[ $post_status ];
1536  }
1537  
1538  /**
1539   * Gets a list of post statuses.
1540   *
1541   * @since 3.0.0
1542   *
1543   * @see register_post_status()
1544   *
1545   * @global stdClass[] $wp_post_statuses List of post statuses.
1546   *
1547   * @param array|string $args     Optional. Array or string of post status arguments to compare against
1548   *                               properties of the global `$wp_post_statuses objects`. Default empty array.
1549   * @param string       $output   Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
1550   * @param string       $operator Optional. The logical operation to perform. 'or' means only one element
1551   *                               from the array needs to match; 'and' means all elements must match.
1552   *                               Default 'and'.
1553   * @return string[]|stdClass[] A list of post status names or objects.
1554   * @phpstan-return ( $output is 'names' ? array<non-falsy-string, non-falsy-string> : array<non-falsy-string, stdClass> )
1555   */
1556  function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
1557      global $wp_post_statuses;
1558  
1559      $field = ( 'names' === $output ) ? 'name' : false;
1560  
1561      return wp_filter_object_list( $wp_post_statuses, $args, $operator, $field );
1562  }
1563  
1564  /**
1565   * Determines whether the post type is hierarchical.
1566   *
1567   * A false return value might also mean that the post type does not exist.
1568   *
1569   * @since 3.0.0
1570   *
1571   * @see get_post_type_object()
1572   *
1573   * @param string $post_type Post type name
1574   * @return bool Whether post type is hierarchical.
1575   */
1576  function is_post_type_hierarchical( $post_type ) {
1577      if ( ! post_type_exists( $post_type ) ) {
1578          return false;
1579      }
1580  
1581      $post_type = get_post_type_object( $post_type );
1582      return $post_type->hierarchical;
1583  }
1584  
1585  /**
1586   * Determines whether a post type is registered.
1587   *
1588   * For more information on this and similar theme functions, check out
1589   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1590   * Conditional Tags} article in the Theme Developer Handbook.
1591   *
1592   * @since 3.0.0
1593   *
1594   * @see get_post_type_object()
1595   *
1596   * @param string $post_type Post type name.
1597   * @return bool Whether post type is registered.
1598   */
1599  function post_type_exists( $post_type ) {
1600      return (bool) get_post_type_object( $post_type );
1601  }
1602  
1603  /**
1604   * Retrieves the post type of the current post or of a given post.
1605   *
1606   * @since 2.1.0
1607   *
1608   * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
1609   * @return string|false          Post type on success, false on failure.
1610   */
1611  function get_post_type( $post = null ) {
1612      $post = get_post( $post );
1613      if ( $post ) {
1614          return $post->post_type;
1615      }
1616  
1617      return false;
1618  }
1619  
1620  /**
1621   * Retrieves a post type object by name.
1622   *
1623   * @since 3.0.0
1624   * @since 4.6.0 Object returned is now an instance of `WP_Post_Type`.
1625   *
1626   * @see register_post_type()
1627   *
1628   * @global array $wp_post_types List of post types.
1629   *
1630   * @param string $post_type The name of a registered post type.
1631   * @return WP_Post_Type|null WP_Post_Type object if it exists, null otherwise.
1632   */
1633  function get_post_type_object( $post_type ) {
1634      global $wp_post_types;
1635  
1636      if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
1637          return null;
1638      }
1639  
1640      return $wp_post_types[ $post_type ];
1641  }
1642  
1643  /**
1644   * Gets a list of all registered post type objects.
1645   *
1646   * @since 2.9.0
1647   *
1648   * @see register_post_type() for accepted arguments.
1649   *
1650   * @global array $wp_post_types List of post types.
1651   *
1652   * @param array|string $args     Optional. An array of key => value arguments to match against
1653   *                               the post type objects. Default empty array.
1654   * @param string       $output   Optional. The type of output to return. Either 'names'
1655   *                               or 'objects'. Default 'names'.
1656   * @param string       $operator Optional. The logical operation to perform. 'or' means only one
1657   *                               element from the array needs to match; 'and' means all elements
1658   *                               must match; 'not' means no elements may match. Default 'and'.
1659   * @return string[]|WP_Post_Type[] An array of post type names or objects.
1660   * @phpstan-return ( $output is 'names' ? string[] : WP_Post_Type[] )
1661   */
1662  function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
1663      global $wp_post_types;
1664  
1665      $field = ( 'names' === $output ) ? 'name' : false;
1666  
1667      return wp_filter_object_list( $wp_post_types, $args, $operator, $field );
1668  }
1669  
1670  /**
1671   * Registers a post type.
1672   *
1673   * Note: Post type registrations should not be hooked before the
1674   * {@see 'init'} action. Also, any taxonomy connections should be
1675   * registered via the `$taxonomies` argument to ensure consistency
1676   * when hooks such as {@see 'parse_query'} or {@see 'pre_get_posts'}
1677   * are used.
1678   *
1679   * Post types can support any number of built-in core features such
1680   * as meta boxes, custom fields, post thumbnails, post statuses,
1681   * comments, and more. See the `$supports` argument for a complete
1682   * list of supported features.
1683   *
1684   * @since 2.9.0
1685   * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
1686   * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing
1687   *              screen and post editing screen.
1688   * @since 4.6.0 Post type object returned is now an instance of `WP_Post_Type`.
1689   * @since 4.7.0 Introduced `show_in_rest`, `rest_base` and `rest_controller_class`
1690   *              arguments to register the post type in REST API.
1691   * @since 5.0.0 The `template` and `template_lock` arguments were added.
1692   * @since 5.3.0 The `supports` argument will now accept an array of arguments for a feature.
1693   * @since 5.9.0 The `rest_namespace` argument was added.
1694   *
1695   * @global array $wp_post_types List of post types.
1696   *
1697   * @param string       $post_type Post type key. Must not exceed 20 characters and may only contain
1698   *                                lowercase alphanumeric characters, dashes, and underscores. See sanitize_key().
1699   * @param array|string $args {
1700   *     Array or string of arguments for registering a post type.
1701   *
1702   *     @type string       $label                           Name of the post type shown in the menu. Usually plural.
1703   *                                                         Default is value of $labels['name'].
1704   *     @type string[]     $labels                          An array of labels for this post type. If not set, post
1705   *                                                         labels are inherited for non-hierarchical types and page
1706   *                                                         labels for hierarchical ones. See get_post_type_labels() for a full
1707   *                                                         list of supported labels.
1708   *     @type string       $description                     A short descriptive summary of what the post type is.
1709   *                                                         Default empty.
1710   *     @type bool         $public                          Whether a post type is intended for use publicly either via
1711   *                                                         the admin interface or by front-end users. While the default
1712   *                                                         settings of $exclude_from_search, $publicly_queryable, $show_ui,
1713   *                                                         and $show_in_nav_menus are inherited from $public, each does not
1714   *                                                         rely on this relationship and controls a very specific intention.
1715   *                                                         Default false.
1716   *     @type bool         $hierarchical                    Whether the post type is hierarchical (e.g. page). Default false.
1717   *     @type bool         $exclude_from_search             Whether to exclude posts with this post type from front end search
1718   *                                                         results. Default is the opposite value of $public.
1719   *     @type bool         $publicly_queryable              Whether queries can be performed on the front end for the post type
1720   *                                                         as part of parse_request(). Endpoints would include:
1721   *                                                          * ?post_type={post_type_key}
1722   *                                                          * ?{post_type_key}={single_post_slug}
1723   *                                                          * ?{post_type_query_var}={single_post_slug}
1724   *                                                         If not set, the default is inherited from $public.
1725   *     @type bool         $show_ui                         Whether to generate and allow a UI for managing this post type in the
1726   *                                                         admin. Default is value of $public.
1727   *     @type bool|string  $show_in_menu                    Where to show the post type in the admin menu. To work, $show_ui
1728   *                                                         must be true. If true, the post type is shown in its own top level
1729   *                                                         menu. If false, no menu is shown. If a string of an existing top
1730   *                                                         level menu ('tools.php' or 'edit.php?post_type=page', for example), the
1731   *                                                         post type will be placed as a sub-menu of that.
1732   *                                                         Default is value of $show_ui.
1733   *     @type bool         $show_in_nav_menus               Makes this post type available for selection in navigation menus.
1734   *                                                         Default is value of $public.
1735   *     @type bool         $show_in_admin_bar               Makes this post type available via the admin bar. Default is value
1736   *                                                         of $show_in_menu.
1737   *     @type bool         $show_in_rest                    Whether to include the post type in the REST API. Set this to true
1738   *                                                         for the post type to be available in the block editor.
1739   *     @type string       $rest_base                       To change the base URL of REST API route. Default is $post_type.
1740   *     @type string       $rest_namespace                  To change the namespace URL of REST API route. Default is wp/v2.
1741   *     @type string       $rest_controller_class           REST API controller class name. Default is 'WP_REST_Posts_Controller'.
1742   *     @type string|bool  $autosave_rest_controller_class  REST API controller class name. Default is 'WP_REST_Autosaves_Controller'.
1743   *     @type string|bool  $revisions_rest_controller_class REST API controller class name. Default is 'WP_REST_Revisions_Controller'.
1744   *     @type bool         $late_route_registration         A flag to direct the REST API controllers for autosave / revisions
1745   *                                                         should be registered before/after the post type controller.
1746   *     @type int          $menu_position                   The position in the menu order the post type should appear. To work,
1747   *                                                         $show_in_menu must be true. Default null (at the bottom).
1748   *     @type string       $menu_icon                       The URL to the icon to be used for this menu. Pass a base64-encoded
1749   *                                                         SVG using a data URI, which will be colored to match the color scheme
1750   *                                                         -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
1751   *                                                         of a Dashicons helper class to use a font icon, e.g.
1752   *                                                        'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
1753   *                                                         so an icon can be added via CSS. Defaults to use the posts icon.
1754   *     @type string|array $capability_type                 The string to use to build the read, edit, and delete capabilities.
1755   *                                                         May be passed as an array to allow for alternative plurals when using
1756   *                                                         this argument as a base to construct the capabilities, e.g.
1757   *                                                         array('story', 'stories'). Default 'post'.
1758   *     @type string[]     $capabilities                    Array of capabilities for this post type. $capability_type is used
1759   *                                                         as a base to construct capabilities by default.
1760   *                                                         See get_post_type_capabilities().
1761   *     @type bool         $map_meta_cap                    Whether to use the internal default meta capability handling.
1762   *                                                         Default false.
1763   *     @type array|false  $supports                        Core feature(s) the post type supports. Serves as an alias for calling
1764   *                                                         add_post_type_support() directly. Core features include 'title',
1765   *                                                         'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt',
1766   *                                                         'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'.
1767   *                                                         Additionally, the 'revisions' feature dictates whether the post type
1768   *                                                         will store revisions, the 'autosave' feature dictates whether the post type
1769   *                                                         will be autosaved, and the 'comments' feature dictates whether the
1770   *                                                         comments count will show on the edit screen. For backward compatibility reasons,
1771   *                                                         adding 'editor' support implies 'autosave' support too. A feature can also be
1772   *                                                         specified as an array of arguments to provide additional information
1773   *                                                         about supporting that feature.
1774   *                                                         Example: `array( 'my_feature', array( 'field' => 'value' ) )`.
1775   *                                                         If false, no features will be added.
1776   *                                                         Default is an array containing 'title' and 'editor'.
1777   *     @type callable     $register_meta_box_cb            Provide a callback function that sets up the meta boxes for the
1778   *                                                         edit form. Do remove_meta_box() and add_meta_box() calls in the
1779   *                                                         callback. Default null.
1780   *     @type string[]     $taxonomies                      An array of taxonomy identifiers that will be registered for the
1781   *                                                         post type. Taxonomies can be registered later with register_taxonomy()
1782   *                                                         or register_taxonomy_for_object_type().
1783   *                                                         Default empty array.
1784   *     @type bool|string  $has_archive                     Whether there should be post type archives, or if a string, the
1785   *                                                         archive slug to use. Will generate the proper rewrite rules if
1786   *                                                         $rewrite is enabled. Default false.
1787   *     @type bool|array   $rewrite                         {
1788   *         Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
1789   *         Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
1790   *         passed with any of these keys:
1791   *
1792   *         @type string $slug       Customize the permastruct slug. Defaults to $post_type key.
1793   *         @type bool   $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
1794   *                                  Default true.
1795   *         @type bool   $feeds      Whether the feed permastruct should be built for this post type.
1796   *                                  Default is value of $has_archive.
1797   *         @type bool   $pages      Whether the permastruct should provide for pagination. Default true.
1798   *         @type int    $ep_mask    Endpoint mask to assign. If not specified and permalink_epmask is set,
1799   *                                  inherits from $permalink_epmask. If not specified and permalink_epmask
1800   *                                  is not set, defaults to EP_PERMALINK.
1801   *     }
1802   *     @type string|bool  $query_var                      Sets the query_var key for this post type. Defaults to $post_type
1803   *                                                        key. If false, a post type cannot be loaded at
1804   *                                                        ?{query_var}={post_slug}. If specified as a string, the query
1805   *                                                        ?{query_var_string}={post_slug} will be valid.
1806   *     @type bool         $can_export                     Whether to allow this post type to be exported. Default true.
1807   *     @type bool         $delete_with_user               Whether to delete posts of this type when deleting a user.
1808   *                                                          * If true, posts of this type belonging to the user will be moved
1809   *                                                            to Trash when the user is deleted.
1810   *                                                          * If false, posts of this type belonging to the user will *not*
1811   *                                                            be trashed or deleted.
1812   *                                                          * If not set (the default), posts are trashed if post type supports
1813   *                                                            the 'author' feature. Otherwise posts are not trashed or deleted.
1814   *                                                        Default null.
1815   *     @type array        $template                       Array of blocks to use as the default initial state for an editor
1816   *                                                        session. Each item should be an array containing block name and
1817   *                                                        optional attributes. Default empty array.
1818   *     @type string|false $template_lock                  Whether the block template should be locked if $template is set.
1819   *                                                          * If set to 'all', the user is unable to insert new blocks,
1820   *                                                            move existing blocks and delete blocks.
1821   *                                                          * If set to 'insert', the user is able to move existing blocks
1822   *                                                            but is unable to insert new blocks and delete blocks.
1823   *                                                          * If set to 'contentOnly', the user is only able to edit the content
1824   *                                                            of existing blocks.
1825   *                                                        Default false.
1826   *     @type bool         $_builtin                       FOR INTERNAL USE ONLY! True if this post type is a native or
1827   *                                                        "built-in" post_type. Default false.
1828   *     @type string       $_edit_link                     FOR INTERNAL USE ONLY! URL segment to use for edit link of
1829   *                                                        this post type. Default 'post.php?post=%d'.
1830   * }
1831   * @return WP_Post_Type|WP_Error The registered post type object on success,
1832   *                               WP_Error object on failure.
1833   *
1834   * @phpstan-param lowercase-string&non-falsy-string $post_type
1835   */
1836  function register_post_type( $post_type, $args = array() ) {
1837      global $wp_post_types;
1838  
1839      if ( ! is_array( $wp_post_types ) ) {
1840          $wp_post_types = array();
1841      }
1842  
1843      // Sanitize post type name.
1844      $post_type = sanitize_key( $post_type );
1845  
1846      if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1847          _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2.0' );
1848          return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1849      }
1850  
1851      $post_type_object = new WP_Post_Type( $post_type, $args );
1852      $post_type_object->add_supports();
1853      $post_type_object->add_rewrite_rules();
1854      $post_type_object->register_meta_boxes();
1855  
1856      $wp_post_types[ $post_type ] = $post_type_object;
1857  
1858      $post_type_object->add_hooks();
1859      $post_type_object->register_taxonomies();
1860  
1861      /**
1862       * Fires after a post type is registered.
1863       *
1864       * @since 3.3.0
1865       * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1866       *
1867       * @param string       $post_type        Post type.
1868       * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1869       */
1870      do_action( 'registered_post_type', $post_type, $post_type_object );
1871  
1872      /**
1873       * Fires after a specific post type is registered.
1874       *
1875       * The dynamic portion of the filter name, `$post_type`, refers to the post type key.
1876       *
1877       * Possible hook names include:
1878       *
1879       *  - `registered_post_type_post`
1880       *  - `registered_post_type_page`
1881       *
1882       * @since 6.0.0
1883       *
1884       * @param string       $post_type        Post type.
1885       * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1886       */
1887      do_action( "registered_post_type_{$post_type}", $post_type, $post_type_object );
1888  
1889      return $post_type_object;
1890  }
1891  
1892  /**
1893   * Unregisters a post type.
1894   *
1895   * Cannot be used to unregister built-in post types.
1896   *
1897   * @since 4.5.0
1898   *
1899   * @global array<string, string>       $post_type_meta_caps Used to store meta capabilities.
1900   * @global array<string, WP_Post_Type> $wp_post_types       List of post types.
1901   *
1902   * @param string $post_type Post type to unregister.
1903   * @return true|WP_Error True on success, WP_Error on failure or if the post type doesn't exist.
1904   */
1905  function unregister_post_type( $post_type ) {
1906      global $post_type_meta_caps, $wp_post_types;
1907  
1908      $post_type_object = get_post_type_object( $post_type );
1909      if ( ! $post_type_object ) {
1910          return new WP_Error( 'invalid_post_type', __( 'Invalid post type.' ) );
1911      }
1912  
1913      // Do not allow unregistering internal post types.
1914      if ( $post_type_object->_builtin ) {
1915          return new WP_Error( 'invalid_post_type', __( 'Unregistering a built-in post type is not allowed' ) );
1916      }
1917  
1918      $post_type_object->remove_supports();
1919      $post_type_object->remove_rewrite_rules();
1920      $post_type_object->unregister_meta_boxes();
1921      $post_type_object->remove_hooks();
1922      $post_type_object->unregister_taxonomies();
1923  
1924      unset( $wp_post_types[ $post_type ] );
1925  
1926      /*
1927       * Rebuild the meta capabilities of the post types that remain.
1928       *
1929       * They are keyed by the custom capability name, so a single entry may be owed to any
1930       * number of registered post types. Removing the entries for this post type alone could
1931       * therefore remove entries that the others still depend on.
1932       */
1933      $post_type_meta_caps = array();
1934      foreach ( $wp_post_types as $registered_post_type ) {
1935          if ( $registered_post_type->map_meta_cap ) {
1936              _post_type_meta_capabilities( get_object_vars( $registered_post_type->cap ) );
1937          }
1938      }
1939  
1940      /**
1941       * Fires after a post type was unregistered.
1942       *
1943       * @since 4.5.0
1944       *
1945       * @param string $post_type Post type key.
1946       */
1947      do_action( 'unregistered_post_type', $post_type );
1948  
1949      return true;
1950  }
1951  
1952  /**
1953   * Builds an object with all post type capabilities out of a post type object
1954   *
1955   * Post type capabilities use the 'capability_type' argument as a base, if the
1956   * capability is not set in the 'capabilities' argument array or if the
1957   * 'capabilities' argument is not supplied.
1958   *
1959   * The capability_type argument can optionally be registered as an array, with
1960   * the first value being singular and the second plural, e.g. array('story, 'stories')
1961   * Otherwise, an 's' will be added to the value for the plural form. After
1962   * registration, capability_type will always be a string of the singular value.
1963   *
1964   * By default, the following keys are accepted as part of the capabilities array:
1965   *
1966   * - edit_post, read_post, and delete_post are meta capabilities, which are then
1967   *   generally mapped to corresponding primitive capabilities depending on the
1968   *   context, which would be the post being edited/read/deleted and the user or
1969   *   role being checked. Thus these capabilities would generally not be granted
1970   *   directly to users or roles.
1971   *
1972   * - edit_posts - Controls whether objects of this post type can be edited.
1973   * - edit_others_posts - Controls whether objects of this type owned by other users
1974   *   can be edited. If the post type does not support an author, then this will
1975   *   behave like edit_posts.
1976   * - delete_posts - Controls whether objects of this post type can be deleted.
1977   * - publish_posts - Controls publishing objects of this post type.
1978   * - read_private_posts - Controls whether private objects can be read.
1979   * - create_posts - Controls whether objects of this post type can be created.
1980   *
1981   * These primitive capabilities are checked in core in various locations.
1982   * There are also six other primitive capabilities which are not referenced
1983   * directly in core, except in map_meta_cap(), which takes the three aforementioned
1984   * meta capabilities and translates them into one or more primitive capabilities
1985   * that must then be checked against the user or role, depending on the context.
1986   *
1987   * - read - Controls whether objects of this post type can be read.
1988   * - delete_private_posts - Controls whether private objects can be deleted.
1989   * - delete_published_posts - Controls whether published objects can be deleted.
1990   * - delete_others_posts - Controls whether objects owned by other users can be
1991   *   can be deleted. If the post type does not support an author, then this will
1992   *   behave like delete_posts.
1993   * - edit_private_posts - Controls whether private objects can be edited.
1994   * - edit_published_posts - Controls whether published objects can be edited.
1995   *
1996   * These additional capabilities are only used in map_meta_cap(). Thus, they are
1997   * only assigned by default if the post type is registered with the 'map_meta_cap'
1998   * argument set to true (default is false).
1999   *
2000   * @since 3.0.0
2001   * @since 5.4.0 'delete_posts' is included in default capabilities.
2002   *
2003   * @see register_post_type()
2004   * @see map_meta_cap()
2005   *
2006   * @param object $args Post type registration arguments.
2007   * @return stdClass {
2008   *     Object with all the capabilities as member variables.
2009   *
2010   *     @type string $edit_post              Capability to edit a post.
2011   *     @type string $read_post              Capability to read a post.
2012   *     @type string $delete_post            Capability to delete a post.
2013   *     @type string $edit_posts             Capability to edit posts.
2014   *     @type string $edit_others_posts      Capability to edit others' posts.
2015   *     @type string $delete_posts           Capability to delete posts.
2016   *     @type string $publish_posts          Capability to publish posts.
2017   *     @type string $read_private_posts     Capability to read private posts.
2018   *     @type string $create_posts           Capability to create posts.
2019   *     @type string $read                   Optional. Capability to read a post.
2020   *     @type string $delete_private_posts   Optional. Capability to delete private posts.
2021   *     @type string $delete_published_posts Optional. Capability to delete published posts.
2022   *     @type string $delete_others_posts    Optional. Capability to delete others' posts.
2023   *     @type string $edit_private_posts     Optional. Capability to edit private posts.
2024   *     @type string $edit_published_posts   Optional. Capability to edit published posts.
2025   * }
2026   */
2027  function get_post_type_capabilities( $args ) {
2028      if ( ! is_array( $args->capability_type ) ) {
2029          $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
2030      }
2031  
2032      // Singular base for meta capabilities, plural base for primitive capabilities.
2033      list( $singular_base, $plural_base ) = $args->capability_type;
2034  
2035      $default_capabilities = array(
2036          // Meta capabilities.
2037          'edit_post'          => 'edit_' . $singular_base,
2038          'read_post'          => 'read_' . $singular_base,
2039          'delete_post'        => 'delete_' . $singular_base,
2040          // Primitive capabilities used outside of map_meta_cap():
2041          'edit_posts'         => 'edit_' . $plural_base,
2042          'edit_others_posts'  => 'edit_others_' . $plural_base,
2043          'delete_posts'       => 'delete_' . $plural_base,
2044          'publish_posts'      => 'publish_' . $plural_base,
2045          'read_private_posts' => 'read_private_' . $plural_base,
2046      );
2047  
2048      // Primitive capabilities used within map_meta_cap():
2049      if ( $args->map_meta_cap ) {
2050          $default_capabilities_for_mapping = array(
2051              'read'                   => 'read',
2052              'delete_private_posts'   => 'delete_private_' . $plural_base,
2053              'delete_published_posts' => 'delete_published_' . $plural_base,
2054              'delete_others_posts'    => 'delete_others_' . $plural_base,
2055              'edit_private_posts'     => 'edit_private_' . $plural_base,
2056              'edit_published_posts'   => 'edit_published_' . $plural_base,
2057          );
2058          $default_capabilities             = array_merge( $default_capabilities, $default_capabilities_for_mapping );
2059      }
2060  
2061      $capabilities = array_merge( $default_capabilities, $args->capabilities );
2062  
2063      // Post creation capability simply maps to edit_posts by default:
2064      if ( ! isset( $capabilities['create_posts'] ) ) {
2065          $capabilities['create_posts'] = $capabilities['edit_posts'];
2066      }
2067  
2068      // Remember meta capabilities for future reference.
2069      if ( $args->map_meta_cap ) {
2070          _post_type_meta_capabilities( $capabilities );
2071      }
2072  
2073      return (object) $capabilities;
2074  }
2075  
2076  /**
2077   * Stores a list of post type meta caps for {@see map_meta_cap()}.
2078   *
2079   * @since 3.1.0
2080   * @since 4.5.0 The list moved to the `$post_type_meta_caps` global and the function
2081   *              no longer returns it when called without arguments.
2082   * @since 7.2.0 The `$capabilities` parameter defaults to an empty array rather than `null`.
2083   * @access private
2084   *
2085   * @global array<string, string> $post_type_meta_caps Used to store meta capabilities.
2086   *
2087   * @param array<string, string> $capabilities Map of core meta capability name to the custom
2088   *                                            capability name it is registered under.
2089   */
2090  function _post_type_meta_capabilities( $capabilities = array() ): void {
2091      global $post_type_meta_caps;
2092  
2093      foreach ( $capabilities as $core => $custom ) {
2094          if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ), true ) ) {
2095              $post_type_meta_caps[ $custom ] = $core;
2096          }
2097      }
2098  }
2099  
2100  /**
2101   * Builds an object with all post type labels out of a post type object.
2102   *
2103   * Note: To set labels used in post type admin notices, see the {@see 'post_updated_messages'} filter.
2104   *
2105   * @since 3.0.0
2106   * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
2107   *              and `use_featured_image` labels.
2108   * @since 4.4.0 Added the `archives`, `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
2109   *              `items_list_navigation`, and `items_list` labels.
2110   * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
2111   * @since 4.7.0 Added the `view_items` and `attributes` labels.
2112   * @since 5.0.0 Added the `item_published`, `item_published_privately`, `item_reverted_to_draft`,
2113   *              `item_scheduled`, and `item_updated` labels.
2114   * @since 5.7.0 Added the `filter_by_date` label.
2115   * @since 5.8.0 Added the `item_link` and `item_link_description` labels.
2116   * @since 6.3.0 Added the `item_trashed` label.
2117   * @since 6.4.0 Changed default values for the `add_new` label to include the type of content.
2118   *              This matches `add_new_item` and provides more context for better accessibility.
2119   * @since 6.6.0 Added the `template_name` label.
2120   * @since 6.7.0 Restored pre-6.4.0 defaults for the `add_new` label and updated documentation.
2121   *              Updated core usage to reference `add_new_item`.
2122   *
2123   * @access private
2124   *
2125   * @param object|WP_Post_Type $post_type_object Post type object.
2126   * @return stdClass {
2127   *     Post type labels object. The first default value is for non-hierarchical post types
2128   *     (like posts) and the second one is for hierarchical post types (like pages).
2129   *
2130   *     @type string      $name                     General name for the post type, usually plural. The same and
2131   *                                                 overridden by `$post_type_object->label`.
2132   *                                                 Default is 'Posts' / 'Pages'.
2133   *     @type string      $singular_name            Name for one object of this post type. Default is 'Post' / 'Page'.
2134   *     @type string      $add_new                  Label for adding a new item. Default is 'Add Post' / 'Add Page'.
2135   *     @type string      $add_new_item             Label for adding a new singular item.
2136   *                                                 Default is 'Add Post' / 'Add Page'.
2137   *     @type string      $edit_item                Label for editing a singular item.
2138   *                                                 Default is 'Edit Post' / 'Edit Page'.
2139   *     @type string      $new_item                 Label for the new item page title.
2140   *                                                 Default is 'New Post' / 'New Page'.
2141   *     @type string      $view_item                Label for viewing a singular item.
2142   *                                                 Default is 'View Post' / 'View Page'.
2143   *     @type string      $view_items               Label for viewing post type archives.
2144   *                                                 Default is 'View Posts' / 'View Pages'.
2145   *     @type string      $search_items             Label for searching plural items.
2146   *                                                 Default is 'Search Posts' / 'Search Pages'.
2147   *     @type string      $not_found                Label used when no items are found.
2148   *                                                 Default is 'No posts found' / 'No pages found'.
2149   *     @type string      $not_found_in_trash       Label used when no items are in the Trash.
2150   *                                                 Default is 'No posts found in Trash' / 'No pages found in Trash'.
2151   *     @type string|null $parent_item_colon        Label used to prefix parents of hierarchical items. Not used on
2152   *                                                 non-hierarchical post types.
2153   *                                                 Default is 'Parent Page:'.
2154   *     @type string      $all_items                Label to signify all items in a submenu link.
2155   *                                                 Default is 'All Posts' / 'All Pages'.
2156   *     @type string      $archives                 Label for archives in nav menus.
2157   *                                                 Default is 'Post Archives' / 'Page Archives'.
2158   *     @type string      $attributes               Label for the attributes meta box.
2159   *                                                 Default is 'Post Attributes' / 'Page Attributes'.
2160   *     @type string      $insert_into_item         Label for the media frame button.
2161   *                                                 Default is 'Insert into post' / 'Insert into page'.
2162   *     @type string      $uploaded_to_this_item    Label for the media frame filter.
2163   *                                                 Default is 'Uploaded to this post' / 'Uploaded to this page'.
2164   *     @type string      $featured_image           Label for the featured image meta box title.
2165   *                                                 Default is 'Featured image'.
2166   *     @type string      $set_featured_image       Label for setting the featured image.
2167   *                                                 Default is 'Set featured image'.
2168   *     @type string      $remove_featured_image    Label for removing the featured image.
2169   *                                                 Default is 'Remove featured image'.
2170   *     @type string      $use_featured_image       Label in the media frame for using a featured image.
2171   *                                                 Default is 'Use as featured image'.
2172   *     @type string      $menu_name                Label for the menu name. Default is the same as `name`.
2173   *     @type string      $name_admin_bar           Label for the object name in the admin bar.
2174   *                                                 Default is the value of `singular_name` in the given labels, or the
2175   *                                                 post type key.
2176   *     @type string      $filter_items_list        Label for the table views hidden heading.
2177   *                                                 Default is 'Filter posts list' / 'Filter pages list'.
2178   *     @type string      $filter_by_date           Label for the date filter in list tables.
2179   *                                                 Default is 'Filter by date'.
2180   *     @type string      $items_list_navigation    Label for the table pagination hidden heading.
2181   *                                                 Default is 'Posts list navigation' / 'Pages list navigation'.
2182   *     @type string      $items_list               Label for the table hidden heading.
2183   *                                                 Default is 'Posts list' / 'Pages list'.
2184   *     @type string      $item_published           Label used when an item is published.
2185   *                                                 Default is 'Post published.' / 'Page published.'
2186   *     @type string      $item_published_privately Label used when an item is published with private visibility.
2187   *                                                 Default is 'Post published privately.' / 'Page published privately.'
2188   *     @type string      $item_reverted_to_draft   Label used when an item is switched to a draft.
2189   *                                                 Default is 'Post reverted to draft.' / 'Page reverted to draft.'
2190   *     @type string      $item_trashed             Label used when an item is moved to Trash.
2191   *                                                 Default is 'Post trashed.' / 'Page trashed.'
2192   *     @type string      $item_scheduled           Label used when an item is scheduled for publishing.
2193   *                                                 Default is 'Post scheduled.' / 'Page scheduled.'
2194   *     @type string      $item_updated             Label used when an item is updated.
2195   *                                                 Default is 'Post updated.' / 'Page updated.'
2196   *     @type string      $item_link                Title for a navigation link block variation.
2197   *                                                 Default is 'Post Link' / 'Page Link'.
2198   *     @type string      $item_link_description    Description for a navigation link block variation.
2199   *                                                 Default is 'A link to a post.' / 'A link to a page.'
2200   *     @type string      $template_name            Label for the single item template. Only set when the post type is
2201   *                                                 given a `singular_name` label.
2202   *                                                 Default is 'Single item: ' followed by the singular name.
2203   * }
2204   */
2205  function get_post_type_labels( $post_type_object ) {
2206      $nohier_vs_hier_defaults = WP_Post_Type::get_default_labels();
2207  
2208      $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
2209  
2210      $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
2211  
2212      if ( ! isset( $post_type_object->labels->template_name ) && isset( $post_type_object->labels->singular_name ) ) {
2213              /* translators: %s: Post type name. */
2214              $labels->template_name = sprintf( __( 'Single item: %s' ), $post_type_object->labels->singular_name );
2215      }
2216  
2217      $post_type = $post_type_object->name;
2218  
2219      $default_labels = clone $labels;
2220  
2221      /**
2222       * Filters the labels of a specific post type.
2223       *
2224       * The dynamic portion of the hook name, `$post_type`, refers to
2225       * the post type slug.
2226       *
2227       * Possible hook names include:
2228       *
2229       *  - `post_type_labels_post`
2230       *  - `post_type_labels_page`
2231       *  - `post_type_labels_attachment`
2232       *
2233       * @since 3.5.0
2234       *
2235       * @see get_post_type_labels() for the full list of labels.
2236       *
2237       * @param object $labels Object with labels for the post type as member variables.
2238       */
2239      $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
2240  
2241      // Ensure that the filtered labels contain all required default values.
2242      $labels = (object) array_merge( (array) $default_labels, (array) $labels );
2243  
2244      return $labels;
2245  }
2246  
2247  /**
2248   * Builds an object with custom-something object (post type, taxonomy) labels
2249   * out of a custom-something object
2250   *
2251   * @since 3.0.0
2252   * @access private
2253   *
2254   * @param object $data_object             A custom-something object.
2255   * @param array  $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
2256   * @return object Object containing labels for the given custom-something object.
2257   */
2258  function _get_custom_object_labels( $data_object, $nohier_vs_hier_defaults ) {
2259      $data_object->labels = (array) $data_object->labels;
2260  
2261      if ( isset( $data_object->label ) && empty( $data_object->labels['name'] ) ) {
2262          $data_object->labels['name'] = $data_object->label;
2263      }
2264  
2265      if ( ! isset( $data_object->labels['singular_name'] ) && isset( $data_object->labels['name'] ) ) {
2266          $data_object->labels['singular_name'] = $data_object->labels['name'];
2267      }
2268  
2269      if ( ! isset( $data_object->labels['name_admin_bar'] ) ) {
2270          $data_object->labels['name_admin_bar'] = $data_object->labels['singular_name'] ?? $data_object->name;
2271      }
2272  
2273      if ( ! isset( $data_object->labels['menu_name'] ) && isset( $data_object->labels['name'] ) ) {
2274          $data_object->labels['menu_name'] = $data_object->labels['name'];
2275      }
2276  
2277      if ( ! isset( $data_object->labels['all_items'] ) && isset( $data_object->labels['menu_name'] ) ) {
2278          $data_object->labels['all_items'] = $data_object->labels['menu_name'];
2279      }
2280  
2281      if ( ! isset( $data_object->labels['archives'] ) && isset( $data_object->labels['all_items'] ) ) {
2282          $data_object->labels['archives'] = $data_object->labels['all_items'];
2283      }
2284  
2285      $defaults = array();
2286      foreach ( $nohier_vs_hier_defaults as $key => $value ) {
2287          $defaults[ $key ] = $data_object->hierarchical ? $value[1] : $value[0];
2288      }
2289  
2290      $labels              = array_merge( $defaults, $data_object->labels );
2291      $data_object->labels = (object) $data_object->labels;
2292  
2293      return (object) $labels;
2294  }
2295  
2296  /**
2297   * Adds submenus for post types.
2298   *
2299   * @access private
2300   * @since 3.1.0
2301   */
2302  function _add_post_type_submenus() {
2303      foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
2304          $ptype_obj = get_post_type_object( $ptype );
2305          // Sub-menus only.
2306          if ( ! $ptype_obj->show_in_menu || true === $ptype_obj->show_in_menu ) {
2307              continue;
2308          }
2309          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" );
2310      }
2311  }
2312  
2313  /**
2314   * Registers support of certain features for a post type.
2315   *
2316   * All core features are directly associated with a functional area of the edit
2317   * screen, such as the editor or a meta box. Features include: 'title', 'editor',
2318   * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
2319   * 'thumbnail', 'custom-fields', and 'post-formats'.
2320   *
2321   * Additionally, the 'revisions' feature dictates whether the post type will
2322   * store revisions, the 'autosave' feature dictates whether the post type
2323   * will be autosaved, and the 'comments' feature dictates whether the comments
2324   * count will show on the edit screen.
2325   *
2326   * A third, optional parameter can also be passed along with a feature to provide
2327   * additional information about supporting that feature.
2328   *
2329   * Example usage:
2330   *
2331   *     add_post_type_support( 'my_post_type', 'comments' );
2332   *     add_post_type_support( 'my_post_type', array(
2333   *         'author', 'excerpt',
2334   *     ) );
2335   *     add_post_type_support( 'my_post_type', 'my_feature', array(
2336   *         'field' => 'value',
2337   *     ) );
2338   *
2339   * @since 3.0.0
2340   * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
2341   *              by adding it to the function signature.
2342   *
2343   * @global array $_wp_post_type_features
2344   *
2345   * @param string       $post_type The post type for which to add the feature.
2346   * @param string|array $feature   The feature being added, accepts an array of
2347   *                                feature strings or a single string.
2348   * @param mixed        ...$args   Optional extra arguments to pass along with certain features.
2349   */
2350  function add_post_type_support( $post_type, $feature, ...$args ) {
2351      global $_wp_post_type_features;
2352  
2353      $features = (array) $feature;
2354      foreach ( $features as $feature ) {
2355          if ( $args ) {
2356              $_wp_post_type_features[ $post_type ][ $feature ] = $args;
2357          } else {
2358              $_wp_post_type_features[ $post_type ][ $feature ] = true;
2359          }
2360      }
2361  }
2362  
2363  /**
2364   * Removes support for a feature from a post type.
2365   *
2366   * @since 3.0.0
2367   *
2368   * @global array $_wp_post_type_features
2369   *
2370   * @param string $post_type The post type for which to remove the feature.
2371   * @param string $feature   The feature being removed.
2372   */
2373  function remove_post_type_support( $post_type, $feature ) {
2374      global $_wp_post_type_features;
2375  
2376      unset( $_wp_post_type_features[ $post_type ][ $feature ] );
2377  }
2378  
2379  /**
2380   * Gets all the post type features
2381   *
2382   * @since 3.4.0
2383   *
2384   * @global array $_wp_post_type_features
2385   *
2386   * @param string $post_type The post type.
2387   * @return array Post type supports list.
2388   */
2389  function get_all_post_type_supports( $post_type ) {
2390      global $_wp_post_type_features;
2391      return $_wp_post_type_features[ $post_type ] ?? array();
2392  }
2393  
2394  /**
2395   * Checks a post type's support for a given feature.
2396   *
2397   * @since 3.0.0
2398   *
2399   * @global array $_wp_post_type_features
2400   *
2401   * @param string $post_type The post type being checked.
2402   * @param string $feature   The feature being checked.
2403   * @return bool Whether the post type supports the given feature.
2404   */
2405  function post_type_supports( $post_type, $feature ) {
2406      global $_wp_post_type_features;
2407  
2408      return ( isset( $_wp_post_type_features[ $post_type ][ $feature ] ) );
2409  }
2410  /**
2411   * Retrieves a list of post type names that support a specific feature.
2412   *
2413   * @since 4.5.0
2414   *
2415   * @global array $_wp_post_type_features Post type features
2416   *
2417   * @param array|string $feature  Single feature or an array of features the post types should support.
2418   * @param string       $operator Optional. The logical operation to perform. 'or' means
2419   *                               only one element from the array needs to match; 'and'
2420   *                               means all elements must match; 'not' means no elements may
2421   *                               match. Default 'and'.
2422   * @return string[] A list of post type names.
2423   */
2424  function get_post_types_by_support( $feature, $operator = 'and' ) {
2425      global $_wp_post_type_features;
2426  
2427      $features = array_fill_keys( (array) $feature, true );
2428  
2429      return array_keys( wp_filter_object_list( $_wp_post_type_features, $features, $operator ) );
2430  }
2431  
2432  /**
2433   * Updates the post type for the post ID.
2434   *
2435   * The page or post cache will be cleaned for the post ID.
2436   *
2437   * @since 2.5.0
2438   *
2439   * @global wpdb $wpdb WordPress database abstraction object.
2440   *
2441   * @param int    $post_id   Optional. Post ID to change post type. Default 0.
2442   * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
2443   *                          name a few. Default 'post'.
2444   * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
2445   */
2446  function set_post_type( $post_id = 0, $post_type = 'post' ) {
2447      global $wpdb;
2448  
2449      $post_type = sanitize_post_field( 'post_type', $post_type, $post_id, 'db' );
2450      $return    = $wpdb->update( $wpdb->posts, array( 'post_type' => $post_type ), array( 'ID' => $post_id ) );
2451  
2452      clean_post_cache( $post_id );
2453  
2454      return $return;
2455  }
2456  
2457  /**
2458   * Determines whether a post type is considered "viewable".
2459   *
2460   * For built-in post types such as posts and pages, the 'public' value will be evaluated.
2461   * For all others, the 'publicly_queryable' value will be used.
2462   *
2463   * @since 4.4.0
2464   * @since 4.5.0 Added the ability to pass a post type name in addition to object.
2465   * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
2466   * @since 5.9.0 Added `is_post_type_viewable` hook to filter the result.
2467   *
2468   * @param string|WP_Post_Type $post_type Post type name or object.
2469   * @return bool Whether the post type should be considered viewable.
2470   */
2471  function is_post_type_viewable( $post_type ) {
2472      if ( is_scalar( $post_type ) ) {
2473          $post_type = get_post_type_object( $post_type );
2474  
2475          if ( ! $post_type ) {
2476              return false;
2477          }
2478      }
2479  
2480      if ( ! is_object( $post_type ) ) {
2481          return false;
2482      }
2483  
2484      $is_viewable = $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
2485  
2486      /**
2487       * Filters whether a post type is considered "viewable".
2488       *
2489       * The returned filtered value must be a boolean type to ensure
2490       * `is_post_type_viewable()` only returns a boolean. This strictness
2491       * is by design to maintain backwards-compatibility and guard against
2492       * potential type errors in PHP 8.1+. Non-boolean values (even falsey
2493       * and truthy values) will result in the function returning false.
2494       *
2495       * @since 5.9.0
2496       *
2497       * @param bool         $is_viewable Whether the post type is "viewable" (strict type).
2498       * @param WP_Post_Type $post_type   Post type object.
2499       */
2500      return true === apply_filters( 'is_post_type_viewable', $is_viewable, $post_type );
2501  }
2502  
2503  /**
2504   * Determines whether a post status is considered "viewable".
2505   *
2506   * For built-in post statuses such as publish and private, the 'public' value will be evaluated.
2507   * For all others, the 'publicly_queryable' value will be used.
2508   *
2509   * @since 5.7.0
2510   * @since 5.9.0 Added `is_post_status_viewable` hook to filter the result.
2511   *
2512   * @param string|stdClass $post_status Post status name or object.
2513   * @return bool Whether the post status should be considered viewable.
2514   */
2515  function is_post_status_viewable( $post_status ) {
2516      if ( is_scalar( $post_status ) ) {
2517          if ( ! is_string( $post_status ) ) {
2518              return false;
2519          }
2520  
2521          $post_status = get_post_status_object( $post_status );
2522  
2523          if ( ! $post_status ) {
2524              return false;
2525          }
2526      }
2527  
2528      if (
2529          ! is_object( $post_status ) ||
2530          $post_status->internal ||
2531          $post_status->protected
2532      ) {
2533          return false;
2534      }
2535  
2536      $is_viewable = $post_status->publicly_queryable || ( $post_status->_builtin && $post_status->public );
2537  
2538      /**
2539       * Filters whether a post status is considered "viewable".
2540       *
2541       * The returned filtered value must be a boolean type to ensure
2542       * `is_post_status_viewable()` only returns a boolean. This strictness
2543       * is by design to maintain backwards-compatibility and guard against
2544       * potential type errors in PHP 8.1+. Non-boolean values (even falsey
2545       * and truthy values) will result in the function returning false.
2546       *
2547       * @since 5.9.0
2548       *
2549       * @param bool     $is_viewable Whether the post status is "viewable" (strict type).
2550       * @param stdClass $post_status Post status object.
2551       */
2552      return true === apply_filters( 'is_post_status_viewable', $is_viewable, $post_status );
2553  }
2554  
2555  /**
2556   * Determines whether a post is publicly viewable.
2557   *
2558   * Posts are considered publicly viewable if both the post status and post type
2559   * are viewable.
2560   *
2561   * @since 5.7.0
2562   *
2563   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2564   * @return bool Whether the post is publicly viewable.
2565   */
2566  function is_post_publicly_viewable( $post = null ) {
2567      $post = get_post( $post );
2568  
2569      if ( ! $post ) {
2570          return false;
2571      }
2572  
2573      $post_type   = get_post_type( $post );
2574      $post_status = get_post_status( $post );
2575  
2576      return is_post_type_viewable( $post_type ) && is_post_status_viewable( $post_status );
2577  }
2578  
2579  /**
2580   * Determines whether a post is embeddable.
2581   *
2582   * @since 6.8.0
2583   *
2584   * @param int|WP_Post|null $post Optional. Post ID or `WP_Post` object. Defaults to global $post.
2585   * @return bool Whether the post should be considered embeddable.
2586   */
2587  function is_post_embeddable( $post = null ) {
2588      $post = get_post( $post );
2589  
2590      if ( ! $post ) {
2591          return false;
2592      }
2593  
2594      $post_type = get_post_type_object( $post->post_type );
2595  
2596      if ( ! $post_type ) {
2597          return false;
2598      }
2599  
2600      $is_embeddable = $post_type->embeddable;
2601  
2602      /**
2603       * Filter whether a post is embeddable.
2604       *
2605       * @since 6.8.0
2606       *
2607       * @param bool    $is_embeddable Whether the post is embeddable.
2608       * @param WP_Post $post          Post object.
2609       */
2610      return apply_filters( 'is_post_embeddable', $is_embeddable, $post );
2611  }
2612  
2613  /**
2614   * Retrieves an array of the latest posts, or posts matching the given criteria.
2615   *
2616   * For more information on the accepted arguments, see the
2617   * {@link https://developer.wordpress.org/reference/classes/wp_query/
2618   * WP_Query} documentation in the Developer Handbook.
2619   *
2620   * The `$ignore_sticky_posts` and `$no_found_rows` arguments are ignored by
2621   * this function and both are set to `true`.
2622   *
2623   * The defaults are as follows:
2624   *
2625   * @since 1.2.0
2626   *
2627   * @see WP_Query
2628   * @see WP_Query::parse_query()
2629   *
2630   * @param array|string $args {
2631   *     Optional. Array or query string of arguments to retrieve posts.
2632   *     See WP_Query::parse_query() for all available arguments.
2633   *
2634   *     @type int        $numberposts      Total number of posts to retrieve. Is an alias of `$posts_per_page`
2635   *                                        in WP_Query. Accepts -1 for all. Default 5.
2636   *     @type int|string $category         Category ID or comma-separated list of IDs (this or any children).
2637   *                                        Is an alias of `$cat` in WP_Query. Default 0.
2638   *     @type int[]      $include          An array of post IDs to retrieve, sticky posts will be included.
2639   *                                        Is an alias of `$post__in` in WP_Query. Default empty array.
2640   *     @type int[]      $exclude          An array of post IDs not to retrieve. Default empty array.
2641   *     @type bool       $suppress_filters Whether to suppress filters. Default true.
2642   * }
2643   * @return WP_Post[]|int[] Array of post objects or post IDs.
2644   *
2645   * @phpstan-return (
2646   *     $args is array{ fields: 'ids', ... }
2647   *         ? int[]
2648   *         : ( $args is array{ fields: 'id=>parent', ... }
2649   *             ? array<int, int>
2650   *             : WP_Post[] )
2651   * )
2652   */
2653  function get_posts( $args = null ) {
2654      $defaults = array(
2655          'numberposts'      => 5,
2656          'category'         => 0,
2657          'orderby'          => 'date',
2658          'order'            => 'DESC',
2659          'include'          => array(),
2660          'exclude'          => array(),
2661          'meta_key'         => '',
2662          'meta_value'       => '',
2663          'post_type'        => 'post',
2664          'suppress_filters' => true,
2665      );
2666  
2667      $parsed_args = wp_parse_args( $args, $defaults );
2668      if ( empty( $parsed_args['post_status'] ) ) {
2669          $parsed_args['post_status'] = ( 'attachment' === $parsed_args['post_type'] ) ? 'inherit' : 'publish';
2670      }
2671      if ( ! empty( $parsed_args['numberposts'] ) && empty( $parsed_args['posts_per_page'] ) ) {
2672          $parsed_args['posts_per_page'] = $parsed_args['numberposts'];
2673      }
2674      if ( ! empty( $parsed_args['category'] ) ) {
2675          $parsed_args['cat'] = $parsed_args['category'];
2676      }
2677      if ( ! empty( $parsed_args['include'] ) ) {
2678          $incposts                      = wp_parse_id_list( $parsed_args['include'] );
2679          $parsed_args['posts_per_page'] = count( $incposts );  // Only the number of posts included.
2680          $parsed_args['post__in']       = $incposts;
2681      } elseif ( ! empty( $parsed_args['exclude'] ) ) {
2682          $parsed_args['post__not_in'] = wp_parse_id_list( $parsed_args['exclude'] );
2683      }
2684  
2685      $parsed_args['ignore_sticky_posts'] = true;
2686      $parsed_args['no_found_rows']       = true;
2687  
2688      $get_posts = new WP_Query();
2689      return $get_posts->query( $parsed_args );
2690  }
2691  
2692  //
2693  // Post meta functions.
2694  //
2695  
2696  /**
2697   * Adds a meta field to the given post.
2698   *
2699   * Post meta data is called "Custom Fields" on the Administration Screen.
2700   *
2701   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
2702   *
2703   * @since 1.5.0
2704   *
2705   * @param int    $post_id    Post ID.
2706   * @param string $meta_key   Metadata name.
2707   * @param mixed  $meta_value Metadata value. Arrays and objects are stored as serialized data and
2708   *                           will be returned as the same type when retrieved. Other data types will
2709   *                           be stored as strings in the database:
2710   *                           - false is stored and retrieved as an empty string ('')
2711   *                           - true is stored and retrieved as '1'
2712   *                           - numbers (both integer and float) are stored and retrieved as strings
2713   *                           Must be serializable if non-scalar.
2714   * @param bool   $unique     Optional. Whether the same key should not be added.
2715   *                           Default false.
2716   * @return int|false Meta ID on success, false on failure.
2717   */
2718  function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
2719      // Make sure meta is added to the post, not a revision.
2720      $the_post = wp_is_post_revision( $post_id );
2721      if ( $the_post ) {
2722          $post_id = $the_post;
2723      }
2724  
2725      return add_metadata( 'post', $post_id, $meta_key, $meta_value, $unique );
2726  }
2727  
2728  /**
2729   * Deletes a post meta field for the given post ID.
2730   *
2731   * You can match based on the key, or key and value. Removing based on key and
2732   * value, will keep from removing duplicate metadata with the same key. It also
2733   * allows removing all metadata matching the key, if needed.
2734   *
2735   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
2736   *
2737   * @since 1.5.0
2738   *
2739   * @param int    $post_id    Post ID.
2740   * @param string $meta_key   Metadata name.
2741   * @param mixed  $meta_value Optional. Metadata value. If provided,
2742   *                           rows will only be removed that match the value.
2743   *                           Must be serializable if non-scalar. Default empty.
2744   * @return bool True on success, false on failure.
2745   *
2746   * @phpstan-param positive-int $post_id
2747   */
2748  function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
2749      // Make sure meta is deleted from the post, not from a revision.
2750      $the_post = wp_is_post_revision( $post_id );
2751      if ( $the_post ) {
2752          $post_id = $the_post;
2753      }
2754  
2755      return delete_metadata( 'post', $post_id, $meta_key, $meta_value );
2756  }
2757  
2758  /**
2759   * Retrieves a post meta field for the given post ID.
2760   *
2761   * @since 1.5.0
2762   *
2763   * @param int    $post_id Post ID.
2764   * @param string $key     Optional. The meta key to retrieve. By default,
2765   *                        returns data for all keys. Default empty.
2766   * @param bool   $single  Optional. Whether to return a single value.
2767   *                        This parameter has no effect if `$key` is not specified.
2768   *                        Default false.
2769   * @return mixed An array of values if `$single` is false.
2770   *               The value of the meta field if `$single` is true.
2771   *               False for an invalid `$post_id` (non-numeric, zero, or negative value).
2772   *               An empty array if a valid but non-existing post ID is passed and `$single` is false.
2773   *               An empty string if a valid but non-existing post ID is passed and `$single` is true.
2774   *               Note: Non-serialized values are returned as strings:
2775   *               - false values are returned as empty strings ('')
2776   *               - true values are returned as '1'
2777   *               - numbers (both integer and float) are returned as strings
2778   *               Arrays and objects retain their original type.
2779   *               These conversions apply to stored values. A default value registered
2780   *               with {@see register_meta()} is never stored, so it is returned with
2781   *               the type it was registered with, which may be an integer, float, or
2782   *               boolean.
2783   *
2784   * @phpstan-return (
2785   *     $key is ''|'0'
2786   *         ? array<array-key, list<string>>|false
2787   *         : ( $single is true
2788   *             ? mixed
2789   *             : list<mixed>|false )
2790   * )
2791   */
2792  function get_post_meta( $post_id, $key = '', $single = false ) {
2793      return get_metadata( 'post', $post_id, $key, $single );
2794  }
2795  
2796  /**
2797   * Updates a post meta field based on the given post ID.
2798   *
2799   * Use the `$prev_value` parameter to differentiate between meta fields with the
2800   * same key and post ID.
2801   *
2802   * If the meta field for the post does not exist, it will be added and its ID returned.
2803   *
2804   * Can be used in place of add_post_meta().
2805   *
2806   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
2807   *
2808   * @since 1.5.0
2809   *
2810   * @param int    $post_id    Post ID.
2811   * @param string $meta_key   Metadata key.
2812   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
2813   * @param mixed  $prev_value Optional. Previous value to check before updating.
2814   *                           If specified, only update existing metadata entries with
2815   *                           this value. Otherwise, update all entries. Default empty.
2816   * @return int|bool Meta ID if the key didn't exist, true on successful update,
2817   *                  false on failure or if the value passed to the function
2818   *                  is the same as the one that is already in the database.
2819   */
2820  function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
2821      // Make sure meta is updated for the post, not for a revision.
2822      $the_post = wp_is_post_revision( $post_id );
2823      if ( $the_post ) {
2824          $post_id = $the_post;
2825      }
2826  
2827      return update_metadata( 'post', $post_id, $meta_key, $meta_value, $prev_value );
2828  }
2829  
2830  /**
2831   * Deletes everything from post meta matching the given meta key.
2832   *
2833   * @since 2.3.0
2834   *
2835   * @param string $post_meta_key Key to search for when deleting.
2836   * @return bool Whether the post meta key was deleted from the database.
2837   */
2838  function delete_post_meta_by_key( $post_meta_key ) {
2839      return delete_metadata( 'post', 0, $post_meta_key, '', true );
2840  }
2841  
2842  /**
2843   * Registers a meta key for posts.
2844   *
2845   * @since 4.9.8
2846   *
2847   * @param string $post_type Post type to register a meta key for. Pass an empty string
2848   *                          to register the meta key across all existing post types.
2849   * @param string $meta_key  The meta key to register.
2850   * @param array  $args      Data used to describe the meta key when registered. See
2851   *                          {@see register_meta()} for a list of supported arguments.
2852   * @return bool True if the meta key was successfully registered, false if not.
2853   */
2854  function register_post_meta( $post_type, $meta_key, array $args ) {
2855      $args['object_subtype'] = $post_type;
2856  
2857      return register_meta( 'post', $meta_key, $args );
2858  }
2859  
2860  /**
2861   * Unregisters a meta key for posts.
2862   *
2863   * @since 4.9.8
2864   *
2865   * @param string $post_type Post type the meta key is currently registered for. Pass
2866   *                          an empty string if the meta key is registered across all
2867   *                          existing post types.
2868   * @param string $meta_key  The meta key to unregister.
2869   * @return bool True on success, false if the meta key was not previously registered.
2870   */
2871  function unregister_post_meta( $post_type, $meta_key ) {
2872      return unregister_meta_key( 'post', $meta_key, $post_type );
2873  }
2874  
2875  /**
2876   * Retrieves post meta fields, based on post ID.
2877   *
2878   * The post meta fields are retrieved from the cache where possible,
2879   * so the function is optimized to be called more than once.
2880   *
2881   * @since 1.2.0
2882   *
2883   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
2884   * @return array<string|int, array<int, string>>|false Array of post meta values keyed by meta key, or false on failure.
2885   *                                                     Post meta values will always be strings, even for values which
2886   *                                                     would otherwise be retrieved individually as arrays or objects
2887   *                                                     via {@see get_post_meta()}. A meta key which is a numeric string
2888   *                                                     is keyed by the equivalent integer, as PHP casts such array keys.
2889   *                                                     An empty array is returned if the post has no post meta.
2890   *
2891   * @phpstan-return array<array-key, list<string>>|false
2892   */
2893  function get_post_custom( $post_id = 0 ) {
2894      $post_id = absint( $post_id );
2895  
2896      if ( ! $post_id ) {
2897          $post_id = get_the_ID();
2898          if ( false === $post_id ) {
2899              return false;
2900          }
2901      }
2902  
2903      return get_post_meta( $post_id );
2904  }
2905  
2906  /**
2907   * Retrieves meta field names for a post.
2908   *
2909   * If there are no meta fields, then nothing (null) will be returned.
2910   *
2911   * @since 1.2.0
2912   *
2913   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
2914   * @return array<string|int>|null Array of the meta field keys, if retrieved. Null if the post has no
2915   *                                post meta, or if the post meta could not be retrieved. A key which is
2916   *                                a numeric string is returned as the equivalent integer.
2917   *
2918   * @phpstan-return non-empty-list<array-key>|null
2919   */
2920  function get_post_custom_keys( $post_id = 0 ) {
2921      $custom = get_post_custom( $post_id );
2922  
2923      if ( ! is_array( $custom ) ) {
2924          return null;
2925      }
2926  
2927      $keys = array_keys( $custom );
2928      if ( $keys ) {
2929          return $keys;
2930      }
2931      return null;
2932  }
2933  
2934  /**
2935   * Retrieves values for a custom post field.
2936   *
2937   * The parameters must not be considered optional. All of the post meta fields
2938   * will be retrieved and only the meta field key values returned.
2939   *
2940   * @since 1.2.0
2941   *
2942   * @param string $key     Optional. Meta field key. Default empty.
2943   * @param int    $post_id Optional. Post ID. Default is the ID of the global `$post`.
2944   * @return string[]|null Meta field values. Null if `$key` is not specified, if the post has no
2945   *                       meta for that key, or if the post meta could not be retrieved.
2946   *                       Values are always strings, as described for {@see get_post_custom()}.
2947   *
2948   * @phpstan-return ( $key is ''|'0' ? null : list<string>|null )
2949   */
2950  function get_post_custom_values( $key = '', $post_id = 0 ) {
2951      if ( ! $key ) {
2952          return null;
2953      }
2954  
2955      $custom = get_post_custom( $post_id );
2956  
2957      return $custom[ $key ] ?? null;
2958  }
2959  
2960  /**
2961   * Determines whether a post is sticky.
2962   *
2963   * Sticky posts should remain at the top of The Loop. If the post ID is not
2964   * given, then The Loop ID for the current post will be used.
2965   *
2966   * For more information on this and similar theme functions, check out
2967   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
2968   * Conditional Tags} article in the Theme Developer Handbook.
2969   *
2970   * @since 2.7.0
2971   *
2972   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
2973   * @return bool Whether post is sticky.
2974   */
2975  function is_sticky( $post_id = 0 ) {
2976      $post_id = absint( $post_id );
2977  
2978      if ( ! $post_id ) {
2979          $post_id = get_the_ID();
2980      }
2981  
2982      $stickies = get_option( 'sticky_posts' );
2983  
2984      if ( is_array( $stickies ) ) {
2985          $stickies  = array_map( 'intval', $stickies );
2986          $is_sticky = in_array( $post_id, $stickies, true );
2987      } else {
2988          $is_sticky = false;
2989      }
2990  
2991      /**
2992       * Filters whether a post is sticky.
2993       *
2994       * @since 5.3.0
2995       *
2996       * @param bool $is_sticky Whether a post is sticky.
2997       * @param int  $post_id   Post ID.
2998       */
2999      return apply_filters( 'is_sticky', $is_sticky, $post_id );
3000  }
3001  
3002  /**
3003   * Sanitizes every post field.
3004   *
3005   * If the context is 'raw', then the post object or array will get minimal
3006   * sanitization of the integer fields.
3007   *
3008   * @since 2.3.0
3009   *
3010   * @see sanitize_post_field()
3011   *
3012   * @param object|WP_Post|array $post    The post object or array
3013   * @param string               $context Optional. How to sanitize post fields.
3014   *                                      Accepts 'raw', 'edit', 'db', 'display',
3015   *                                      'attribute', or 'js'. Default 'display'.
3016   * @return object|WP_Post|array The now sanitized post object or array (will be the
3017   *                              same type as `$post`).
3018   *
3019   * @phpstan-param stdClass|WP_Post|array<string, mixed> $post
3020   * @phpstan-param 'raw'|'edit'|'db'|'display'|'attribute'|'js' $context
3021   * @phpstan-return (
3022   *     $post is WP_Post ? WP_Post : (
3023   *         $post is stdClass ? stdClass : array<string, mixed>
3024   *     )
3025   * )
3026   */
3027  function sanitize_post( $post, $context = 'display' ) {
3028      if ( is_object( $post ) ) {
3029          // Check if post already filtered for this context.
3030          if ( isset( $post->filter ) && $context === $post->filter ) {
3031              return $post;
3032          }
3033          if ( ! isset( $post->ID ) ) {
3034              $post->ID = 0;
3035          }
3036          foreach ( array_keys( get_object_vars( $post ) ) as $field ) {
3037              $post->$field = sanitize_post_field( $field, $post->$field, (int) $post->ID, $context );
3038          }
3039          $post->filter = $context;
3040      } elseif ( is_array( $post ) ) {
3041          // Check if post already filtered for this context.
3042          if ( isset( $post['filter'] ) && $context === $post['filter'] ) {
3043              return $post;
3044          }
3045          if ( ! isset( $post['ID'] ) ) {
3046              $post['ID'] = 0;
3047          }
3048          foreach ( array_keys( $post ) as $field ) {
3049              $post[ $field ] = sanitize_post_field( $field, $post[ $field ], (int) $post['ID'], $context );
3050          }
3051          $post['filter'] = $context;
3052      }
3053      return $post;
3054  }
3055  
3056  /**
3057   * Sanitizes a post field based on context.
3058   *
3059   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and
3060   * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
3061   * are treated like 'display' when calling filters. The 'sample' value is used
3062   * for permalink previewing.
3063   *
3064   * @since 2.3.0
3065   * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
3066   *
3067   * @param string $field   The Post Object field name.
3068   * @param mixed  $value   The Post Object value.
3069   * @param int    $post_id Post ID.
3070   * @param string $context Optional. How to sanitize the field. Possible values are 'raw', 'edit', 'db', 'display',
3071   *                        'attribute' and 'js'. The 'sample' value is used for permalink previewing. Default 'display'.
3072   * @return mixed Sanitized value.
3073   *
3074   * @phpstan-param 'raw'|'edit'|'db'|'display'|'attribute'|'js'|'sample' $context
3075   * @phpstan-return (
3076   *     $field is 'ID'|'post_parent'|'menu_order' ? int : (
3077   *         $field is 'ancestors' ? non-negative-int[] : string
3078   *     )
3079   * )
3080   */
3081  function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
3082      $int_fields = array( 'ID', 'post_parent', 'menu_order' );
3083      if ( in_array( $field, $int_fields, true ) ) {
3084          $value = (int) $value;
3085      }
3086  
3087      // Fields which contain arrays of integers.
3088      $array_int_fields = array( 'ancestors' );
3089      if ( in_array( $field, $array_int_fields, true ) ) {
3090          $value = array_map( 'absint', (array) $value );
3091          return $value;
3092      }
3093  
3094      if ( 'raw' === $context ) {
3095          return $value;
3096      }
3097  
3098      $prefixed = false;
3099      if ( str_contains( $field, 'post_' ) ) {
3100          $prefixed        = true;
3101          $field_no_prefix = str_replace( 'post_', '', $field );
3102      }
3103  
3104      if ( 'edit' === $context ) {
3105          $format_to_edit = array( 'post_content', 'post_excerpt', 'post_title', 'post_password' );
3106  
3107          if ( $prefixed ) {
3108  
3109              /**
3110               * Filters the value of a specific post field to edit.
3111               *
3112               * The dynamic portion of the hook name, `$field`, refers to the post
3113               * field name. Possible filter names include:
3114               *
3115               *  - `edit_post_author`
3116               *  - `edit_post_date`
3117               *  - `edit_post_date_gmt`
3118               *  - `edit_post_content`
3119               *  - `edit_post_title`
3120               *  - `edit_post_excerpt`
3121               *  - `edit_post_status`
3122               *  - `edit_post_password`
3123               *  - `edit_post_name`
3124               *  - `edit_post_modified`
3125               *  - `edit_post_modified_gmt`
3126               *  - `edit_post_content_filtered`
3127               *  - `edit_post_parent`
3128               *  - `edit_post_type`
3129               *  - `edit_post_mime_type`
3130               *
3131               * @since 2.3.0
3132               *
3133               * @param mixed $value   Value of the post field.
3134               * @param int   $post_id Post ID.
3135               */
3136              $value = apply_filters( "edit_{$field}", $value, $post_id );
3137  
3138              /**
3139               * Filters the value of a specific post field to edit.
3140               *
3141               * Only applied to post fields with a name which is prefixed with `post_`.
3142               *
3143               * The dynamic portion of the hook name, `$field_no_prefix`, refers to the
3144               * post field name minus the `post_` prefix. Possible filter names include:
3145               *
3146               *  - `author_edit_pre`
3147               *  - `date_edit_pre`
3148               *  - `date_gmt_edit_pre`
3149               *  - `content_edit_pre`
3150               *  - `title_edit_pre`
3151               *  - `excerpt_edit_pre`
3152               *  - `status_edit_pre`
3153               *  - `password_edit_pre`
3154               *  - `name_edit_pre`
3155               *  - `modified_edit_pre`
3156               *  - `modified_gmt_edit_pre`
3157               *  - `content_filtered_edit_pre`
3158               *  - `parent_edit_pre`
3159               *  - `type_edit_pre`
3160               *  - `mime_type_edit_pre`
3161               *
3162               * @since 2.3.0
3163               *
3164               * @param mixed $value   Value of the post field.
3165               * @param int   $post_id Post ID.
3166               */
3167              $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
3168          } else {
3169              /**
3170               * Filters the value of a specific post field to edit.
3171               *
3172               * Only applied to post fields not prefixed with `post_`.
3173               *
3174               * The dynamic portion of the hook name, `$field`, refers to the
3175               * post field name. Possible filter names include:
3176               *
3177               *  - `edit_post_ID`
3178               *  - `edit_post_ping_status`
3179               *  - `edit_post_pinged`
3180               *  - `edit_post_to_ping`
3181               *  - `edit_post_comment_count`
3182               *  - `edit_post_comment_status`
3183               *  - `edit_post_guid`
3184               *  - `edit_post_menu_order`
3185               *
3186               * @since 2.3.0
3187               *
3188               * @param mixed $value   Value of the post field.
3189               * @param int   $post_id Post ID.
3190               */
3191              $value = apply_filters( "edit_post_{$field}", $value, $post_id );
3192          }
3193  
3194          if ( in_array( $field, $format_to_edit, true ) ) {
3195              if ( 'post_content' === $field ) {
3196                  $value = format_to_edit( $value, user_can_richedit() );
3197              } else {
3198                  $value = format_to_edit( $value );
3199              }
3200          } else {
3201              $value = esc_attr( $value );
3202          }
3203      } elseif ( 'db' === $context ) {
3204          if ( $prefixed ) {
3205  
3206              /**
3207               * Filters the value of a specific post field before saving.
3208               *
3209               * Only applied to post fields with a name which is prefixed with `post_`.
3210               *
3211               * The dynamic portion of the hook name, `$field`, refers to the post
3212               * field name. Possible filter names include:
3213               *
3214               *  - `pre_post_author`
3215               *  - `pre_post_date`
3216               *  - `pre_post_date_gmt`
3217               *  - `pre_post_content`
3218               *  - `pre_post_title`
3219               *  - `pre_post_excerpt`
3220               *  - `pre_post_status`
3221               *  - `pre_post_password`
3222               *  - `pre_post_name`
3223               *  - `pre_post_modified`
3224               *  - `pre_post_modified_gmt`
3225               *  - `pre_post_content_filtered`
3226               *  - `pre_post_parent`
3227               *  - `pre_post_type`
3228               *  - `pre_post_mime_type`
3229               *
3230               * @since 2.3.0
3231               *
3232               * @param mixed $value Value of the post field.
3233               */
3234              $value = apply_filters( "pre_{$field}", $value );
3235  
3236              /**
3237               * Filters the value of a specific field before saving.
3238               *
3239               * Only applied to post fields with a name which is prefixed with `post_`.
3240               *
3241               * The dynamic portion of the hook name, `$field_no_prefix`, refers to the
3242               * post field name minus the `post_` prefix. Possible filter names include:
3243               *
3244               *  - `author_save_pre`
3245               *  - `date_save_pre`
3246               *  - `date_gmt_save_pre`
3247               *  - `content_save_pre`
3248               *  - `title_save_pre`
3249               *  - `excerpt_save_pre`
3250               *  - `status_save_pre`
3251               *  - `password_save_pre`
3252               *  - `name_save_pre`
3253               *  - `modified_save_pre`
3254               *  - `modified_gmt_save_pre`
3255               *  - `content_filtered_save_pre`
3256               *  - `parent_save_pre`
3257               *  - `type_save_pre`
3258               *  - `mime_type_save_pre`
3259               *
3260               * @since 2.3.0
3261               *
3262               * @param mixed $value Value of the post field.
3263               */
3264              $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
3265          } else {
3266              /**
3267               * Filters the value of a specific field before saving.
3268               *
3269               * Only applied to post fields with a name which is prefixed with `post_`.
3270               *
3271               * The dynamic portion of the hook name, `$field_no_prefix`, refers to the
3272               * post field name minus the `post_` prefix. Possible filter names include:
3273               *
3274               *  - `pre_post_ID`
3275               *  - `pre_post_comment_status`
3276               *  - `pre_post_ping_status`
3277               *  - `pre_post_to_ping`
3278               *  - `pre_post_pinged`
3279               *  - `pre_post_guid`
3280               *  - `pre_post_menu_order`
3281               *  - `pre_post_comment_count`
3282               *
3283               * @since 2.3.0
3284               *
3285               * @param mixed $value Value of the post field.
3286               */
3287              $value = apply_filters( "pre_post_{$field}", $value );
3288  
3289              /**
3290               * Filters the value of a specific post field before saving.
3291               *
3292               * Only applied to post fields with a name which is *not* prefixed with `post_`.
3293               *
3294               * The dynamic portion of the hook name, `$field`, refers to the post
3295               * field name. Possible filter names include:
3296               *
3297               *  - `ID_pre`
3298               *  - `comment_status_pre`
3299               *  - `ping_status_pre`
3300               *  - `to_ping_pre`
3301               *  - `pinged_pre`
3302               *  - `guid_pre`
3303               *  - `menu_order_pre`
3304               *  - `comment_count_pre`
3305               *
3306               * @since 2.3.0
3307               *
3308               * @param mixed $value Value of the post field.
3309               */
3310              $value = apply_filters( "{$field}_pre", $value );
3311          }
3312      } else {
3313  
3314          // Use display filters by default.
3315          if ( $prefixed ) {
3316  
3317              /**
3318               * Filters the value of a specific post field for display.
3319               *
3320               * Only applied to post fields with a name which is prefixed with `post_`.
3321               *
3322               * The dynamic portion of the hook name, `$field`, refers to the post
3323               * field name. Possible filter names include:
3324               *
3325               *  - `post_author`
3326               *  - `post_date`
3327               *  - `post_date_gmt`
3328               *  - `post_content`
3329               *  - `post_title`
3330               *  - `post_excerpt`
3331               *  - `post_status`
3332               *  - `post_password`
3333               *  - `post_name`
3334               *  - `post_modified`
3335               *  - `post_modified_gmt`
3336               *  - `post_content_filtered`
3337               *  - `post_parent`
3338               *  - `post_type`
3339               *  - `post_mime_type`
3340               *
3341               * @since 2.3.0
3342               *
3343               * @param mixed  $value   Value of the prefixed post field.
3344               * @param int    $post_id Post ID.
3345               * @param string $context Context for how to sanitize the field.
3346               *                        Accepts 'raw', 'edit', 'db', 'display',
3347               *                        'attribute', or 'js'. The 'sample' value is
3348               *                        used for permalink previewing. Default 'display'.
3349               */
3350              $value = apply_filters( "{$field}", $value, $post_id, $context );
3351          } else {
3352              /**
3353               * Filters the value of a specific post field for display.
3354               *
3355               * Only applied to post fields name which is *not* prefixed with `post_`.
3356               *
3357               * The dynamic portion of the hook name, `$field`, refers to the post
3358               * field name. Possible filter names include:
3359               *
3360               *  - `post_ID`
3361               *  - `post_comment_status`
3362               *  - `post_ping_status`
3363               *  - `post_to_ping`
3364               *  - `post_pinged`
3365               *  - `post_guid`
3366               *  - `post_menu_order`
3367               *  - `post_comment_count`
3368               *
3369               * @since 2.3.0
3370               *
3371               * @param mixed  $value   Value of the unprefixed post field.
3372               * @param int    $post_id Post ID
3373               * @param string $context Context for how to sanitize the field.
3374               *                        Accepts 'raw', 'edit', 'db', 'display',
3375               *                        'attribute', or 'js'. The 'sample' value is
3376               *                        used for permalink previewing. Default 'display'.
3377               */
3378              $value = apply_filters( "post_{$field}", $value, $post_id, $context );
3379          }
3380  
3381          if ( 'attribute' === $context ) {
3382              $value = esc_attr( $value );
3383          } elseif ( 'js' === $context ) {
3384              $value = esc_js( $value );
3385          }
3386      }
3387  
3388      // Restore the type for integer fields after esc_attr().
3389      if ( in_array( $field, $int_fields, true ) ) {
3390          $value = (int) $value;
3391      }
3392      return $value;
3393  }
3394  
3395  /**
3396   * Makes a post sticky.
3397   *
3398   * Sticky posts should be displayed at the top of the front page.
3399   *
3400   * @since 2.7.0
3401   *
3402   * @param int $post_id Post ID.
3403   */
3404  function stick_post( $post_id ) {
3405      $post_id  = (int) $post_id;
3406      $stickies = get_option( 'sticky_posts' );
3407      $updated  = false;
3408  
3409      if ( ! is_array( $stickies ) ) {
3410          $stickies = array();
3411      } else {
3412          $stickies = array_unique( array_map( 'intval', $stickies ) );
3413      }
3414  
3415      if ( ! in_array( $post_id, $stickies, true ) ) {
3416          $stickies[] = $post_id;
3417          $updated    = update_option( 'sticky_posts', array_values( $stickies ) );
3418      }
3419  
3420      if ( $updated ) {
3421          /**
3422           * Fires once a post has been added to the sticky list.
3423           *
3424           * @since 4.6.0
3425           *
3426           * @param int $post_id ID of the post that was stuck.
3427           */
3428          do_action( 'post_stuck', $post_id );
3429      }
3430  }
3431  
3432  /**
3433   * Un-sticks a post.
3434   *
3435   * Sticky posts should be displayed at the top of the front page.
3436   *
3437   * @since 2.7.0
3438   *
3439   * @param int $post_id Post ID.
3440   */
3441  function unstick_post( $post_id ) {
3442      $post_id  = (int) $post_id;
3443      $stickies = get_option( 'sticky_posts' );
3444  
3445      if ( ! is_array( $stickies ) ) {
3446          return;
3447      }
3448  
3449      $stickies = array_values( array_unique( array_map( 'intval', $stickies ) ) );
3450  
3451      if ( ! in_array( $post_id, $stickies, true ) ) {
3452          return;
3453      }
3454  
3455      $offset = array_search( $post_id, $stickies, true );
3456      if ( false === $offset ) {
3457          return;
3458      }
3459  
3460      array_splice( $stickies, $offset, 1 );
3461  
3462      $updated = update_option( 'sticky_posts', $stickies );
3463  
3464      if ( $updated ) {
3465          /**
3466           * Fires once a post has been removed from the sticky list.
3467           *
3468           * @since 4.6.0
3469           *
3470           * @param int $post_id ID of the post that was unstuck.
3471           */
3472          do_action( 'post_unstuck', $post_id );
3473      }
3474  }
3475  
3476  /**
3477   * Returns the cache key for wp_count_posts() based on the passed arguments.
3478   *
3479   * @since 3.9.0
3480   * @access private
3481   *
3482   * @param string $type Optional. Post type to retrieve count Default 'post'.
3483   * @param string $perm Optional. 'readable' or empty. Default empty.
3484   * @return string The cache key.
3485   */
3486  function _count_posts_cache_key( $type = 'post', $perm = '' ) {
3487      $cache_key = 'posts-' . $type;
3488  
3489      if ( 'readable' === $perm && is_user_logged_in() ) {
3490          $post_type_object = get_post_type_object( $type );
3491  
3492          if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
3493              $cache_key .= '_' . $perm . '_' . get_current_user_id();
3494          }
3495      }
3496  
3497      return $cache_key;
3498  }
3499  
3500  /**
3501   * Counts number of posts of a post type and if user has permissions to view.
3502   *
3503   * This function provides an efficient method of finding the amount of post's
3504   * type a blog has. Another method is to count the amount of items in
3505   * get_posts(), but that method has a lot of overhead with doing so. Therefore,
3506   * when developing for 2.5+, use this function instead.
3507   *
3508   * The $perm parameter checks for 'readable' value and if the user can read
3509   * private posts, it will display that for the user that is signed in.
3510   *
3511   * @since 2.5.0
3512   *
3513   * @global wpdb $wpdb WordPress database abstraction object.
3514   *
3515   * @param string $type Optional. Post type to retrieve count. Default 'post'.
3516   * @param string $perm Optional. 'readable' or empty. Default empty.
3517   * @return stdClass An object containing the number of posts for each status,
3518   *                  or an empty object if the post type does not exist.
3519   */
3520  function wp_count_posts( $type = 'post', $perm = '' ) {
3521      global $wpdb;
3522  
3523      if ( ! post_type_exists( $type ) ) {
3524          return new stdClass();
3525      }
3526  
3527      /**
3528       * Filters the post counts before the query is run.
3529       *
3530       * Returning a non-null value short-circuits wp_count_posts(), skipping both
3531       * the object cache lookup and the database query. This allows the counts to
3532       * be served from another source, such as a value pre-computed in the
3533       * background, when an exact real-time count is not required.
3534       *
3535       * Any registered post status missing from the filtered value are added
3536       * to the result and set to zero.
3537       *
3538       * The returned value is not cached and passed through the
3539       * {@see 'wp_count_posts'} filter.
3540       *
3541       * @since 7.2.0
3542       *
3543       * @param stdClass|null $counts An object containing the post counts by status,
3544       *                              or null to run the default query. Default null.
3545       * @param string        $type   Post type.
3546       * @param string        $perm   The permission to determine if the posts are 'readable'
3547       *                              by the current user.
3548       */
3549      $counts = apply_filters( 'pre_wp_count_posts', null, $type, $perm );
3550  
3551      if ( null !== $counts ) {
3552          $counts = (object) $counts;
3553  
3554          foreach ( get_post_stati() as $status ) {
3555              if ( ! isset( $counts->{$status} ) ) {
3556                  $counts->{$status} = 0;
3557              }
3558          }
3559  
3560          /** This filter is documented in wp-includes/post.php */
3561          return apply_filters( 'wp_count_posts', $counts, $type, $perm );
3562      }
3563  
3564      $cache_key = _count_posts_cache_key( $type, $perm );
3565  
3566      $counts = wp_cache_get( $cache_key, 'counts' );
3567      if ( false !== $counts ) {
3568          // We may have cached this before every status was registered.
3569          foreach ( get_post_stati() as $status ) {
3570              if ( ! isset( $counts->{$status} ) ) {
3571                  $counts->{$status} = 0;
3572              }
3573          }
3574  
3575          /** This filter is documented in wp-includes/post.php */
3576          return apply_filters( 'wp_count_posts', $counts, $type, $perm );
3577      }
3578  
3579      if (
3580          'readable' === $perm &&
3581          is_user_logged_in() &&
3582          ! current_user_can( get_post_type_object( $type )->cap->read_private_posts )
3583      ) {
3584          // Optimized query uses subqueries which can leverage DB indexes for better performance. See #61097.
3585          $query = "
3586              SELECT post_status, COUNT(*) AS num_posts
3587              FROM (
3588                  SELECT post_status
3589                  FROM {$wpdb->posts}
3590                  WHERE post_type = %s AND post_status != 'private'
3591                  UNION ALL
3592                  SELECT post_status
3593                  FROM {$wpdb->posts}
3594                  WHERE post_type = %s AND post_status = 'private' AND post_author = %d
3595              ) AS filtered_posts
3596          ";
3597          $args  = array( $type, $type, get_current_user_id() );
3598      } else {
3599          $query = "
3600              SELECT post_status, COUNT(*) AS num_posts
3601              FROM {$wpdb->posts}
3602              WHERE post_type = %s
3603          ";
3604          $args  = array( $type );
3605      }
3606  
3607      $query .= ' GROUP BY post_status';
3608  
3609      $results = (array) $wpdb->get_results(
3610          $wpdb->prepare( $query, ...$args ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are used in the string contained in the variable.
3611          ARRAY_A
3612      );
3613      $counts  = array_fill_keys( get_post_stati(), 0 );
3614  
3615      foreach ( $results as $row ) {
3616          $counts[ $row['post_status'] ] = $row['num_posts'];
3617      }
3618  
3619      $counts = (object) $counts;
3620      wp_cache_set( $cache_key, $counts, 'counts' );
3621  
3622      /**
3623       * Filters the post counts by status for the current post type.
3624       *
3625       * @since 3.7.0
3626       *
3627       * @param stdClass $counts An object containing the current post_type's post
3628       *                         counts by status.
3629       * @param string   $type   Post type.
3630       * @param string   $perm   The permission to determine if the posts are 'readable'
3631       *                         by the current user.
3632       */
3633      return apply_filters( 'wp_count_posts', $counts, $type, $perm );
3634  }
3635  
3636  /**
3637   * Counts number of attachments for the mime type(s).
3638   *
3639   * If you set the optional mime_type parameter, then an array will still be
3640   * returned, but will only have the item you are looking for. It does not give
3641   * you the number of attachments that are children of a post. You can get that
3642   * by counting the number of children that post has.
3643   *
3644   * @since 2.5.0
3645   *
3646   * @global wpdb $wpdb WordPress database abstraction object.
3647   *
3648   * @param string|string[] $mime_type Optional. Array or comma-separated list of
3649   *                                   MIME patterns. Default empty.
3650   * @return stdClass An object containing the attachment counts by mime type.
3651   */
3652  function wp_count_attachments( $mime_type = '' ) {
3653      global $wpdb;
3654  
3655      $cache_key = sprintf(
3656          'attachments%s',
3657          ! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : ''
3658      );
3659  
3660      $counts = wp_cache_get( $cache_key, 'counts' );
3661  
3662      if ( false === $counts ) {
3663          $and   = wp_post_mime_type_where( $mime_type );
3664          $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 );
3665  
3666          $counts = array();
3667          foreach ( (array) $count as $row ) {
3668              $counts[ $row['post_mime_type'] ] = $row['num_posts'];
3669          }
3670          $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
3671  
3672          wp_cache_set( $cache_key, (object) $counts, 'counts' );
3673      }
3674  
3675      /**
3676       * Filters the attachment counts by mime type.
3677       *
3678       * @since 3.7.0
3679       *
3680       * @param stdClass        $counts    An object containing the attachment counts by
3681       *                                   mime type.
3682       * @param string|string[] $mime_type Array or comma-separated list of MIME patterns.
3683       */
3684      return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
3685  }
3686  
3687  /**
3688   * Gets default post mime types.
3689   *
3690   * @since 2.9.0
3691   * @since 5.3.0 Added the 'Documents', 'Spreadsheets', and 'Archives' mime type groups.
3692   *
3693   * @return array<string, array{0: string, 1: string, 2: array}> List of post mime types, keyed by mime type group
3694   *                                                              or by a comma-separated list of mime types. Each
3695   *                                                              value is a three-item array: the plural name of the
3696   *                                                              group, the label for its "Manage" screen, and the
3697   *                                                              translatable count strings returned by _n_noop().
3698   *
3699   * @phpstan-return array<string, array{
3700   *     0: string,
3701   *     1: string,
3702   *     2: array{
3703   *         singular: literal-string,
3704   *         plural: literal-string,
3705   *         context: literal-string|null,
3706   *         domain: literal-string|null,
3707   *         ...
3708   *     },
3709   * }>
3710   */
3711  function get_post_mime_types() {
3712      $post_mime_types = array(   // array( adj, noun )
3713          'image'       => array(
3714              __( 'Images' ),
3715              __( 'Manage Images' ),
3716              /* translators: %s: Number of images. */
3717              _n_noop(
3718                  'Image <span class="count">(%s)</span>',
3719                  'Images <span class="count">(%s)</span>'
3720              ),
3721          ),
3722          'audio'       => array(
3723              _x( 'Audio', 'file type group' ),
3724              __( 'Manage Audio' ),
3725              /* translators: %s: Number of audio files. */
3726              _n_noop(
3727                  'Audio <span class="count">(%s)</span>',
3728                  'Audio <span class="count">(%s)</span>'
3729              ),
3730          ),
3731          'video'       => array(
3732              _x( 'Video', 'file type group' ),
3733              __( 'Manage Video' ),
3734              /* translators: %s: Number of video files. */
3735              _n_noop(
3736                  'Video <span class="count">(%s)</span>',
3737                  'Video <span class="count">(%s)</span>'
3738              ),
3739          ),
3740          'document'    => array(
3741              __( 'Documents' ),
3742              __( 'Manage Documents' ),
3743              /* translators: %s: Number of documents. */
3744              _n_noop(
3745                  'Document <span class="count">(%s)</span>',
3746                  'Documents <span class="count">(%s)</span>'
3747              ),
3748          ),
3749          'spreadsheet' => array(
3750              __( 'Spreadsheets' ),
3751              __( 'Manage Spreadsheets' ),
3752              /* translators: %s: Number of spreadsheets. */
3753              _n_noop(
3754                  'Spreadsheet <span class="count">(%s)</span>',
3755                  'Spreadsheets <span class="count">(%s)</span>'
3756              ),
3757          ),
3758          'archive'     => array(
3759              _x( 'Archives', 'file type group' ),
3760              __( 'Manage Archives' ),
3761              /* translators: %s: Number of archives. */
3762              _n_noop(
3763                  'Archive <span class="count">(%s)</span>',
3764                  'Archives <span class="count">(%s)</span>'
3765              ),
3766          ),
3767      );
3768  
3769      $ext_types  = wp_get_ext_types();
3770      $mime_types = wp_get_mime_types();
3771  
3772      foreach ( $post_mime_types as $group => $labels ) {
3773          if ( in_array( $group, array( 'image', 'audio', 'video' ), true ) ) {
3774              continue;
3775          }
3776  
3777          if ( ! isset( $ext_types[ $group ] ) ) {
3778              unset( $post_mime_types[ $group ] );
3779              continue;
3780          }
3781  
3782          $group_mime_types = array();
3783          foreach ( $ext_types[ $group ] as $extension ) {
3784              foreach ( $mime_types as $exts => $mime ) {
3785                  if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
3786                      $group_mime_types[] = $mime;
3787                      break;
3788                  }
3789              }
3790          }
3791          $group_mime_types = implode( ',', array_unique( $group_mime_types ) );
3792  
3793          $post_mime_types[ $group_mime_types ] = $labels;
3794          unset( $post_mime_types[ $group ] );
3795      }
3796  
3797      /**
3798       * Filters the default list of post mime types.
3799       *
3800       * @since 2.5.0
3801       *
3802       * @param array<string, array{0: string, 1: string, 2: array}> $post_mime_types Default list of post mime types.
3803       *                                                                              See {@see get_post_mime_types()}.
3804       *
3805       * @phpstan-param array<string, array{
3806       *     0: string,
3807       *     1: string,
3808       *     2: array{
3809       *         singular: literal-string,
3810       *         plural: literal-string,
3811       *         context: literal-string|null,
3812       *         domain: literal-string|null,
3813       *         ...
3814       *     },
3815       * }> $post_mime_types
3816       */
3817      return apply_filters( 'post_mime_types', $post_mime_types );
3818  }
3819  
3820  /**
3821   * Checks a MIME-Type against a list.
3822   *
3823   * If the `$wildcard_mime_types` parameter is a string, it must be comma separated
3824   * list. If the `$real_mime_types` is a string, it is also comma separated to
3825   * create the list.
3826   *
3827   * @since 2.5.0
3828   *
3829   * @param string|string[] $wildcard_mime_types Mime types, e.g. `audio/mpeg`, `image` (same as `image/*`),
3830   *                                             or `flash` (same as `*flash*`).
3831   * @param string|string[] $real_mime_types     Real post mime type values.
3832   * @return array array(wildcard=>array(real types)).
3833   */
3834  function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
3835      $matches = array();
3836      if ( is_string( $wildcard_mime_types ) ) {
3837          $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
3838      }
3839      if ( is_string( $real_mime_types ) ) {
3840          $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
3841      }
3842  
3843      $patternses = array();
3844      $wild       = '[-._a-z0-9]*';
3845  
3846      foreach ( (array) $wildcard_mime_types as $type ) {
3847          $mimes = array_map( 'trim', explode( ',', $type ) );
3848          foreach ( $mimes as $mime ) {
3849              $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
3850  
3851              $patternses[][ $type ] = "^$regex$";
3852  
3853              if ( ! str_contains( $mime, '/' ) ) {
3854                  $patternses[][ $type ] = "^$regex/";
3855                  $patternses[][ $type ] = $regex;
3856              }
3857          }
3858      }
3859      asort( $patternses );
3860  
3861      foreach ( $patternses as $patterns ) {
3862          foreach ( $patterns as $type => $pattern ) {
3863              foreach ( (array) $real_mime_types as $real ) {
3864                  if ( preg_match( "#$pattern#", $real )
3865                      && ( empty( $matches[ $type ] ) || ! in_array( $real, $matches[ $type ], true ) )
3866                  ) {
3867                      $matches[ $type ][] = $real;
3868                  }
3869              }
3870          }
3871      }
3872  
3873      return $matches;
3874  }
3875  
3876  /**
3877   * Converts MIME types into SQL.
3878   *
3879   * @since 2.5.0
3880   *
3881   * @param string|string[] $post_mime_types List of mime types or comma separated string
3882   *                                         of mime types.
3883   * @param string          $table_alias     Optional. Specify a table alias, if needed.
3884   *                                         Default empty.
3885   * @return string The SQL AND clause for mime searching.
3886   */
3887  function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
3888      $where     = '';
3889      $wildcards = array( '', '%', '%/%' );
3890      if ( is_string( $post_mime_types ) ) {
3891          $post_mime_types = array_map( 'trim', explode( ',', $post_mime_types ) );
3892      }
3893  
3894      $where_clauses = array();
3895  
3896      foreach ( (array) $post_mime_types as $mime_type ) {
3897          $mime_type = preg_replace( '/\s/', '', $mime_type );
3898          $slashpos  = strpos( $mime_type, '/' );
3899          if ( false !== $slashpos ) {
3900              $mime_group    = preg_replace( '/[^-*.a-zA-Z0-9]/', '', substr( $mime_type, 0, $slashpos ) );
3901              $mime_subgroup = preg_replace( '/[^-*.+a-zA-Z0-9]/', '', substr( $mime_type, $slashpos + 1 ) );
3902              if ( empty( $mime_subgroup ) ) {
3903                  $mime_subgroup = '*';
3904              } else {
3905                  $mime_subgroup = str_replace( '/', '', $mime_subgroup );
3906              }
3907              $mime_pattern = "$mime_group/$mime_subgroup";
3908          } else {
3909              $mime_pattern = preg_replace( '/[^-*.a-zA-Z0-9]/', '', $mime_type );
3910              if ( ! str_contains( $mime_pattern, '*' ) ) {
3911                  $mime_pattern .= '/*';
3912              }
3913          }
3914  
3915          $mime_pattern = preg_replace( '/\*+/', '%', $mime_pattern );
3916  
3917          if ( in_array( $mime_type, $wildcards, true ) ) {
3918              return '';
3919          }
3920  
3921          if ( str_contains( $mime_pattern, '%' ) ) {
3922              $where_clauses[] = empty( $table_alias ) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
3923          } else {
3924              $where_clauses[] = empty( $table_alias ) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
3925          }
3926      }
3927  
3928      if ( ! empty( $where_clauses ) ) {
3929          $where = ' AND (' . implode( ' OR ', $where_clauses ) . ') ';
3930      }
3931  
3932      return $where;
3933  }
3934  
3935  /**
3936   * Trashes or deletes a post or page.
3937   *
3938   * When the post and page is permanently deleted, everything that is tied to
3939   * it is deleted also. This includes comments, post meta fields, and terms
3940   * associated with the post.
3941   *
3942   * The post or page is moved to Trash instead of permanently deleted unless
3943   * Trash is disabled, item is already in the Trash, or $force_delete is true.
3944   *
3945   * @since 1.0.0
3946   *
3947   * @global wpdb $wpdb WordPress database abstraction object.
3948   * @see wp_delete_attachment()
3949   * @see wp_trash_post()
3950   *
3951   * @param int  $post_id      Post ID. (The default of 0 is for historical reasons; providing it is incorrect.)
3952   * @param bool $force_delete Optional. Whether to bypass Trash and force deletion.
3953   *                           Default false.
3954   * @return WP_Post|false|null Post data on success, false or null on failure.
3955   */
3956  function wp_delete_post( $post_id = 0, $force_delete = false ) {
3957      global $wpdb;
3958  
3959      $post_id = (int) $post_id;
3960      if ( $post_id <= 0 ) {
3961          _doing_it_wrong( __FUNCTION__, __( 'The post ID must be greater than 0.' ), '6.9.0' );
3962          return false;
3963      }
3964  
3965      $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) );
3966  
3967      if ( ! $post ) {
3968          return $post;
3969      }
3970  
3971      $post = get_post( $post );
3972  
3973      if ( ! $force_delete
3974          && ( 'post' === $post->post_type || 'page' === $post->post_type )
3975          && 'trash' !== get_post_status( $post_id ) && EMPTY_TRASH_DAYS
3976      ) {
3977          return wp_trash_post( $post_id );
3978      }
3979  
3980      if ( 'attachment' === $post->post_type ) {
3981          return wp_delete_attachment( $post_id, $force_delete );
3982      }
3983  
3984      /**
3985       * Filters whether a post deletion should take place.
3986       *
3987       * @since 4.4.0
3988       *
3989       * @param WP_Post|false|null $check        Whether to go forward with deletion. Anything other than null will short-circuit deletion.
3990       * @param WP_Post            $post         Post object.
3991       * @param bool               $force_delete Whether to bypass the Trash.
3992       */
3993      $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
3994      if ( null !== $check ) {
3995          return $check;
3996      }
3997  
3998      /**
3999       * Fires before a post is deleted, at the start of wp_delete_post().
4000       *
4001       * @since 3.2.0
4002       * @since 5.5.0 Added the `$post` parameter.
4003       *
4004       * @see wp_delete_post()
4005       *
4006       * @param int     $post_id Post ID.
4007       * @param WP_Post $post    Post object.
4008       */
4009      do_action( 'before_delete_post', $post_id, $post );
4010  
4011      delete_post_meta( $post_id, '_wp_trash_meta_status' );
4012      delete_post_meta( $post_id, '_wp_trash_meta_time' );
4013  
4014      wp_delete_object_term_relationships( $post_id, get_object_taxonomies( $post->post_type ) );
4015  
4016      $parent_data  = array( 'post_parent' => $post->post_parent );
4017      $parent_where = array( 'post_parent' => $post_id );
4018  
4019      if ( is_post_type_hierarchical( $post->post_type ) ) {
4020          // Point children of this page to its parent, also clean the cache of affected children.
4021          $children_query = $wpdb->prepare(
4022              "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s",
4023              $post_id,
4024              $post->post_type
4025          );
4026  
4027          $children = $wpdb->get_results( $children_query );
4028  
4029          if ( $children ) {
4030              $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
4031          }
4032      }
4033  
4034      // Do raw query. wp_get_post_revisions() is filtered.
4035      $revision_ids = $wpdb->get_col(
4036          $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $post_id )
4037      );
4038  
4039      // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
4040      foreach ( $revision_ids as $revision_id ) {
4041          wp_delete_post_revision( $revision_id );
4042      }
4043  
4044      // Point all attachments to this post up one level.
4045      $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
4046  
4047      wp_defer_comment_counting( true );
4048  
4049      $comment_ids = $wpdb->get_col(
4050          $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d ORDER BY comment_ID DESC", $post_id )
4051      );
4052  
4053      foreach ( $comment_ids as $comment_id ) {
4054          wp_delete_comment( $comment_id, true );
4055      }
4056  
4057      wp_defer_comment_counting( false );
4058  
4059      $post_meta_ids = $wpdb->get_col(
4060          $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id )
4061      );
4062  
4063      foreach ( $post_meta_ids as $mid ) {
4064          delete_metadata_by_mid( 'post', $mid );
4065      }
4066  
4067      /**
4068       * Fires immediately before a post is deleted from the database.
4069       *
4070       * The dynamic portion of the hook name, `$post->post_type`, refers to
4071       * the post type slug.
4072       *
4073       * @since 6.6.0
4074       *
4075       * @param int     $post_id Post ID.
4076       * @param WP_Post $post    Post object.
4077       */
4078      do_action( "delete_post_{$post->post_type}", $post_id, $post );
4079  
4080      /**
4081       * Fires immediately before a post is deleted from the database.
4082       *
4083       * @since 1.2.0
4084       * @since 5.5.0 Added the `$post` parameter.
4085       *
4086       * @param int     $post_id Post ID.
4087       * @param WP_Post $post    Post object.
4088       */
4089      do_action( 'delete_post', $post_id, $post );
4090  
4091      $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4092      if ( ! $result ) {
4093          return false;
4094      }
4095  
4096      /**
4097       * Fires immediately after a post is deleted from the database.
4098       *
4099       * The dynamic portion of the hook name, `$post->post_type`, refers to
4100       * the post type slug.
4101       *
4102       * @since 6.6.0
4103       *
4104       * @param int     $post_id Post ID.
4105       * @param WP_Post $post    Post object.
4106       */
4107      do_action( "deleted_post_{$post->post_type}", $post_id, $post );
4108  
4109      /**
4110       * Fires immediately after a post is deleted from the database.
4111       *
4112       * @since 2.2.0
4113       * @since 5.5.0 Added the `$post` parameter.
4114       *
4115       * @param int     $post_id Post ID.
4116       * @param WP_Post $post    Post object.
4117       */
4118      do_action( 'deleted_post', $post_id, $post );
4119  
4120      clean_post_cache( $post );
4121  
4122      if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
4123          foreach ( $children as $child ) {
4124              clean_post_cache( $child );
4125          }
4126      }
4127  
4128      wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) );
4129  
4130      /**
4131       * Fires after a post is deleted, at the conclusion of wp_delete_post().
4132       *
4133       * @since 3.2.0
4134       * @since 5.5.0 Added the `$post` parameter.
4135       *
4136       * @see wp_delete_post()
4137       *
4138       * @param int     $post_id Post ID.
4139       * @param WP_Post $post    Post object.
4140       */
4141      do_action( 'after_delete_post', $post_id, $post );
4142  
4143      return $post;
4144  }
4145  
4146  /**
4147   * Resets the page_on_front, show_on_front, and page_for_post settings when
4148   * a linked page is deleted or trashed.
4149   *
4150   * Also ensures the post is no longer sticky.
4151   *
4152   * @since 3.7.0
4153   * @access private
4154   *
4155   * @param int $post_id Post ID.
4156   */
4157  function _reset_front_page_settings_for_post( $post_id ) {
4158      $post = get_post( $post_id );
4159  
4160      if ( 'page' === $post->post_type ) {
4161          /*
4162           * If the page is defined in option page_on_front or post_for_posts,
4163           * adjust the corresponding options.
4164           */
4165          if ( (int) get_option( 'page_on_front' ) === $post->ID ) {
4166              update_option( 'show_on_front', 'posts' );
4167              update_option( 'page_on_front', 0 );
4168          }
4169          if ( (int) get_option( 'page_for_posts' ) === $post->ID ) {
4170              update_option( 'page_for_posts', 0 );
4171          }
4172      }
4173  
4174      unstick_post( $post->ID );
4175  }
4176  
4177  /**
4178   * Resets the Privacy Policy page ID option when the Privacy Policy page
4179   * is permanently deleted, to prevent uncached database queries for a
4180   * non-existent page.
4181   *
4182   * @since 7.1.0
4183   * @access private
4184   *
4185   * @param int $post_id The ID of the post being deleted.
4186   */
4187  function _reset_privacy_policy_page_for_post( int $post_id ): void {
4188      if ( 'page' === get_post_type( $post_id ) && ( (int) get_option( 'wp_page_for_privacy_policy' ) === $post_id ) ) {
4189          update_option( 'wp_page_for_privacy_policy', 0 );
4190      }
4191  }
4192  
4193  /**
4194   * Moves a post or page to the Trash
4195   *
4196   * If Trash is disabled, the post or page is permanently deleted.
4197   *
4198   * @since 2.9.0
4199   *
4200   * @see wp_delete_post()
4201   *
4202   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`
4203   *                     if `EMPTY_TRASH_DAYS` equals true.
4204   * @return WP_Post|false|null Post data on success, false or null on failure.
4205   */
4206  function wp_trash_post( $post_id = 0 ) {
4207      if ( ! EMPTY_TRASH_DAYS ) {
4208          return wp_delete_post( $post_id, true );
4209      }
4210  
4211      $post = get_post( $post_id );
4212  
4213      if ( ! $post ) {
4214          return $post;
4215      }
4216  
4217      if ( 'trash' === $post->post_status ) {
4218          return false;
4219      }
4220  
4221      $previous_status = $post->post_status;
4222  
4223      /**
4224       * Filters whether a post trashing should take place.
4225       *
4226       * @since 4.9.0
4227       * @since 6.3.0 Added the `$previous_status` parameter.
4228       *
4229       * @param bool|null $trash           Whether to go forward with trashing.
4230       * @param WP_Post   $post            Post object.
4231       * @param string    $previous_status The status of the post about to be trashed.
4232       */
4233      $check = apply_filters( 'pre_trash_post', null, $post, $previous_status );
4234  
4235      if ( null !== $check ) {
4236          return $check;
4237      }
4238  
4239      /**
4240       * Fires before a post is sent to the Trash.
4241       *
4242       * @since 3.3.0
4243       * @since 6.3.0 Added the `$previous_status` parameter.
4244       *
4245       * @param int    $post_id         Post ID.
4246       * @param string $previous_status The status of the post about to be trashed.
4247       */
4248      do_action( 'wp_trash_post', $post_id, $previous_status );
4249  
4250      add_post_meta( $post_id, '_wp_trash_meta_status', $previous_status );
4251      add_post_meta( $post_id, '_wp_trash_meta_time', time() );
4252  
4253      $post_updated = wp_update_post(
4254          array(
4255              'ID'          => $post_id,
4256              'post_status' => 'trash',
4257          )
4258      );
4259  
4260      if ( ! $post_updated ) {
4261          return false;
4262      }
4263  
4264      wp_trash_post_comments( $post_id );
4265  
4266      /**
4267       * Fires after a post is sent to the Trash.
4268       *
4269       * @since 2.9.0
4270       * @since 6.3.0 Added the `$previous_status` parameter.
4271       *
4272       * @param int    $post_id         Post ID.
4273       * @param string $previous_status The status of the post at the point where it was trashed.
4274       */
4275      do_action( 'trashed_post', $post_id, $previous_status );
4276  
4277      return $post;
4278  }
4279  
4280  /**
4281   * Restores a post from the Trash.
4282   *
4283   * @since 2.9.0
4284   * @since 5.6.0 An untrashed post is now returned to 'draft' status by default, except for
4285   *              attachments which are returned to their original 'inherit' status.
4286   *
4287   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
4288   * @return WP_Post|false|null Post data on success, false or null on failure.
4289   */
4290  function wp_untrash_post( $post_id = 0 ) {
4291      $post = get_post( $post_id );
4292  
4293      if ( ! $post ) {
4294          return $post;
4295      }
4296  
4297      $post_id = $post->ID;
4298  
4299      if ( 'trash' !== $post->post_status ) {
4300          return false;
4301      }
4302  
4303      $previous_status = get_post_meta( $post_id, '_wp_trash_meta_status', true );
4304  
4305      /**
4306       * Filters whether a post untrashing should take place.
4307       *
4308       * @since 4.9.0
4309       * @since 5.6.0 Added the `$previous_status` parameter.
4310       *
4311       * @param bool|null $untrash         Whether to go forward with untrashing.
4312       * @param WP_Post   $post            Post object.
4313       * @param string    $previous_status The status of the post at the point where it was trashed.
4314       */
4315      $check = apply_filters( 'pre_untrash_post', null, $post, $previous_status );
4316      if ( null !== $check ) {
4317          return $check;
4318      }
4319  
4320      /**
4321       * Fires before a post is restored from the Trash.
4322       *
4323       * @since 2.9.0
4324       * @since 5.6.0 Added the `$previous_status` parameter.
4325       *
4326       * @param int    $post_id         Post ID.
4327       * @param string $previous_status The status of the post at the point where it was trashed.
4328       */
4329      do_action( 'untrash_post', $post_id, $previous_status );
4330  
4331      $new_status = ( 'attachment' === $post->post_type ) ? 'inherit' : 'draft';
4332  
4333      /**
4334       * Filters the status that a post gets assigned when it is restored from the trash (untrashed).
4335       *
4336       * By default posts that are restored will be assigned a status of 'draft'. Return the value of `$previous_status`
4337       * in order to assign the status that the post had before it was trashed. The `wp_untrash_post_set_previous_status()`
4338       * function is available for this.
4339       *
4340       * Prior to WordPress 5.6.0, restored posts were always assigned their original status.
4341       *
4342       * @since 5.6.0
4343       *
4344       * @param string $new_status      The new status of the post being restored.
4345       * @param int    $post_id         The ID of the post being restored.
4346       * @param string $previous_status The status of the post at the point where it was trashed.
4347       */
4348      $post_status = apply_filters( 'wp_untrash_post_status', $new_status, $post_id, $previous_status );
4349  
4350      delete_post_meta( $post_id, '_wp_trash_meta_status' );
4351      delete_post_meta( $post_id, '_wp_trash_meta_time' );
4352  
4353      $post_updated = wp_update_post(
4354          array(
4355              'ID'          => $post_id,
4356              'post_status' => $post_status,
4357          )
4358      );
4359  
4360      if ( ! $post_updated ) {
4361          return false;
4362      }
4363  
4364      wp_untrash_post_comments( $post_id );
4365  
4366      /**
4367       * Fires after a post is restored from the Trash.
4368       *
4369       * @since 2.9.0
4370       * @since 5.6.0 Added the `$previous_status` parameter.
4371       *
4372       * @param int    $post_id         Post ID.
4373       * @param string $previous_status The status of the post at the point where it was trashed.
4374       */
4375      do_action( 'untrashed_post', $post_id, $previous_status );
4376  
4377      return $post;
4378  }
4379  
4380  /**
4381   * Moves comments for a post to the Trash.
4382   *
4383   * @since 2.9.0
4384   *
4385   * @global wpdb $wpdb WordPress database abstraction object.
4386   *
4387   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
4388   * @return int|false|null int if the comments were successfully deleted, false on failure and null if the post or comment did not exist.
4389   */
4390  function wp_trash_post_comments( $post = null ) {
4391      global $wpdb;
4392  
4393      $post = get_post( $post );
4394  
4395      if ( ! $post ) {
4396          return null;
4397      }
4398  
4399      $post_id = $post->ID;
4400  
4401      /**
4402       * Fires before comments are sent to the Trash.
4403       *
4404       * @since 2.9.0
4405       *
4406       * @param int $post_id Post ID.
4407       */
4408      do_action( 'trash_post_comments', $post_id );
4409  
4410      $comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ) );
4411  
4412      if ( ! $comments ) {
4413          return null;
4414      }
4415  
4416      // Cache current status for each comment.
4417      $statuses = array();
4418      foreach ( $comments as $comment ) {
4419          $statuses[ $comment->comment_ID ] = $comment->comment_approved;
4420      }
4421      add_post_meta( $post_id, '_wp_trash_meta_comments_status', $statuses );
4422  
4423      // Set status for all comments to post-trashed.
4424      $result = $wpdb->update( $wpdb->comments, array( 'comment_approved' => 'post-trashed' ), array( 'comment_post_ID' => $post_id ) );
4425  
4426      clean_comment_cache( array_keys( $statuses ) );
4427  
4428      /**
4429       * Fires after comments are sent to the Trash.
4430       *
4431       * @since 2.9.0
4432       *
4433       * @param int   $post_id  Post ID.
4434       * @param array $statuses Array of comment statuses.
4435       */
4436      do_action( 'trashed_post_comments', $post_id, $statuses );
4437  
4438      return $result;
4439  }
4440  
4441  /**
4442   * Restores comments for a post from the Trash.
4443   *
4444   * @since 2.9.0
4445   *
4446   * @global wpdb $wpdb WordPress database abstraction object.
4447   *
4448   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
4449   * @return true|null
4450   */
4451  function wp_untrash_post_comments( $post = null ) {
4452      global $wpdb;
4453  
4454      $post = get_post( $post );
4455  
4456      if ( ! $post ) {
4457          return null;
4458      }
4459  
4460      $post_id = $post->ID;
4461  
4462      $statuses = get_post_meta( $post_id, '_wp_trash_meta_comments_status', true );
4463  
4464      if ( ! $statuses ) {
4465          return true;
4466      }
4467  
4468      /**
4469       * Fires before comments are restored for a post from the Trash.
4470       *
4471       * @since 2.9.0
4472       *
4473       * @param int $post_id Post ID.
4474       */
4475      do_action( 'untrash_post_comments', $post_id );
4476  
4477      // Restore each comment to its original status.
4478      $group_by_status = array();
4479      foreach ( $statuses as $comment_id => $comment_status ) {
4480          $group_by_status[ $comment_status ][] = $comment_id;
4481      }
4482  
4483      foreach ( $group_by_status as $status => $comments ) {
4484          // Confidence check. This shouldn't happen.
4485          if ( 'post-trashed' === $status ) {
4486              $status = '0';
4487          }
4488          $comments_in = implode( ', ', array_map( 'intval', $comments ) );
4489          $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
4490      }
4491  
4492      clean_comment_cache( array_keys( $statuses ) );
4493  
4494      delete_post_meta( $post_id, '_wp_trash_meta_comments_status' );
4495  
4496      /**
4497       * Fires after comments are restored for a post from the Trash.
4498       *
4499       * @since 2.9.0
4500       *
4501       * @param int $post_id Post ID.
4502       */
4503      do_action( 'untrashed_post_comments', $post_id );
4504  
4505      return null;
4506  }
4507  
4508  /**
4509   * Retrieves the list of categories for a post.
4510   *
4511   * Compatibility layer for themes and plugins. Also an easy layer of abstraction
4512   * away from the complexity of the taxonomy layer.
4513   *
4514   * @since 2.1.0
4515   *
4516   * @see wp_get_object_terms()
4517   *
4518   * @param int   $post_id Optional. The Post ID. Does not default to the ID of the
4519   *                       global $post. Default 0.
4520   * @param array $args    Optional. Category query parameters. Default empty array.
4521   *                       See WP_Term_Query::__construct() for supported arguments.
4522   * @return int[]|WP_Term[]|string[]|string|WP_Error List of categories. An array of category IDs by
4523   *                                                  default, and if the `$fields` argument passed via
4524   *                                                  `$args` is 'ids'. If `$fields` is 'all' or
4525   *                                                  'all_with_object_id', an array of WP_Term objects.
4526   *                                                  If `$fields` is 'names', an array of category names.
4527   *                                                  If `$fields` is 'count', a count thereof as a numeric
4528   *                                                  string. WP_Error object if 'category' taxonomy
4529   *                                                  doesn't exist.
4530   *
4531   * @phpstan-return (
4532   *     $args is array{ fields: 'count', ... }
4533   *         ? numeric-string|WP_Error
4534   *         : ( $args is array{ fields: 'id=>parent', ... }
4535   *             ? array<int, int>|WP_Error
4536   *             : ( $args is array{ fields: 'names'|'slugs', ... }
4537   *                 ? string[]|WP_Error
4538   *                 : ( $args is array{ fields: 'id=>name'|'id=>slug', ... }
4539   *                     ? array<int, string>|WP_Error
4540   *                     : ( $args is array{ fields: 'all'|'all_with_object_id', ... }
4541   *                         ? WP_Term[]|WP_Error
4542   *                         : int[]|WP_Error ) ) ) )
4543   * )
4544   */
4545  function wp_get_post_categories( $post_id = 0, $args = array() ) {
4546      $post_id = (int) $post_id;
4547  
4548      $defaults = array( 'fields' => 'ids' );
4549      $args     = wp_parse_args( $args, $defaults );
4550  
4551      $cats = wp_get_object_terms( $post_id, 'category', $args );
4552      return $cats;
4553  }
4554  
4555  /**
4556   * Retrieves the tags for a post.
4557   *
4558   * There is only one default for this function, called 'fields' and by default
4559   * is set to 'all'. There are other defaults that can be overridden in
4560   * wp_get_object_terms().
4561   *
4562   * @since 2.3.0
4563   *
4564   * @param int   $post_id Optional. The Post ID. Does not default to the ID of the
4565   *                       global $post. Default 0.
4566   * @param array $args    Optional. Tag query parameters. Default empty array.
4567   *                       See WP_Term_Query::__construct() for supported arguments.
4568   * @return WP_Term[]|int[]|string[]|string|WP_Error Array of WP_Term objects on success or empty array if no
4569   *                                                  tags were found. A count thereof as a numeric string if
4570   *                                                  the `$fields` argument passed via `$args` is 'count'.
4571   *                                                  WP_Error object if 'post_tag' taxonomy doesn't exist.
4572   *
4573   * @phpstan-return (
4574   *     $args is array{ fields: 'count', ... }
4575   *         ? numeric-string|WP_Error
4576   *         : ( $args is array{ fields: 'ids'|'tt_ids', ... }
4577   *             ? int[]|WP_Error
4578   *             : ( $args is array{ fields: 'id=>parent', ... }
4579   *                 ? array<int, int>|WP_Error
4580   *                 : ( $args is array{ fields: 'names'|'slugs', ... }
4581   *                     ? string[]|WP_Error
4582   *                     : ( $args is array{ fields: 'id=>name'|'id=>slug', ... }
4583   *                         ? array<int, string>|WP_Error
4584   *                         : WP_Term[]|WP_Error ) ) ) )
4585   * )
4586   */
4587  function wp_get_post_tags( $post_id = 0, $args = array() ) {
4588      return wp_get_post_terms( $post_id, 'post_tag', $args );
4589  }
4590  
4591  /**
4592   * Retrieves the terms for a post.
4593   *
4594   * @since 2.8.0
4595   *
4596   * @param int             $post_id  Optional. The Post ID. Does not default to the ID of the
4597   *                                  global $post. Default 0.
4598   * @param string|string[] $taxonomy Optional. The taxonomy slug or array of slugs for which
4599   *                                  to retrieve terms. Default 'post_tag'.
4600   * @param array           $args     {
4601   *     Optional. Term query parameters. See WP_Term_Query::__construct() for supported arguments.
4602   *
4603   *     @type string $fields Term fields to retrieve. Default 'all'.
4604   * }
4605   * @return WP_Term[]|int[]|string[]|string|WP_Error Array of WP_Term objects on success or empty array if no
4606   *                                                  terms were found. A count thereof as a numeric string if
4607   *                                                  the `$fields` argument passed via `$args` is 'count'.
4608   *                                                  WP_Error object if `$taxonomy` doesn't exist.
4609   *
4610   * @phpstan-return (
4611   *     $args is array{ fields: 'count', ... }
4612   *         ? numeric-string|WP_Error
4613   *         : ( $args is array{ fields: 'ids'|'tt_ids', ... }
4614   *             ? int[]|WP_Error
4615   *             : ( $args is array{ fields: 'id=>parent', ... }
4616   *                 ? array<int, int>|WP_Error
4617   *                 : ( $args is array{ fields: 'names'|'slugs', ... }
4618   *                     ? string[]|WP_Error
4619   *                     : ( $args is array{ fields: 'id=>name'|'id=>slug', ... }
4620   *                         ? array<int, string>|WP_Error
4621   *                         : WP_Term[]|WP_Error ) ) ) )
4622   * )
4623   */
4624  function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
4625      $post_id = (int) $post_id;
4626  
4627      $defaults = array( 'fields' => 'all' );
4628      $args     = wp_parse_args( $args, $defaults );
4629  
4630      $tags = wp_get_object_terms( $post_id, $taxonomy, $args );
4631  
4632      return $tags;
4633  }
4634  
4635  /**
4636   * Retrieves a number of recent posts.
4637   *
4638   * @since 1.0.0
4639   *
4640   * @see get_posts()
4641   *
4642   * @param array  $args   Optional. Arguments to retrieve posts. Default empty array.
4643   * @param string $output Optional. The required return type. One of OBJECT or ARRAY_A, which
4644   *                       correspond to a WP_Post object or an associative array, respectively.
4645   *                       Default ARRAY_A.
4646   * @return array|false Array of recent posts, where the type of each element is determined
4647   *                     by the `$output` parameter. Empty array on failure.
4648   *
4649   * @phpstan-param 'OBJECT'|'ARRAY_A' $output
4650   * @phpstan-return (
4651   *     $output is 'ARRAY_A' ? array<int, non-empty-array<string, mixed>> : WP_Post[]|false
4652   * )
4653   */
4654  function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
4655  
4656      if ( is_numeric( $args ) ) {
4657          _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
4658          $args = array( 'numberposts' => absint( $args ) );
4659      }
4660  
4661      // Set default arguments.
4662      $defaults = array(
4663          'numberposts'      => 10,
4664          'offset'           => 0,
4665          'category'         => 0,
4666          'orderby'          => 'post_date',
4667          'order'            => 'DESC',
4668          'include'          => '',
4669          'exclude'          => '',
4670          'meta_key'         => '',
4671          'meta_value'       => '',
4672          'post_type'        => 'post',
4673          'post_status'      => 'draft, publish, future, pending, private',
4674          'suppress_filters' => true,
4675      );
4676  
4677      /** @var array{ fields: null, ... } $parsed_args */
4678      $parsed_args = wp_parse_args( $args, $defaults );
4679  
4680      $results = get_posts( $parsed_args );
4681  
4682      // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
4683      if ( ARRAY_A === $output ) {
4684          $posts = array();
4685          foreach ( $results as $key => $result ) {
4686              /** @var non-empty-array<string, mixed> $object_vars */
4687              $object_vars   = get_object_vars( $result );
4688              $posts[ $key ] = $object_vars;
4689          }
4690          return $posts;
4691      }
4692  
4693      return $results ? $results : false;
4694  }
4695  
4696  /**
4697   * Inserts or updates a post in the database.
4698   *
4699   * If the `$postarr` parameter contains an 'ID', the corresponding post will be updated.
4700   * If not, a new post will be created using the values provided.
4701   *
4702   * You can set the post date manually, by setting the values for 'post_date'
4703   * and 'post_date_gmt' keys. You can close the comments or open the comments by
4704   * setting the value for 'comment_status' key.
4705   *
4706   * @since 1.0.0
4707   * @since 2.6.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
4708   * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
4709   * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
4710   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
4711   *
4712   * @see sanitize_post()
4713   * @global wpdb $wpdb WordPress database abstraction object.
4714   *
4715   * @param array $postarr {
4716   *     An array of elements that make up a post to update or insert.
4717   *
4718   *     @type int    $ID                    The post ID. If equal to something other than 0,
4719   *                                         the post with that ID will be updated. Default 0.
4720   *     @type int    $post_author           The ID of the user who added the post. Default is
4721   *                                         the current user ID.
4722   *     @type string $post_date             The date of the post. Default is the current time.
4723   *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
4724   *                                         the value of `$post_date`.
4725   *     @type string $post_content          The post content. Default empty.
4726   *     @type string $post_content_filtered The filtered post content. Default empty.
4727   *     @type string $post_title            The post title. Default empty.
4728   *     @type string $post_excerpt          The post excerpt. Default empty.
4729   *     @type string $post_status           The post status. Default 'draft'.
4730   *     @type string $post_type             The post type. Default 'post'.
4731   *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
4732   *                                         Default is the value of 'default_comment_status' option.
4733   *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
4734   *                                         Default is the value of 'default_ping_status' option.
4735   *     @type string $post_password         The password to access the post. Default empty.
4736   *     @type string $post_name             The post name. Default is the sanitized post title
4737   *                                         when creating a new post.
4738   *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
4739   *                                         Default empty.
4740   *     @type string $pinged                Space or carriage return-separated list of URLs that have
4741   *                                         been pinged. Default empty.
4742   *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
4743   *     @type int    $menu_order            The order the post should be displayed in. Default 0.
4744   *     @type string $post_mime_type        The mime type of the post. Default empty.
4745   *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
4746   *     @type int    $import_id             The post ID to be used when inserting a new post.
4747   *                                         If specified, must not match any existing post ID. Default 0.
4748   *     @type int[]  $post_category         Array of category IDs.
4749   *                                         Defaults to value of the 'default_category' option.
4750   *     @type array  $tags_input            Array of tag names, slugs, or IDs. Default empty.
4751   *     @type array  $tax_input             An array of taxonomy terms keyed by their taxonomy name.
4752   *                                         If the taxonomy is hierarchical, the term list needs to be
4753   *                                         either an array of term IDs or a comma-separated string of IDs.
4754   *                                         If the taxonomy is non-hierarchical, the term list can be an array
4755   *                                         that contains term names or slugs, or a comma-separated string
4756   *                                         of names or slugs. This is because, in hierarchical taxonomy,
4757   *                                         child terms can have the same names with different parent terms,
4758   *                                         so the only way to connect them is using ID. Default empty.
4759   *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
4760   *     @type string $page_template         Page template to use.
4761   * }
4762   * @param bool  $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
4763   * @param bool  $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
4764   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
4765   *
4766   * @phpstan-return (
4767   *     $wp_error is false ? int : int|WP_Error
4768   * )
4769   */
4770  function wp_insert_post( $postarr, $wp_error = false, $fire_after_hooks = true ) {
4771      global $wpdb;
4772  
4773      // Capture original pre-sanitized array for passing into filters.
4774      $unsanitized_postarr = $postarr;
4775  
4776      $user_id = get_current_user_id();
4777  
4778      $defaults = array(
4779          'post_author'           => $user_id,
4780          'post_content'          => '',
4781          'post_content_filtered' => '',
4782          'post_title'            => '',
4783          'post_excerpt'          => '',
4784          'post_status'           => 'draft',
4785          'post_type'             => 'post',
4786          'comment_status'        => '',
4787          'ping_status'           => '',
4788          'post_password'         => '',
4789          'to_ping'               => '',
4790          'pinged'                => '',
4791          'post_parent'           => 0,
4792          'menu_order'            => 0,
4793          'guid'                  => '',
4794          'import_id'             => 0,
4795          'context'               => '',
4796          'post_date'             => '',
4797          'post_date_gmt'         => '',
4798      );
4799  
4800      $postarr = wp_parse_args( $postarr, $defaults );
4801  
4802      unset( $postarr['filter'] );
4803  
4804      $postarr = sanitize_post( $postarr, 'db' );
4805  
4806      // Are we updating or creating?
4807      $post_id = 0;
4808      $update  = false;
4809      $guid    = $postarr['guid'];
4810  
4811      if ( ! empty( $postarr['ID'] ) ) {
4812          $update = true;
4813  
4814          // Get the post ID and GUID.
4815          $post_id     = $postarr['ID'];
4816          $post_before = get_post( $post_id );
4817  
4818          if ( is_null( $post_before ) ) {
4819              if ( $wp_error ) {
4820                  return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
4821              }
4822              return 0;
4823          }
4824  
4825          $guid            = get_post_field( 'guid', $post_id );
4826          $previous_status = get_post_field( 'post_status', $post_id );
4827      } else {
4828          $previous_status = 'new';
4829          $post_before     = null;
4830      }
4831  
4832      $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
4833  
4834      $post_title   = $postarr['post_title'];
4835      $post_content = $postarr['post_content'];
4836      $post_excerpt = $postarr['post_excerpt'];
4837  
4838      if ( isset( $postarr['post_name'] ) ) {
4839          $post_name = $postarr['post_name'];
4840      } elseif ( $update ) {
4841          // For an update, don't modify the post_name if it wasn't supplied as an argument.
4842          $post_name = $post_before->post_name;
4843      }
4844  
4845      $maybe_empty = 'attachment' !== $post_type
4846          && ! $post_content && ! $post_title && ! $post_excerpt
4847          && post_type_supports( $post_type, 'editor' )
4848          && post_type_supports( $post_type, 'title' )
4849          && post_type_supports( $post_type, 'excerpt' );
4850  
4851      /**
4852       * Filters whether the post should be considered "empty".
4853       *
4854       * The post is considered "empty" if both:
4855       * 1. The post type supports the title, editor, and excerpt fields
4856       * 2. The title, editor, and excerpt fields are all empty
4857       *
4858       * Returning a truthy value from the filter will effectively short-circuit
4859       * the new post being inserted and return 0. If $wp_error is true, a WP_Error
4860       * will be returned instead.
4861       *
4862       * @since 3.3.0
4863       *
4864       * @param bool  $maybe_empty Whether the post should be considered "empty".
4865       * @param array $postarr     Array of post data.
4866       */
4867      if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
4868          if ( $wp_error ) {
4869              return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
4870          } else {
4871              return 0;
4872          }
4873      }
4874  
4875      $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
4876  
4877      if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash', 'auto-draft' ), true ) ) {
4878          $post_status = 'inherit';
4879      }
4880  
4881      if ( ! empty( $postarr['post_category'] ) ) {
4882          // Filter out empty terms.
4883          $post_category = array_filter( $postarr['post_category'] );
4884      } elseif ( $update && ! isset( $postarr['post_category'] ) ) {
4885          $post_category = $post_before->post_category;
4886      }
4887  
4888      // Make sure we set a valid category.
4889      if ( empty( $post_category ) || 0 === count( $post_category ) || ! is_array( $post_category ) ) {
4890          // 'post' requires at least one category.
4891          if ( 'post' === $post_type && 'auto-draft' !== $post_status ) {
4892              $post_category = array( get_option( 'default_category' ) );
4893          } else {
4894              $post_category = array();
4895          }
4896      }
4897  
4898      /*
4899       * Don't allow contributors to set the post slug for pending review posts.
4900       *
4901       * For new posts check the primitive capability, for updates check the meta capability.
4902       */
4903      if ( 'pending' === $post_status ) {
4904          $post_type_object = get_post_type_object( $post_type );
4905  
4906          if ( ! $update && $post_type_object && ! current_user_can( $post_type_object->cap->publish_posts ) ) {
4907              $post_name = '';
4908          } elseif ( $update && ! current_user_can( 'publish_post', $post_id ) ) {
4909              $post_name = '';
4910          }
4911      }
4912  
4913      /*
4914       * Create a valid post name. Drafts and pending posts are allowed to have
4915       * an empty post name.
4916       */
4917      if ( empty( $post_name ) ) {
4918          if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true ) ) {
4919              $post_name = sanitize_title( $post_title );
4920          } else {
4921              $post_name = '';
4922          }
4923      } else {
4924          // On updates, we need to check to see if it's using the old, fixed sanitization context.
4925          $check_name = sanitize_title( $post_name, '', 'old-save' );
4926  
4927          if ( $update
4928              && strtolower( urlencode( $post_name ) ) === $check_name
4929              && get_post_field( 'post_name', $post_id ) === $check_name
4930          ) {
4931              $post_name = $check_name;
4932          } else { // New post, or slug has changed.
4933              $post_name = sanitize_title( $post_name );
4934          }
4935      }
4936  
4937      /*
4938       * Resolve the post date from any provided post date or post date GMT strings;
4939       * if none are provided, the date will be set to now.
4940       */
4941      $post_date = wp_resolve_post_date( $postarr['post_date'], $postarr['post_date_gmt'] );
4942  
4943      if ( ! $post_date ) {
4944          if ( $wp_error ) {
4945              return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
4946          } else {
4947              return 0;
4948          }
4949      }
4950  
4951      if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' === $postarr['post_date_gmt'] ) {
4952          if ( ! in_array( $post_status, get_post_stati( array( 'date_floating' => true ) ), true ) ) {
4953              $post_date_gmt = get_gmt_from_date( $post_date );
4954          } else {
4955              $post_date_gmt = '0000-00-00 00:00:00';
4956          }
4957      } else {
4958          $post_date_gmt = $postarr['post_date_gmt'];
4959      }
4960  
4961      if ( $update || '0000-00-00 00:00:00' === $post_date ) {
4962          $post_modified     = current_time( 'mysql' );
4963          $post_modified_gmt = current_time( 'mysql', true );
4964      } else {
4965          $post_modified     = $post_date;
4966          $post_modified_gmt = $post_date_gmt;
4967      }
4968  
4969      if ( 'attachment' !== $post_type ) {
4970          $now = gmdate( 'Y-m-d H:i:s' );
4971  
4972          if ( 'publish' === $post_status ) {
4973              if ( strtotime( $post_date_gmt ) - strtotime( $now ) >= MINUTE_IN_SECONDS ) {
4974                  $post_status = 'future';
4975              }
4976          } elseif ( 'future' === $post_status ) {
4977              if ( strtotime( $post_date_gmt ) - strtotime( $now ) < MINUTE_IN_SECONDS ) {
4978                  $post_status = 'publish';
4979              }
4980          }
4981      }
4982  
4983      // Comment status.
4984      if ( empty( $postarr['comment_status'] ) ) {
4985          if ( $update ) {
4986              $comment_status = 'closed';
4987          } else {
4988              $comment_status = get_default_comment_status( $post_type );
4989          }
4990      } else {
4991          $comment_status = $postarr['comment_status'];
4992      }
4993  
4994      // These variables are needed by compact() later.
4995      $post_content_filtered = $postarr['post_content_filtered'];
4996      $post_author           = $postarr['post_author'] ?? $user_id;
4997      $ping_status           = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
4998      $to_ping               = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
4999      $pinged                = $postarr['pinged'] ?? '';
5000      $import_id             = $postarr['import_id'] ?? 0;
5001  
5002      /*
5003       * The 'wp_insert_post_parent' filter expects all variables to be present.
5004       * Previously, these variables would have already been extracted
5005       */
5006      if ( isset( $postarr['menu_order'] ) ) {
5007          $menu_order = (int) $postarr['menu_order'];
5008      } else {
5009          $menu_order = 0;
5010      }
5011  
5012      $post_password = $postarr['post_password'] ?? '';
5013      if ( 'private' === $post_status ) {
5014          $post_password = '';
5015      }
5016  
5017      if ( isset( $postarr['post_parent'] ) ) {
5018          $post_parent = (int) $postarr['post_parent'];
5019      } else {
5020          $post_parent = 0;
5021      }
5022  
5023      $new_postarr = array_merge(
5024          array(
5025              'ID' => $post_id,
5026          ),
5027          compact( array_diff( array_keys( $defaults ), array( 'context', 'filter' ) ) )
5028      );
5029  
5030      /**
5031       * Filters the post parent -- used to check for and prevent hierarchy loops.
5032       *
5033       * @since 3.1.0
5034       *
5035       * @param int   $post_parent Post parent ID.
5036       * @param int   $post_id     Post ID.
5037       * @param array $new_postarr Array of parsed post data.
5038       * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
5039       */
5040      $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_id, $new_postarr, $postarr );
5041  
5042      /*
5043       * If the post is being untrashed and it has a desired slug stored in post meta,
5044       * reassign it.
5045       */
5046      if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
5047          $desired_post_slug = get_post_meta( $post_id, '_wp_desired_post_slug', true );
5048  
5049          if ( $desired_post_slug ) {
5050              delete_post_meta( $post_id, '_wp_desired_post_slug' );
5051              $post_name = $desired_post_slug;
5052          }
5053      }
5054  
5055      // If a trashed post has the desired slug, change it and let this post have it.
5056      if ( 'trash' !== $post_status && $post_name ) {
5057          /**
5058           * Filters whether or not to add a `__trashed` suffix to the name of trashed posts that match the name of the updated post.
5059           *
5060           * @since 5.4.0
5061           *
5062           * @param bool   $add_trashed_suffix Whether to attempt to add the suffix.
5063           * @param string $post_name          The name of the post being updated.
5064           * @param int    $post_id            Post ID.
5065           */
5066          $add_trashed_suffix = apply_filters( 'add_trashed_suffix_to_trashed_posts', true, $post_name, $post_id );
5067  
5068          if ( $add_trashed_suffix ) {
5069              wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_id );
5070          }
5071      }
5072  
5073      // When trashing an existing post, change its slug to allow non-trashed posts to use it.
5074      if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
5075          $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_id );
5076      }
5077  
5078      $post_name = wp_unique_post_slug( $post_name, $post_id, $post_status, $post_type, $post_parent );
5079  
5080      // Don't unslash.
5081      $post_mime_type = $postarr['post_mime_type'] ?? '';
5082  
5083      // Expected_slashed (everything!).
5084      $data = compact(
5085          'post_author',
5086          'post_date',
5087          'post_date_gmt',
5088          'post_content',
5089          'post_content_filtered',
5090          'post_title',
5091          'post_excerpt',
5092          'post_status',
5093          'post_type',
5094          'comment_status',
5095          'ping_status',
5096          'post_password',
5097          'post_name',
5098          'to_ping',
5099          'pinged',
5100          'post_modified',
5101          'post_modified_gmt',
5102          'post_parent',
5103          'menu_order',
5104          'post_mime_type',
5105          'guid'
5106      );
5107  
5108      $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
5109  
5110      foreach ( $emoji_fields as $emoji_field ) {
5111          if ( isset( $data[ $emoji_field ] ) ) {
5112              $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
5113  
5114              // The 'utf8' character set is a deprecated alias of 'utf8mb3'. See <https://dev.mysql.com/doc/refman/8.4/en/charset-unicode-utf8.html>.
5115              if ( 'utf8' === $charset || 'utf8mb3' === $charset ) {
5116                  $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
5117              }
5118          }
5119      }
5120  
5121      if ( 'attachment' === $post_type ) {
5122          /**
5123           * Filters attachment post data before it is updated in or added to the database.
5124           *
5125           * @since 3.9.0
5126           * @since 5.4.1 The `$unsanitized_postarr` parameter was added.
5127           * @since 6.0.0 The `$update` parameter was added.
5128           *
5129           * @param array $data                An array of slashed, sanitized, and processed attachment post data.
5130           * @param array $postarr             An array of slashed and sanitized attachment post data, but not processed.
5131           * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed attachment post data
5132           *                                   as originally passed to wp_insert_post().
5133           * @param bool  $update              Whether this is an existing attachment post being updated.
5134           */
5135          $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr, $unsanitized_postarr, $update );
5136      } else {
5137          /**
5138           * Filters slashed post data just before it is inserted into the database.
5139           *
5140           * @since 2.7.0
5141           * @since 5.4.1 The `$unsanitized_postarr` parameter was added.
5142           * @since 6.0.0 The `$update` parameter was added.
5143           *
5144           * @param array $data                An array of slashed, sanitized, and processed post data.
5145           * @param array $postarr             An array of sanitized (and slashed) but otherwise unmodified post data.
5146           * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as
5147           *                                   originally passed to wp_insert_post().
5148           * @param bool  $update              Whether this is an existing post being updated.
5149           */
5150          $data = apply_filters( 'wp_insert_post_data', $data, $postarr, $unsanitized_postarr, $update );
5151      }
5152  
5153      $data  = wp_unslash( $data );
5154      $where = array( 'ID' => $post_id );
5155  
5156      if ( $update ) {
5157          /**
5158           * Fires immediately before an existing post is updated in the database.
5159           *
5160           * @since 2.5.0
5161           *
5162           * @param int   $post_id Post ID.
5163           * @param array $data    Array of unslashed post data.
5164           */
5165          do_action( 'pre_post_update', $post_id, $data );
5166  
5167          if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
5168              if ( $wp_error ) {
5169                  if ( 'attachment' === $post_type ) {
5170                      $message = __( 'Could not update attachment in the database.' );
5171                  } else {
5172                      $message = __( 'Could not update post in the database.' );
5173                  }
5174  
5175                  return new WP_Error( 'db_update_error', $message, $wpdb->last_error );
5176              } else {
5177                  return 0;
5178              }
5179          }
5180      } else {
5181          // If there is a suggested ID, use it if not already present.
5182          if ( ! empty( $import_id ) ) {
5183              $import_id = (int) $import_id;
5184  
5185              if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id ) ) ) {
5186                  $data['ID'] = $import_id;
5187              }
5188          }
5189  
5190          /**
5191           * Fires immediately before a new post is inserted in the database.
5192           *
5193           * @since 6.9.0
5194           *
5195           * @param array $data Array of unslashed post data.
5196           */
5197          do_action( 'pre_post_insert', $data );
5198  
5199          if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
5200              if ( $wp_error ) {
5201                  if ( 'attachment' === $post_type ) {
5202                      $message = __( 'Could not insert attachment into the database.' );
5203                  } else {
5204                      $message = __( 'Could not insert post into the database.' );
5205                  }
5206  
5207                  return new WP_Error( 'db_insert_error', $message, $wpdb->last_error );
5208              } else {
5209                  return 0;
5210              }
5211          }
5212  
5213          $post_id = (int) $wpdb->insert_id;
5214  
5215          // Use the newly generated $post_id.
5216          $where = array( 'ID' => $post_id );
5217      }
5218  
5219      if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ), true ) ) {
5220          $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_id ), $post_id, $data['post_status'], $post_type, $post_parent );
5221  
5222          $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
5223          clean_post_cache( $post_id );
5224      }
5225  
5226      if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
5227          wp_set_post_categories( $post_id, $post_category );
5228      }
5229  
5230      if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
5231          wp_set_post_tags( $post_id, $postarr['tags_input'] );
5232      }
5233  
5234      // Add default term for all associated custom taxonomies.
5235      if ( 'auto-draft' !== $post_status ) {
5236          foreach ( get_object_taxonomies( $post_type, 'object' ) as $taxonomy => $tax_object ) {
5237  
5238              if ( ! empty( $tax_object->default_term ) ) {
5239  
5240                  // Filter out empty terms.
5241                  if ( isset( $postarr['tax_input'][ $taxonomy ] ) && is_array( $postarr['tax_input'][ $taxonomy ] ) ) {
5242                      $postarr['tax_input'][ $taxonomy ] = array_filter( $postarr['tax_input'][ $taxonomy ] );
5243                  }
5244  
5245                  // Passed custom taxonomy list overwrites the existing list if not empty.
5246                  $terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
5247                  if ( ! empty( $terms ) && empty( $postarr['tax_input'][ $taxonomy ] ) ) {
5248                      $postarr['tax_input'][ $taxonomy ] = $terms;
5249                  }
5250  
5251                  if ( empty( $postarr['tax_input'][ $taxonomy ] ) ) {
5252                      $default_term_id = get_option( 'default_term_' . $taxonomy );
5253                      if ( ! empty( $default_term_id ) ) {
5254                          $postarr['tax_input'][ $taxonomy ] = array( (int) $default_term_id );
5255                      }
5256                  }
5257              }
5258          }
5259      }
5260  
5261      // New-style support for all custom taxonomies.
5262      if ( ! empty( $postarr['tax_input'] ) ) {
5263          foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
5264              $taxonomy_obj = get_taxonomy( $taxonomy );
5265  
5266              if ( ! $taxonomy_obj ) {
5267                  /* translators: %s: Taxonomy name. */
5268                  _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
5269                  continue;
5270              }
5271  
5272              // array = hierarchical, string = non-hierarchical.
5273              if ( is_array( $tags ) ) {
5274                  $tags = array_filter( $tags );
5275              }
5276  
5277              if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
5278                  wp_set_post_terms( $post_id, $tags, $taxonomy );
5279              }
5280          }
5281      }
5282  
5283      if ( ! empty( $postarr['meta_input'] ) ) {
5284          foreach ( $postarr['meta_input'] as $field => $value ) {
5285              update_post_meta( $post_id, $field, $value );
5286          }
5287      }
5288  
5289      $current_guid = get_post_field( 'guid', $post_id );
5290  
5291      // Set GUID.
5292      if ( ! $update && '' === $current_guid ) {
5293          $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_id ) ), $where );
5294      }
5295  
5296      if ( 'attachment' === $postarr['post_type'] ) {
5297          if ( ! empty( $postarr['file'] ) ) {
5298              update_attached_file( $post_id, $postarr['file'] );
5299          }
5300  
5301          if ( ! empty( $postarr['context'] ) ) {
5302              add_post_meta( $post_id, '_wp_attachment_context', $postarr['context'], true );
5303          }
5304      }
5305  
5306      // Set or remove featured image.
5307      if ( isset( $postarr['_thumbnail_id'] ) ) {
5308          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
5309  
5310          if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
5311              if ( wp_attachment_is( 'audio', $post_id ) ) {
5312                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
5313              } elseif ( wp_attachment_is( 'video', $post_id ) ) {
5314                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
5315              }
5316          }
5317  
5318          if ( $thumbnail_support ) {
5319              $thumbnail_id = (int) $postarr['_thumbnail_id'];
5320              if ( -1 === $thumbnail_id ) {
5321                  delete_post_thumbnail( $post_id );
5322              } else {
5323                  set_post_thumbnail( $post_id, $thumbnail_id );
5324              }
5325          }
5326      }
5327  
5328      clean_post_cache( $post_id );
5329  
5330      $post = get_post( $post_id );
5331  
5332      if ( ! empty( $postarr['page_template'] ) ) {
5333          $post->page_template = $postarr['page_template'];
5334          $page_templates      = wp_get_theme()->get_page_templates( $post );
5335  
5336          if ( 'default' !== $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
5337              if ( $wp_error ) {
5338                  return new WP_Error( 'invalid_page_template', __( 'Invalid page template.' ) );
5339              }
5340  
5341              update_post_meta( $post_id, '_wp_page_template', 'default' );
5342          } else {
5343              update_post_meta( $post_id, '_wp_page_template', $postarr['page_template'] );
5344          }
5345      }
5346  
5347      if ( 'attachment' !== $postarr['post_type'] ) {
5348          wp_transition_post_status( $data['post_status'], $previous_status, $post );
5349      } else {
5350          if ( $update ) {
5351              /**
5352               * Fires once an existing attachment has been updated.
5353               *
5354               * @since 2.0.0
5355               *
5356               * @param int $post_id Attachment ID.
5357               */
5358              do_action( 'edit_attachment', $post_id );
5359  
5360              $post_after = get_post( $post_id );
5361  
5362              /**
5363               * Fires once an existing attachment has been updated.
5364               *
5365               * @since 4.4.0
5366               *
5367               * @param int     $post_id      Post ID.
5368               * @param WP_Post $post_after   Post object following the update.
5369               * @param WP_Post $post_before  Post object before the update.
5370               */
5371              do_action( 'attachment_updated', $post_id, $post_after, $post_before );
5372          } else {
5373  
5374              /**
5375               * Fires once an attachment has been added.
5376               *
5377               * @since 2.0.0
5378               *
5379               * @param int $post_id Attachment ID.
5380               */
5381              do_action( 'add_attachment', $post_id );
5382          }
5383  
5384          return $post_id;
5385      }
5386  
5387      if ( $update ) {
5388          /**
5389           * Fires once an existing post has been updated.
5390           *
5391           * The dynamic portion of the hook name, `$post->post_type`, refers to
5392           * the post type slug.
5393           *
5394           * Possible hook names include:
5395           *
5396           *  - `edit_post_post`
5397           *  - `edit_post_page`
5398           *
5399           * @since 5.1.0
5400           *
5401           * @param int     $post_id Post ID.
5402           * @param WP_Post $post    Post object.
5403           */
5404          do_action( "edit_post_{$post->post_type}", $post_id, $post );
5405  
5406          /**
5407           * Fires once an existing post has been updated.
5408           *
5409           * @since 1.2.0
5410           *
5411           * @param int     $post_id Post ID.
5412           * @param WP_Post $post    Post object.
5413           */
5414          do_action( 'edit_post', $post_id, $post );
5415  
5416          $post_after = get_post( $post_id );
5417  
5418          /**
5419           * Fires once an existing post has been updated.
5420           *
5421           * @since 3.0.0
5422           *
5423           * @param int     $post_id      Post ID.
5424           * @param WP_Post $post_after   Post object following the update.
5425           * @param WP_Post $post_before  Post object before the update.
5426           */
5427          do_action( 'post_updated', $post_id, $post_after, $post_before );
5428      }
5429  
5430      /**
5431       * Fires once a post has been saved.
5432       *
5433       * The dynamic portion of the hook name, `$post->post_type`, refers to
5434       * the post type slug.
5435       *
5436       * Possible hook names include:
5437       *
5438       *  - `save_post_post`
5439       *  - `save_post_page`
5440       *
5441       * @since 3.7.0
5442       *
5443       * @param int     $post_id Post ID.
5444       * @param WP_Post $post    Post object.
5445       * @param bool    $update  Whether this is an existing post being updated.
5446       */
5447      do_action( "save_post_{$post->post_type}", $post_id, $post, $update );
5448  
5449      /**
5450       * Fires once a post has been saved.
5451       *
5452       * @since 1.5.0
5453       *
5454       * @param int     $post_id Post ID.
5455       * @param WP_Post $post    Post object.
5456       * @param bool    $update  Whether this is an existing post being updated.
5457       */
5458      do_action( 'save_post', $post_id, $post, $update );
5459  
5460      /**
5461       * Fires once a post has been saved.
5462       *
5463       * @since 2.0.0
5464       *
5465       * @param int     $post_id Post ID.
5466       * @param WP_Post $post    Post object.
5467       * @param bool    $update  Whether this is an existing post being updated.
5468       */
5469      do_action( 'wp_insert_post', $post_id, $post, $update );
5470  
5471      if ( $fire_after_hooks ) {
5472          wp_after_insert_post( $post, $update, $post_before );
5473      }
5474  
5475      return $post_id;
5476  }
5477  
5478  /**
5479   * Updates a post with new post data.
5480   *
5481   * The date does not have to be set for drafts. You can set the date and it will
5482   * not be overridden.
5483   *
5484   * @since 1.0.0
5485   * @since 3.5.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
5486   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
5487   *
5488   * @param array|object $postarr          Optional. Post data. Arrays are expected to be escaped,
5489   *                                       objects are not. See wp_insert_post() for accepted arguments.
5490   *                                       Default array.
5491   * @param bool         $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
5492   * @param bool         $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
5493   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
5494   *
5495   * @phpstan-return (
5496   *     $wp_error is false ? int : int|WP_Error
5497   * )
5498   */
5499  function wp_update_post( $postarr = array(), $wp_error = false, $fire_after_hooks = true ) {
5500      if ( is_object( $postarr ) ) {
5501          // Non-escaped post was passed.
5502          $postarr = get_object_vars( $postarr );
5503          $postarr = wp_slash( $postarr );
5504      }
5505  
5506      // First, get all of the original fields.
5507      $post = get_post( $postarr['ID'], ARRAY_A );
5508  
5509      if ( is_null( $post ) ) {
5510          if ( $wp_error ) {
5511              return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
5512          }
5513          return 0;
5514      }
5515  
5516      // Escape data pulled from DB.
5517      $post = wp_slash( $post );
5518  
5519      // Passed post category list overwrites existing category list if not empty.
5520      if ( isset( $postarr['post_category'] ) && is_array( $postarr['post_category'] )
5521          && count( $postarr['post_category'] ) > 0
5522      ) {
5523          $post_cats = $postarr['post_category'];
5524      } else {
5525          $post_cats = $post['post_category'];
5526      }
5527  
5528      // Drafts shouldn't be assigned a date unless explicitly done so by the user.
5529      if ( isset( $post['post_status'] )
5530          && in_array( $post['post_status'], array( 'draft', 'pending', 'auto-draft' ), true )
5531          && empty( $postarr['edit_date'] ) && ( '0000-00-00 00:00:00' === $post['post_date_gmt'] )
5532      ) {
5533          $clear_date = true;
5534      } else {
5535          $clear_date = false;
5536      }
5537  
5538      // Merge old and new fields with new fields overwriting old ones.
5539      $postarr                  = array_merge( $post, $postarr );
5540      $postarr['post_category'] = $post_cats;
5541      if ( $clear_date ) {
5542          $postarr['post_date']     = current_time( 'mysql' );
5543          $postarr['post_date_gmt'] = '';
5544      }
5545  
5546      if ( 'attachment' === $postarr['post_type'] ) {
5547          return wp_insert_attachment( $postarr, false, 0, $wp_error );
5548      }
5549  
5550      // Discard 'tags_input' parameter if it's the same as existing post tags.
5551      if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $postarr['post_type'], 'post_tag' ) ) {
5552          $tags      = get_the_terms( $postarr['ID'], 'post_tag' );
5553          $tag_names = array();
5554  
5555          if ( $tags && ! is_wp_error( $tags ) ) {
5556              $tag_names = wp_list_pluck( $tags, 'name' );
5557          }
5558  
5559          if ( $postarr['tags_input'] === $tag_names ) {
5560              unset( $postarr['tags_input'] );
5561          }
5562      }
5563  
5564      return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
5565  }
5566  
5567  /**
5568   * Publishes a post by transitioning the post status.
5569   *
5570   * @since 2.1.0
5571   *
5572   * @global wpdb $wpdb WordPress database abstraction object.
5573   *
5574   * @param int|WP_Post $post Post ID or post object.
5575   */
5576  function wp_publish_post( $post ) {
5577      global $wpdb;
5578  
5579      $post = get_post( $post );
5580  
5581      if ( ! $post ) {
5582          return;
5583      }
5584  
5585      if ( 'publish' === $post->post_status ) {
5586          return;
5587      }
5588  
5589      $post_before = get_post( $post->ID );
5590  
5591      // Ensure at least one term is applied for taxonomies with a default term.
5592      foreach ( get_object_taxonomies( $post->post_type, 'object' ) as $taxonomy => $tax_object ) {
5593          // Skip taxonomy if no default term is set.
5594          if (
5595              'category' !== $taxonomy &&
5596              empty( $tax_object->default_term )
5597          ) {
5598              continue;
5599          }
5600  
5601          // Do not modify previously set terms.
5602          if ( ! empty( get_the_terms( $post, $taxonomy ) ) ) {
5603              continue;
5604          }
5605  
5606          if ( 'category' === $taxonomy ) {
5607              $default_term_id = (int) get_option( 'default_category', 0 );
5608          } else {
5609              $default_term_id = (int) get_option( 'default_term_' . $taxonomy, 0 );
5610          }
5611  
5612          if ( ! $default_term_id ) {
5613              continue;
5614          }
5615          wp_set_post_terms( $post->ID, array( $default_term_id ), $taxonomy );
5616      }
5617  
5618      $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
5619  
5620      clean_post_cache( $post->ID );
5621  
5622      $old_status        = $post->post_status;
5623      $post->post_status = 'publish';
5624      wp_transition_post_status( 'publish', $old_status, $post );
5625  
5626      /** This action is documented in wp-includes/post.php */
5627      do_action( "edit_post_{$post->post_type}", $post->ID, $post );
5628  
5629      /** This action is documented in wp-includes/post.php */
5630      do_action( 'edit_post', $post->ID, $post );
5631  
5632      /** This action is documented in wp-includes/post.php */
5633      do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
5634  
5635      /** This action is documented in wp-includes/post.php */
5636      do_action( 'save_post', $post->ID, $post, true );
5637  
5638      /** This action is documented in wp-includes/post.php */
5639      do_action( 'wp_insert_post', $post->ID, $post, true );
5640  
5641      wp_after_insert_post( $post, true, $post_before );
5642  }
5643  
5644  /**
5645   * Publishes future post and make sure post ID has future post status.
5646   *
5647   * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
5648   * from publishing drafts, etc.
5649   *
5650   * @since 2.5.0
5651   *
5652   * @param int|WP_Post $post Post ID or post object.
5653   */
5654  function check_and_publish_future_post( $post ) {
5655      $post = get_post( $post );
5656  
5657      if ( ! $post ) {
5658          return;
5659      }
5660  
5661      if ( 'future' !== $post->post_status ) {
5662          return;
5663      }
5664  
5665      $time = strtotime( $post->post_date_gmt . ' GMT' );
5666  
5667      // Uh oh, someone jumped the gun!
5668      if ( $time > time() ) {
5669          wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); // Clear anything else in the system.
5670          wp_schedule_single_event( $time, 'publish_future_post', array( $post->ID ) );
5671          return;
5672      }
5673  
5674      // wp_publish_post() returns no meaningful value.
5675      wp_publish_post( $post->ID );
5676  }
5677  
5678  /**
5679   * Uses wp_checkdate to return a valid Gregorian-calendar value for post_date.
5680   * If post_date is not provided, this first checks post_date_gmt if provided,
5681   * then falls back to use the current time.
5682   *
5683   * For back-compat purposes in wp_insert_post, an empty post_date and an invalid
5684   * post_date_gmt will continue to return '1970-01-01 00:00:00' rather than false.
5685   *
5686   * @since 5.7.0
5687   *
5688   * @param string $post_date     The date in mysql format (`Y-m-d H:i:s`).
5689   * @param string $post_date_gmt The GMT date in mysql format (`Y-m-d H:i:s`).
5690   * @return string|false A valid Gregorian-calendar date string, or false on failure.
5691   */
5692  function wp_resolve_post_date( $post_date = '', $post_date_gmt = '' ) {
5693      // If the date is empty, set the date to now.
5694      if ( empty( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
5695          if ( empty( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
5696              $post_date = current_time( 'mysql' );
5697          } else {
5698              $post_date = get_date_from_gmt( $post_date_gmt );
5699          }
5700      }
5701  
5702      // Validate the date.
5703      preg_match( '/^(\d{4})-(\d{1,2})-(\d{1,2})/', $post_date, $matches );
5704  
5705      if ( empty( $matches ) || ! is_array( $matches ) || count( $matches ) < 4 ) {
5706          return false;
5707      }
5708  
5709      $valid_date = wp_checkdate( $matches[2], $matches[3], $matches[1], $post_date );
5710  
5711      if ( ! $valid_date ) {
5712          return false;
5713      }
5714      return $post_date;
5715  }
5716  
5717  /**
5718   * Computes a unique slug for the post, when given the desired slug and some post details.
5719   *
5720   * @since 2.8.0
5721   *
5722   * @global wpdb       $wpdb       WordPress database abstraction object.
5723   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
5724   *
5725   * @param string $slug        The desired slug (post_name).
5726   * @param int    $post_id     Post ID.
5727   * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
5728   * @param string $post_type   Post type.
5729   * @param int    $post_parent Post parent ID.
5730   * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
5731   */
5732  function wp_unique_post_slug( $slug, $post_id, $post_status, $post_type, $post_parent ) {
5733      if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true )
5734          || ( 'inherit' === $post_status && 'revision' === $post_type ) || 'user_request' === $post_type
5735      ) {
5736          return $slug;
5737      }
5738  
5739      /**
5740       * Filters the post slug before it is generated to be unique.
5741       *
5742       * Returning a non-null value will short-circuit the
5743       * unique slug generation, returning the passed value instead.
5744       *
5745       * @since 5.1.0
5746       *
5747       * @param string|null $override_slug Short-circuit return value.
5748       * @param string      $slug          The desired slug (post_name).
5749       * @param int         $post_id       Post ID.
5750       * @param string      $post_status   The post status.
5751       * @param string      $post_type     Post type.
5752       * @param int         $post_parent   Post parent ID.
5753       */
5754      $override_slug = apply_filters( 'pre_wp_unique_post_slug', null, $slug, $post_id, $post_status, $post_type, $post_parent );
5755      if ( null !== $override_slug ) {
5756          return $override_slug;
5757      }
5758  
5759      global $wpdb, $wp_rewrite;
5760  
5761      $original_slug = $slug;
5762  
5763      $feeds = $wp_rewrite->feeds;
5764      if ( ! is_array( $feeds ) ) {
5765          $feeds = array();
5766      }
5767  
5768      if ( 'attachment' === $post_type ) {
5769          // Attachment slugs must be unique across all types.
5770          $check_sql       = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
5771          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_id ) );
5772  
5773          /**
5774           * Filters whether the post slug would make a bad attachment slug.
5775           *
5776           * @since 3.1.0
5777           *
5778           * @param bool   $bad_slug Whether the slug would be bad as an attachment slug.
5779           * @param string $slug     The post slug.
5780           */
5781          $is_bad_attachment_slug = apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug );
5782  
5783          if ( $post_name_check
5784              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5785              || $is_bad_attachment_slug
5786          ) {
5787              $suffix = 2;
5788              do {
5789                  $alt_post_name   = wp_truncate_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5790                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_id ) );
5791                  ++$suffix;
5792              } while ( $post_name_check );
5793              $slug = $alt_post_name;
5794          }
5795      } elseif ( is_post_type_hierarchical( $post_type ) ) {
5796          if ( 'nav_menu_item' === $post_type ) {
5797              return $slug;
5798          }
5799  
5800          /*
5801           * Page slugs must be unique within their own trees. Pages are in a separate
5802           * namespace than posts so page slugs are allowed to overlap post slugs.
5803           */
5804          $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";
5805          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_id, $post_parent ) );
5806  
5807          /**
5808           * Filters whether the post slug would make a bad hierarchical post slug.
5809           *
5810           * @since 3.1.0
5811           *
5812           * @param bool   $bad_slug    Whether the post slug would be bad in a hierarchical post context.
5813           * @param string $slug        The post slug.
5814           * @param string $post_type   Post type.
5815           * @param int    $post_parent Post parent ID.
5816           */
5817          $is_bad_hierarchical_slug = apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent );
5818  
5819          if ( $post_name_check
5820              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5821              || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )
5822              || $is_bad_hierarchical_slug
5823          ) {
5824              $suffix = 2;
5825              do {
5826                  $alt_post_name   = wp_truncate_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5827                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_id, $post_parent ) );
5828                  ++$suffix;
5829              } while ( $post_name_check );
5830              $slug = $alt_post_name;
5831          }
5832      } else {
5833          // Post slugs must be unique across all posts.
5834          $check_sql       = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
5835          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_id ) );
5836  
5837          $post = get_post( $post_id );
5838  
5839          // Prevent new post slugs that could result in URLs that conflict with date archives.
5840          $conflicts_with_date_archive = false;
5841          if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) ) {
5842              $slug_num = (int) $slug;
5843  
5844              if ( $slug_num ) {
5845                  $permastructs   = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
5846                  $postname_index = array_search( '%postname%', $permastructs, true );
5847  
5848                  /*
5849                  * Potential date clashes are as follows:
5850                  *
5851                  * - Any integer in the first permastruct position could be a year.
5852                  * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
5853                  * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
5854                  */
5855                  if ( 0 === $postname_index ||
5856                      ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
5857                      ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
5858                  ) {
5859                      $conflicts_with_date_archive = true;
5860                  }
5861              }
5862          }
5863  
5864          /**
5865           * Filters whether the post slug would be bad as a flat slug.
5866           *
5867           * @since 3.1.0
5868           *
5869           * @param bool   $bad_slug  Whether the post slug would be bad as a flat slug.
5870           * @param string $slug      The post slug.
5871           * @param string $post_type Post type.
5872           */
5873          $is_bad_flat_slug = apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type );
5874  
5875          if ( $post_name_check
5876              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5877              || $conflicts_with_date_archive
5878              || $is_bad_flat_slug
5879          ) {
5880              $suffix = 2;
5881              do {
5882                  $alt_post_name   = wp_truncate_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5883                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_id ) );
5884                  ++$suffix;
5885              } while ( $post_name_check );
5886              $slug = $alt_post_name;
5887          }
5888      }
5889  
5890      /**
5891       * Filters the unique post slug.
5892       *
5893       * @since 3.3.0
5894       *
5895       * @param string $slug          The post slug.
5896       * @param int    $post_id       Post ID.
5897       * @param string $post_status   The post status.
5898       * @param string $post_type     Post type.
5899       * @param int    $post_parent   Post parent ID
5900       * @param string $original_slug The original post slug.
5901       */
5902      return apply_filters( 'wp_unique_post_slug', $slug, $post_id, $post_status, $post_type, $post_parent, $original_slug );
5903  }
5904  
5905  /**
5906   * Adds tags to a post.
5907   *
5908   * @see wp_set_post_tags()
5909   *
5910   * @since 2.3.0
5911   *
5912   * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
5913   * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
5914   *                              separated by commas. Default empty.
5915   * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
5916   */
5917  function wp_add_post_tags( $post_id = 0, $tags = '' ) {
5918      return wp_set_post_tags( $post_id, $tags, true );
5919  }
5920  
5921  /**
5922   * Sets the tags for a post.
5923   *
5924   * @since 2.3.0
5925   *
5926   * @see wp_set_object_terms()
5927   *
5928   * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
5929   * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
5930   *                              separated by commas. Default empty.
5931   * @param bool         $append  Optional. If true, don't delete existing tags, just add on. If false,
5932   *                              replace the tags with the new tags. Default false.
5933   * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
5934   */
5935  function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
5936      return wp_set_post_terms( $post_id, $tags, 'post_tag', $append );
5937  }
5938  
5939  /**
5940   * Sets the terms for a post.
5941   *
5942   * @since 2.8.0
5943   *
5944   * @see wp_set_object_terms()
5945   *
5946   * @param int          $post_id  Optional. The Post ID. Does not default to the ID of the global $post.
5947   * @param string|array $terms    Optional. An array of terms to set for the post, or a string of terms
5948   *                               separated by commas. Hierarchical taxonomies must always pass IDs rather
5949   *                               than names so that children with the same names but different parents
5950   *                               aren't confused. Default empty.
5951   * @param string       $taxonomy Optional. Taxonomy name. Default 'post_tag'.
5952   * @param bool         $append   Optional. If true, don't delete existing terms, just add on. If false,
5953   *                               replace the terms with the new terms. Default false.
5954   * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
5955   */
5956  function wp_set_post_terms( $post_id = 0, $terms = '', $taxonomy = 'post_tag', $append = false ) {
5957      $post_id = (int) $post_id;
5958  
5959      if ( ! $post_id ) {
5960          return false;
5961      }
5962  
5963      if ( empty( $terms ) ) {
5964          $terms = array();
5965      }
5966  
5967      if ( ! is_array( $terms ) ) {
5968          $comma = _x( ',', 'tag delimiter' );
5969          if ( ',' !== $comma ) {
5970              $terms = str_replace( $comma, ',', $terms );
5971          }
5972          $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
5973      }
5974  
5975      /*
5976       * Hierarchical taxonomies must always pass IDs rather than names so that
5977       * children with the same names but different parents aren't confused.
5978       */
5979      if ( is_taxonomy_hierarchical( $taxonomy ) ) {
5980          $terms = array_unique( array_map( 'intval', $terms ) );
5981      }
5982  
5983      return wp_set_object_terms( $post_id, $terms, $taxonomy, $append );
5984  }
5985  
5986  /**
5987   * Sets categories for a post.
5988   *
5989   * If no categories are provided, the default category is used.
5990   *
5991   * @since 2.1.0
5992   *
5993   * @param int       $post_id         Optional. The Post ID. Does not default to the ID
5994   *                                   of the global $post. Default 0.
5995   * @param int[]|int $post_categories Optional. List of category IDs, or the ID of a single category.
5996   *                                   Default empty array.
5997   * @param bool      $append          If true, don't delete existing categories, just add on.
5998   *                                   If false, replace the categories with the new categories.
5999   * @return array|false|WP_Error Array of term taxonomy IDs of affected categories. WP_Error or false on failure.
6000   */
6001  function wp_set_post_categories( $post_id = 0, $post_categories = array(), $append = false ) {
6002      $post_id     = (int) $post_id;
6003      $post_type   = get_post_type( $post_id );
6004      $post_status = get_post_status( $post_id );
6005  
6006      // If $post_categories isn't already an array, make it one.
6007      $post_categories = (array) $post_categories;
6008  
6009      if ( empty( $post_categories ) ) {
6010          /**
6011           * Filters post types (in addition to 'post') that require a default category.
6012           *
6013           * @since 5.5.0
6014           *
6015           * @param string[] $post_types An array of post type names. Default empty array.
6016           */
6017          $default_category_post_types = apply_filters( 'default_category_post_types', array() );
6018  
6019          // Regular posts always require a default category.
6020          $default_category_post_types = array_merge( $default_category_post_types, array( 'post' ) );
6021  
6022          if ( in_array( $post_type, $default_category_post_types, true )
6023              && is_object_in_taxonomy( $post_type, 'category' )
6024              && 'auto-draft' !== $post_status
6025          ) {
6026              $post_categories = array( get_option( 'default_category' ) );
6027              $append          = false;
6028          } else {
6029              $post_categories = array();
6030          }
6031      } elseif ( 1 === count( $post_categories ) && '' === reset( $post_categories ) ) {
6032          return true;
6033      }
6034  
6035      return wp_set_post_terms( $post_id, $post_categories, 'category', $append );
6036  }
6037  
6038  /**
6039   * Fires actions related to the transitioning of a post's status.
6040   *
6041   * When a post is saved, the post status is "transitioned" from one status to another,
6042   * though this does not always mean the status has actually changed before and after
6043   * the save. This function fires a number of action hooks related to that transition:
6044   * the generic {@see 'transition_post_status'} action, as well as the dynamic hooks
6045   * {@see '$old_status_to_$new_status'} and {@see '$new_status_$post->post_type'}. Note
6046   * that the function does not transition the post object in the database.
6047   *
6048   * For instance: When publishing a post for the first time, the post status may transition
6049   * from 'draft' – or some other status – to 'publish'. However, if a post is already
6050   * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
6051   * before and after the transition.
6052   *
6053   * @since 2.3.0
6054   *
6055   * @param string  $new_status Transition to this post status.
6056   * @param string  $old_status Previous post status.
6057   * @param WP_Post $post       Post data.
6058   */
6059  function wp_transition_post_status( $new_status, $old_status, $post ) {
6060      /**
6061       * Fires when a post is transitioned from one status to another.
6062       *
6063       * @since 2.3.0
6064       *
6065       * @param string  $new_status New post status.
6066       * @param string  $old_status Old post status.
6067       * @param WP_Post $post       Post object.
6068       */
6069      do_action( 'transition_post_status', $new_status, $old_status, $post );
6070  
6071      $new_status_object = get_post_status_object( $new_status );
6072      $old_status_valid  = get_post_status_object( $old_status ) || 'new' === $old_status;
6073      $post_type_object  = get_post_type_object( $post->post_type );
6074  
6075      if ( $new_status_object && $old_status_valid ) {
6076          /**
6077           * Fires when a post is transitioned from one status to another.
6078           *
6079           * The dynamic portions of the hook name, `$new_status` and `$old_status`,
6080           * refer to the old and new post statuses, respectively.
6081           *
6082           * Possible hook names include:
6083           *
6084           *  - `draft_to_publish`
6085           *  - `publish_to_trash`
6086           *  - `pending_to_draft`
6087           *
6088           * @since 2.3.0
6089           *
6090           * @param WP_Post $post Post object.
6091           */
6092          do_action( "{$old_status}_to_{$new_status}", $post );
6093      }
6094  
6095      if ( $new_status_object && $post_type_object ) {
6096          /**
6097           * Fires when a post is transitioned from one status to another.
6098           *
6099           * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
6100           * refer to the new post status and post type, respectively.
6101           *
6102           * Possible hook names include:
6103           *
6104           *  - `draft_post`
6105           *  - `future_post`
6106           *  - `pending_post`
6107           *  - `private_post`
6108           *  - `publish_post`
6109           *  - `trash_post`
6110           *  - `draft_page`
6111           *  - `future_page`
6112           *  - `pending_page`
6113           *  - `private_page`
6114           *  - `publish_page`
6115           *  - `trash_page`
6116           *  - `publish_attachment`
6117           *  - `trash_attachment`
6118           *
6119           * Please note: When this action is hooked using a particular post status (like
6120           * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
6121           * first transitioned to that status from something else, as well as upon
6122           * subsequent post updates (old and new status are both the same).
6123           *
6124           * Therefore, if you are looking to only fire a callback when a post is first
6125           * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
6126           *
6127           * @since 2.3.0
6128           * @since 5.9.0 Added `$old_status` parameter.
6129           *
6130           * @param int     $post_id    Post ID.
6131           * @param WP_Post $post       Post object.
6132           * @param string  $old_status Old post status.
6133           */
6134          do_action( "{$new_status}_{$post->post_type}", $post->ID, $post, $old_status );
6135      }
6136  }
6137  
6138  /**
6139   * Fires actions after a post, its terms and meta data has been saved.
6140   *
6141   * @since 5.6.0
6142   *
6143   * @param int|WP_Post  $post        The post ID or object that has been saved.
6144   * @param bool         $update      Whether this is an existing post being updated.
6145   * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
6146   *                                  to the update for updated posts.
6147   */
6148  function wp_after_insert_post( $post, $update, $post_before ) {
6149      $post = get_post( $post );
6150  
6151      if ( ! $post ) {
6152          return;
6153      }
6154  
6155      $post_id = $post->ID;
6156  
6157      /**
6158       * Fires once a post, its terms and meta data has been saved.
6159       *
6160       * @since 5.6.0
6161       *
6162       * @param int          $post_id     Post ID.
6163       * @param WP_Post      $post        Post object.
6164       * @param bool         $update      Whether this is an existing post being updated.
6165       * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
6166       *                                  to the update for updated posts.
6167       */
6168      do_action( 'wp_after_insert_post', $post_id, $post, $update, $post_before );
6169  }
6170  
6171  //
6172  // Comment, trackback, and pingback functions.
6173  //
6174  
6175  /**
6176   * Adds a URL to those already pinged.
6177   *
6178   * @since 1.5.0
6179   * @since 4.7.0 `$post` can be a WP_Post object.
6180   * @since 4.7.0 `$uri` can be an array of URIs.
6181   *
6182   * @global wpdb $wpdb WordPress database abstraction object.
6183   *
6184   * @param int|WP_Post  $post Post ID or post object.
6185   * @param string|array $uri  Ping URI or array of URIs.
6186   * @return int|false How many rows were updated.
6187   */
6188  function add_ping( $post, $uri ) {
6189      global $wpdb;
6190  
6191      $post = get_post( $post );
6192  
6193      if ( ! $post ) {
6194          return false;
6195      }
6196  
6197      $pung = trim( $post->pinged );
6198      $pung = preg_split( '/\s/', $pung );
6199  
6200      if ( is_array( $uri ) ) {
6201          $pung = array_merge( $pung, $uri );
6202      } else {
6203          $pung[] = $uri;
6204      }
6205      $new = implode( "\n", $pung );
6206  
6207      /**
6208       * Filters the new ping URL to add for the given post.
6209       *
6210       * @since 2.0.0
6211       *
6212       * @param string $new New ping URL to add.
6213       */
6214      $new = apply_filters( 'add_ping', $new );
6215  
6216      $return = $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post->ID ) );
6217      clean_post_cache( $post->ID );
6218      return $return;
6219  }
6220  
6221  /**
6222   * Retrieves enclosures already enclosed for a post.
6223   *
6224   * @since 1.5.0
6225   *
6226   * @param int $post_id Post ID.
6227   * @return string[] Array of enclosures for the given post.
6228   */
6229  function get_enclosed( $post_id ) {
6230      $custom_fields = get_post_custom( $post_id );
6231      $pung          = array();
6232      if ( ! is_array( $custom_fields ) ) {
6233          return $pung;
6234      }
6235  
6236      foreach ( $custom_fields as $key => $val ) {
6237          if ( 'enclosure' !== $key || ! is_array( $val ) ) {
6238              continue;
6239          }
6240          foreach ( $val as $enc ) {
6241              $enclosure = explode( "\n", $enc );
6242              $pung[]    = trim( $enclosure[0] );
6243          }
6244      }
6245  
6246      /**
6247       * Filters the list of enclosures already enclosed for the given post.
6248       *
6249       * @since 2.0.0
6250       *
6251       * @param string[] $pung    Array of enclosures for the given post.
6252       * @param int      $post_id Post ID.
6253       */
6254      return apply_filters( 'get_enclosed', $pung, $post_id );
6255  }
6256  
6257  /**
6258   * Retrieves URLs already pinged for a post.
6259   *
6260   * @since 1.5.0
6261   *
6262   * @since 4.7.0 `$post` can be a WP_Post object.
6263   *
6264   * @param int|WP_Post $post Post ID or object.
6265   * @return string[]|false Array of URLs already pinged for the given post, false if the post is not found.
6266   */
6267  function get_pung( $post ) {
6268      $post = get_post( $post );
6269  
6270      if ( ! $post ) {
6271          return false;
6272      }
6273  
6274      $pung = trim( $post->pinged );
6275      $pung = preg_split( '/\s/', $pung );
6276  
6277      /**
6278       * Filters the list of already-pinged URLs for the given post.
6279       *
6280       * @since 2.0.0
6281       *
6282       * @param string[] $pung Array of URLs already pinged for the given post.
6283       */
6284      return apply_filters( 'get_pung', $pung );
6285  }
6286  
6287  /**
6288   * Retrieves URLs that need to be pinged.
6289   *
6290   * @since 1.5.0
6291   * @since 4.7.0 `$post` can be a WP_Post object.
6292   *
6293   * @param int|WP_Post $post Post ID or post object.
6294   * @return string[]|false List of URLs yet to ping.
6295   */
6296  function get_to_ping( $post ) {
6297      $post = get_post( $post );
6298  
6299      if ( ! $post ) {
6300          return false;
6301      }
6302  
6303      $to_ping = sanitize_trackback_urls( $post->to_ping );
6304      $to_ping = preg_split( '/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY );
6305  
6306      /**
6307       * Filters the list of URLs yet to ping for the given post.
6308       *
6309       * @since 2.0.0
6310       *
6311       * @param string[] $to_ping List of URLs yet to ping.
6312       */
6313      return apply_filters( 'get_to_ping', $to_ping );
6314  }
6315  
6316  /**
6317   * Does trackbacks for a list of URLs.
6318   *
6319   * @since 1.0.0
6320   *
6321   * @param string $tb_list Comma separated list of URLs.
6322   * @param int    $post_id Post ID.
6323   */
6324  function trackback_url_list( $tb_list, $post_id ) {
6325      if ( ! empty( $tb_list ) ) {
6326          // Get post data.
6327          $post = get_post( $post_id );
6328          if ( ! $post ) {
6329              return;
6330          }
6331          $postdata = $post->to_array();
6332  
6333          // Form an excerpt.
6334          $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
6335  
6336          if ( strlen( $excerpt ) > 255 ) {
6337              $excerpt = substr( $excerpt, 0, 252 ) . '&hellip;';
6338          }
6339  
6340          $trackback_urls = explode( ',', $tb_list );
6341          foreach ( (array) $trackback_urls as $tb_url ) {
6342              $tb_url = trim( $tb_url );
6343              trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
6344          }
6345      }
6346  }
6347  
6348  //
6349  // Page functions.
6350  //
6351  
6352  /**
6353   * Gets a list of page IDs.
6354   *
6355   * @since 2.0.0
6356   *
6357   * @global wpdb $wpdb WordPress database abstraction object.
6358   *
6359   * @return string[] List of page IDs as strings.
6360   */
6361  function get_all_page_ids() {
6362      global $wpdb;
6363  
6364      $page_ids = wp_cache_get( 'all_page_ids', 'posts' );
6365      if ( ! is_array( $page_ids ) ) {
6366          $page_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'page'" );
6367          wp_cache_add( 'all_page_ids', $page_ids, 'posts' );
6368      }
6369  
6370      return $page_ids;
6371  }
6372  
6373  /**
6374   * Retrieves page data given a page ID or page object.
6375   *
6376   * Use get_post() instead of get_page().
6377   *
6378   * @since 1.5.1
6379   * @deprecated 3.5.0 Use get_post()
6380   *
6381   * @param int|WP_Post $page   Page object or page ID. Passed by reference.
6382   * @param string      $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
6383   *                            correspond to a WP_Post object, an associative array, or a numeric array,
6384   *                            respectively. Default OBJECT.
6385   * @param string      $filter Optional. How the return value should be filtered. Accepts 'raw',
6386   *                            'edit', 'db', 'display'. Default 'raw'.
6387   * @return WP_Post|array|null WP_Post or array on success, null on failure.
6388   *
6389   * @phpstan-param int|numeric-string|WP_Post|null $page
6390   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
6391   * @phpstan-param 'raw'|'edit'|'db'|'display' $filter
6392   * @phpstan-return (
6393   *     $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : (
6394   *         $output is 'ARRAY_N' ? non-empty-array<int, mixed>|null : (
6395   *             WP_Post|null
6396   *         )
6397   *     )
6398   * )
6399   */
6400  function get_page( $page, $output = OBJECT, $filter = 'raw' ) {
6401      return get_post( $page, $output, $filter );
6402  }
6403  
6404  /**
6405   * Retrieves a page given its path.
6406   *
6407   * @since 2.1.0
6408   *
6409   * @global wpdb $wpdb WordPress database abstraction object.
6410   *
6411   * @param string       $page_path Page path.
6412   * @param string       $output    Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
6413   *                                correspond to a WP_Post object, an associative array, or a numeric array,
6414   *                                respectively. Default OBJECT.
6415   * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
6416   * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
6417   *
6418   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
6419   * @phpstan-param string|string[]              $post_type
6420   * @phpstan-return (
6421   *     $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : (
6422   *         $output is 'ARRAY_N' ? non-empty-array<int, mixed>|null : (
6423   *             WP_Post|null
6424   *         )
6425   *     )
6426   * )
6427   */
6428  function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
6429      global $wpdb;
6430  
6431      $last_changed = wp_cache_get_last_changed( 'posts' );
6432  
6433      $hash      = md5( $page_path . serialize( $post_type ) );
6434      $cache_key = "get_page_by_path:$hash";
6435      $cached    = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
6436      if ( false !== $cached ) {
6437          // Special case: '0' is a bad `$page_path`.
6438          if ( '0' === $cached || 0 === $cached ) {
6439              return null;
6440          } else {
6441              return get_post( (int) $cached, $output );
6442          }
6443      }
6444  
6445      $page_path     = rawurlencode( urldecode( $page_path ) );
6446      $page_path     = str_replace( '%2F', '/', $page_path );
6447      $page_path     = str_replace( '%20', ' ', $page_path );
6448      $parts         = explode( '/', trim( $page_path, '/' ) );
6449      $parts         = array_map( 'sanitize_title_for_query', $parts );
6450      $escaped_parts = esc_sql( $parts );
6451  
6452      $in_string = "'" . implode( "','", $escaped_parts ) . "'";
6453  
6454      if ( is_array( $post_type ) ) {
6455          $post_types = $post_type;
6456      } else {
6457          $post_types = array( $post_type, 'attachment' );
6458      }
6459  
6460      $post_types          = esc_sql( $post_types );
6461      $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
6462      $sql                 = "
6463          SELECT ID, post_name, post_parent, post_type
6464          FROM $wpdb->posts
6465          WHERE post_name IN ($in_string)
6466          AND post_type IN ($post_type_in_string)
6467          ORDER BY
6468              post_status = 'publish' DESC,
6469              post_status IN ('draft', 'pending', 'auto-draft') ASC, ID ASC
6470      ";
6471  
6472      /** @var array<object{ ID: string, post_name: string, post_parent: string, post_type: string }> $pages */
6473      $pages = $wpdb->get_results( $sql, OBJECT_K ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The escaping has been applied above via esc_sql().
6474  
6475      $revparts = array_reverse( $parts );
6476  
6477      $found_id = 0;
6478      foreach ( (array) $pages as $page ) {
6479          if ( $page->post_name === $revparts[0] ) {
6480              $count = 0;
6481              $p     = $page;
6482  
6483              /*
6484               * Loop through the given path parts from right to left,
6485               * ensuring each matches the post ancestry.
6486               */
6487              while ( 0 !== (int) $p->post_parent && isset( $pages[ $p->post_parent ] ) ) {
6488                  ++$count;
6489                  $parent = $pages[ $p->post_parent ];
6490                  if ( ! isset( $revparts[ $count ] ) || $parent->post_name !== $revparts[ $count ] ) {
6491                      break;
6492                  }
6493                  $p = $parent;
6494              }
6495  
6496              if ( 0 === (int) $p->post_parent
6497                  && count( $revparts ) === $count + 1
6498                  && $p->post_name === $revparts[ $count ]
6499              ) {
6500                  $found_id = $page->ID;
6501  
6502                  /*
6503                   * A string like 'page' also searches attachments: /about/photo/ could be
6504                   * a child page or an attachment page, and this lookup handles both.
6505                   * Keep an attachment as a fallback, but keep looking for the requested
6506                   * type so an attachment cannot hide a page with the same path.
6507                   *
6508                   * An array is the exact list of types to search; no extra types are added.
6509                   * SQL already checks that list, so stop at the first full-path match.
6510                   */
6511                  if ( is_array( $post_type ) || $page->post_type === $post_type ) {
6512                      break;
6513                  }
6514              }
6515          }
6516      }
6517  
6518      // We cache misses as well as hits.
6519      wp_cache_set_salted( $cache_key, $found_id, 'post-queries', $last_changed );
6520  
6521      if ( $found_id ) {
6522          return get_post( (int) $found_id, $output );
6523      }
6524  
6525      return null;
6526  }
6527  
6528  /**
6529   * Identifies descendants of a given page ID in a list of page objects.
6530   *
6531   * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
6532   *
6533   * @since 1.5.1
6534   *
6535   * @param int       $page_id Page ID.
6536   * @param WP_Post[] $pages   List of page objects from which descendants should be identified.
6537   * @return WP_Post[] List of page children.
6538   */
6539  function get_page_children( $page_id, $pages ) {
6540      // Build a hash of ID -> children.
6541      $children = array();
6542      foreach ( (array) $pages as $page ) {
6543          $children[ (int) $page->post_parent ][] = $page;
6544      }
6545  
6546      $page_list = array();
6547  
6548      // Start the search by looking at immediate children.
6549      if ( isset( $children[ $page_id ] ) ) {
6550          // Always start at the end of the stack in order to preserve original `$pages` order.
6551          $to_look = array_reverse( $children[ $page_id ] );
6552  
6553          while ( $to_look ) {
6554              $p           = array_pop( $to_look );
6555              $page_list[] = $p;
6556              if ( isset( $children[ $p->ID ] ) ) {
6557                  foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
6558                      // Append to the `$to_look` stack to descend the tree.
6559                      $to_look[] = $child;
6560                  }
6561              }
6562          }
6563      }
6564  
6565      return $page_list;
6566  }
6567  
6568  /**
6569   * Orders the pages with children under parents in a flat list.
6570   *
6571   * It uses auxiliary structure to hold parent-children relationships and
6572   * runs in O(N) complexity
6573   *
6574   * @since 2.0.0
6575   *
6576   * @param WP_Post[] $pages   Posts array (passed by reference).
6577   * @param int       $page_id Optional. Parent page ID. Default 0.
6578   * @return string[] Array of post names keyed by ID and arranged by hierarchy. Children immediately follow their parents.
6579   */
6580  function get_page_hierarchy( &$pages, $page_id = 0 ) {
6581      if ( empty( $pages ) ) {
6582          return array();
6583      }
6584  
6585      $children = array();
6586      foreach ( (array) $pages as $p ) {
6587          $parent_id                = (int) $p->post_parent;
6588          $children[ $parent_id ][] = $p;
6589      }
6590  
6591      $result = array();
6592      _page_traverse_name( $page_id, $children, $result );
6593  
6594      return $result;
6595  }
6596  
6597  /**
6598   * Traverses and return all the nested children post names of a root page.
6599   *
6600   * $children contains parent-children relations
6601   *
6602   * @since 2.9.0
6603   * @access private
6604   *
6605   * @see _page_traverse_name()
6606   *
6607   * @param int      $page_id  Page ID.
6608   * @param array    $children Parent-children relations (passed by reference).
6609   * @param string[] $result   Array of page names keyed by ID (passed by reference).
6610   */
6611  function _page_traverse_name( $page_id, &$children, &$result ) {
6612      if ( isset( $children[ $page_id ] ) ) {
6613          foreach ( (array) $children[ $page_id ] as $child ) {
6614              $result[ $child->ID ] = $child->post_name;
6615              _page_traverse_name( $child->ID, $children, $result );
6616          }
6617      }
6618  }
6619  
6620  /**
6621   * Builds the URI path for a page.
6622   *
6623   * Sub pages will be in the "directory" under the parent page post name.
6624   *
6625   * @since 1.5.0
6626   * @since 4.6.0 The `$page` parameter was made optional.
6627   *
6628   * @param WP_Post|object|int $page Optional. Page ID or WP_Post object. Default is global $post.
6629   * @return string|false Page URI, false on error.
6630   */
6631  function get_page_uri( $page = 0 ) {
6632      if ( ! $page instanceof WP_Post ) {
6633          $page = get_post( $page );
6634      }
6635  
6636      if ( ! $page ) {
6637          return false;
6638      }
6639  
6640      $uri = $page->post_name;
6641  
6642      foreach ( $page->ancestors as $parent ) {
6643          $parent = get_post( $parent );
6644          if ( $parent && $parent->post_name ) {
6645              $uri = $parent->post_name . '/' . $uri;
6646          }
6647      }
6648  
6649      /**
6650       * Filters the URI for a page.
6651       *
6652       * @since 4.4.0
6653       *
6654       * @param string  $uri  Page URI.
6655       * @param WP_Post $page Page object.
6656       */
6657      return apply_filters( 'get_page_uri', $uri, $page );
6658  }
6659  
6660  /**
6661   * Retrieves an array of pages (or hierarchical post type items).
6662   *
6663   * @since 1.5.0
6664   * @since 6.3.0 Use WP_Query internally.
6665   *
6666   * @param array|string $args {
6667   *     Optional. Array or string of arguments to retrieve pages.
6668   *
6669   *     @type int          $child_of     Page ID to return child and grandchild pages of. Note: The value
6670   *                                      of `$hierarchical` has no bearing on whether `$child_of` returns
6671   *                                      hierarchical results. Default 0, or no restriction.
6672   *     @type string       $sort_order   How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
6673   *     @type string       $sort_column  What columns to sort pages by, comma-separated. Accepts 'post_author',
6674   *                                      'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
6675   *                                      'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
6676   *                                      'post_' can be omitted for any values that start with it.
6677   *                                      Default 'post_title'.
6678   *     @type bool         $hierarchical Whether to return pages hierarchically. If false in conjunction with
6679   *                                      `$child_of` also being false, both arguments will be disregarded.
6680   *                                      Default true.
6681   *     @type int[]        $exclude      Array of page IDs to exclude. Default empty array.
6682   *     @type int[]        $include      Array of page IDs to include. Cannot be used with `$child_of`,
6683   *                                      `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
6684   *                                      Default empty array.
6685   *     @type string       $meta_key     Only include pages with this meta key. Default empty.
6686   *     @type string       $meta_value   Only include pages with this meta value. Requires `$meta_key`.
6687   *                                      Default empty.
6688   *     @type string       $authors      A comma-separated list of author IDs. Default empty.
6689   *     @type int          $parent       Page ID to return direct children of. Default -1, or no restriction.
6690   *     @type string|int[] $exclude_tree Comma-separated string or array of page IDs to exclude.
6691   *                                      Default empty array.
6692   *     @type int          $number       The number of pages to return. Default 0, or all pages.
6693   *     @type int          $offset       The number of pages to skip before returning. Requires `$number`.
6694   *                                      Default 0.
6695   *     @type string       $post_type    The post type to query. Default 'page'.
6696   *     @type string|array $post_status  A comma-separated list or array of post statuses to include.
6697   *                                      Default 'publish'.
6698   * }
6699   * @return WP_Post[]|false Array of pages (or hierarchical post type items). Boolean false if the
6700   *                         specified post type is not hierarchical or the specified status is not
6701   *                         supported by the post type.
6702   */
6703  function get_pages( $args = array() ) {
6704      $defaults = array(
6705          'child_of'     => 0,
6706          'sort_order'   => 'ASC',
6707          'sort_column'  => 'post_title',
6708          'hierarchical' => 1,
6709          'exclude'      => array(),
6710          'include'      => array(),
6711          'meta_key'     => '',
6712          'meta_value'   => '',
6713          'authors'      => '',
6714          'parent'       => -1,
6715          'exclude_tree' => array(),
6716          'number'       => '',
6717          'offset'       => 0,
6718          'post_type'    => 'page',
6719          'post_status'  => 'publish',
6720      );
6721  
6722      $parsed_args = wp_parse_args( $args, $defaults );
6723  
6724      $number       = (int) $parsed_args['number'];
6725      $offset       = (int) $parsed_args['offset'];
6726      $child_of     = (int) $parsed_args['child_of'];
6727      $hierarchical = $parsed_args['hierarchical'];
6728      $exclude      = $parsed_args['exclude'];
6729      $meta_key     = $parsed_args['meta_key'];
6730      $meta_value   = $parsed_args['meta_value'];
6731      $parent       = $parsed_args['parent'];
6732      $post_status  = $parsed_args['post_status'];
6733  
6734      // Make sure the post type is hierarchical.
6735      $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
6736      if ( ! in_array( $parsed_args['post_type'], $hierarchical_post_types, true ) ) {
6737          return false;
6738      }
6739  
6740      if ( $parent > 0 && ! $child_of ) {
6741          $hierarchical = false;
6742      }
6743  
6744      // Make sure we have a valid post status.
6745      if ( ! is_array( $post_status ) ) {
6746          $post_status = explode( ',', $post_status );
6747      }
6748      if ( array_diff( $post_status, get_post_stati() ) ) {
6749          return false;
6750      }
6751  
6752      $query_args = array(
6753          'orderby'                => 'post_title',
6754          'order'                  => 'ASC',
6755          'post__not_in'           => wp_parse_id_list( $exclude ),
6756          'meta_key'               => $meta_key,
6757          'meta_value'             => $meta_value,
6758          'posts_per_page'         => -1,
6759          'offset'                 => $offset,
6760          'post_type'              => $parsed_args['post_type'],
6761          'post_status'            => $post_status,
6762          'update_post_term_cache' => false,
6763          'update_post_meta_cache' => false,
6764          'ignore_sticky_posts'    => true,
6765          'no_found_rows'          => true,
6766      );
6767  
6768      if ( ! empty( $parsed_args['include'] ) ) {
6769          $child_of = 0; // Ignore child_of, parent, exclude, meta_key, and meta_value params if using include.
6770          $parent   = -1;
6771          unset( $query_args['post__not_in'], $query_args['meta_key'], $query_args['meta_value'] );
6772          $hierarchical           = false;
6773          $query_args['post__in'] = wp_parse_id_list( $parsed_args['include'] );
6774      }
6775  
6776      if ( ! empty( $parsed_args['authors'] ) ) {
6777          $post_authors = wp_parse_list( $parsed_args['authors'] );
6778  
6779          if ( ! empty( $post_authors ) ) {
6780              $query_args['author__in'] = array();
6781              foreach ( $post_authors as $post_author ) {
6782                  // Do we have an author id or an author login?
6783                  if ( 0 === (int) $post_author ) {
6784                      $post_author = get_user_by( 'login', $post_author );
6785                      if ( empty( $post_author ) ) {
6786                          continue;
6787                      }
6788                      if ( empty( $post_author->ID ) ) {
6789                          continue;
6790                      }
6791                      $post_author = $post_author->ID;
6792                  }
6793                  $query_args['author__in'][] = (int) $post_author;
6794              }
6795          }
6796      }
6797  
6798      if ( is_array( $parent ) ) {
6799          $post_parent__in = array_map( 'absint', (array) $parent );
6800          if ( ! empty( $post_parent__in ) ) {
6801              $query_args['post_parent__in'] = $post_parent__in;
6802          }
6803      } elseif ( $parent >= 0 ) {
6804          $query_args['post_parent'] = $parent;
6805      }
6806  
6807      /*
6808       * Maintain backward compatibility for `sort_column` key.
6809       * Additionally to `WP_Query`, it has been supporting the `post_modified_gmt` field, so this logic will translate
6810       * it to `post_modified` which should result in the same order given the two dates in the fields match.
6811       */
6812      $orderby = wp_parse_list( $parsed_args['sort_column'] );
6813      $orderby = array_map(
6814          static function ( $orderby_field ) {
6815              $orderby_field = trim( $orderby_field );
6816              if ( 'post_modified_gmt' === $orderby_field || 'modified_gmt' === $orderby_field ) {
6817                  $orderby_field = str_replace( '_gmt', '', $orderby_field );
6818              }
6819              return $orderby_field;
6820          },
6821          $orderby
6822      );
6823      if ( $orderby ) {
6824          $query_args['orderby'] = array_fill_keys( $orderby, $parsed_args['sort_order'] );
6825      }
6826  
6827      $order = $parsed_args['sort_order'];
6828      if ( $order ) {
6829          $query_args['order'] = $order;
6830      }
6831  
6832      if ( ! empty( $number ) ) {
6833          $query_args['posts_per_page'] = $number;
6834      }
6835  
6836      /**
6837       * Filters query arguments passed to WP_Query in get_pages().
6838       *
6839       * @since 6.3.0
6840       *
6841       * @param array $query_args  Array of arguments passed to WP_Query.
6842       * @param array $parsed_args Array of get_pages() arguments.
6843       */
6844      $query_args = apply_filters( 'get_pages_query_args', $query_args, $parsed_args );
6845  
6846      $pages = new WP_Query();
6847      $pages = $pages->query( $query_args );
6848  
6849      if ( $child_of || $hierarchical ) {
6850          $pages = get_page_children( $child_of, $pages );
6851      }
6852  
6853      if ( ! empty( $parsed_args['exclude_tree'] ) ) {
6854          $exclude = wp_parse_id_list( $parsed_args['exclude_tree'] );
6855          foreach ( $exclude as $id ) {
6856              $children = get_page_children( $id, $pages );
6857              foreach ( $children as $child ) {
6858                  $exclude[] = $child->ID;
6859              }
6860          }
6861  
6862          $num_pages = count( $pages );
6863          for ( $i = 0; $i < $num_pages; $i++ ) {
6864              if ( in_array( $pages[ $i ]->ID, $exclude, true ) ) {
6865                  unset( $pages[ $i ] );
6866              }
6867          }
6868      }
6869  
6870      /**
6871       * Filters the retrieved list of pages.
6872       *
6873       * @since 2.1.0
6874       *
6875       * @param WP_Post[] $pages       Array of page objects.
6876       * @param array     $parsed_args Array of get_pages() arguments.
6877       */
6878      return apply_filters( 'get_pages', $pages, $parsed_args );
6879  }
6880  
6881  //
6882  // Attachment functions.
6883  //
6884  
6885  /**
6886   * Determines whether an attachment URI is local and really an attachment.
6887   *
6888   * For more information on this and similar theme functions, check out
6889   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
6890   * Conditional Tags} article in the Theme Developer Handbook.
6891   *
6892   * @since 2.0.0
6893   *
6894   * @param string $url URL to check
6895   * @return bool True on success, false on failure.
6896   */
6897  function is_local_attachment( $url ) {
6898      if ( ! str_contains( $url, home_url() ) ) {
6899          return false;
6900      }
6901      if ( str_contains( $url, home_url( '/?attachment_id=' ) ) ) {
6902          return true;
6903      }
6904  
6905      $id = url_to_postid( $url );
6906      if ( $id ) {
6907          $post = get_post( $id );
6908          if ( 'attachment' === $post->post_type ) {
6909              return true;
6910          }
6911      }
6912      return false;
6913  }
6914  
6915  /**
6916   * Inserts an attachment.
6917   *
6918   * If you set the 'ID' in the $args parameter, it will mean that you are
6919   * updating and attempt to update the attachment. You can also set the
6920   * attachment name or title by setting the key 'post_name' or 'post_title'.
6921   *
6922   * You can set the dates for the attachment manually by setting the 'post_date'
6923   * and 'post_date_gmt' keys' values.
6924   *
6925   * By default, the comments will use the default settings for whether the
6926   * comments are allowed. You can close them manually or keep them open by
6927   * setting the value for the 'comment_status' key.
6928   *
6929   * @since 2.0.0
6930   * @since 4.7.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
6931   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
6932   *
6933   * @see wp_insert_post()
6934   *
6935   * @param string|array $args             Arguments for inserting an attachment.
6936   * @param string|false $file             Optional. Filename. Default false.
6937   * @param int          $parent_post_id   Optional. Parent post ID or 0 for no parent. Default 0.
6938   * @param bool         $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
6939   * @param bool         $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
6940   * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
6941   *
6942   * @phpstan-return (
6943   *     $wp_error is false ? int : int|WP_Error
6944   * )
6945   */
6946  function wp_insert_attachment( $args, $file = false, $parent_post_id = 0, $wp_error = false, $fire_after_hooks = true ) {
6947      $defaults = array(
6948          'file'        => $file,
6949          'post_parent' => 0,
6950      );
6951  
6952      $data = wp_parse_args( $args, $defaults );
6953  
6954      if ( ! empty( $parent_post_id ) ) {
6955          $data['post_parent'] = $parent_post_id;
6956      }
6957  
6958      $data['post_type'] = 'attachment';
6959  
6960      return wp_insert_post( $data, $wp_error, $fire_after_hooks );
6961  }
6962  
6963  /**
6964   * Trashes or deletes an attachment.
6965   *
6966   * When an attachment is permanently deleted, the file will also be removed.
6967   * Deletion removes all post meta fields, taxonomy, comments, etc. associated
6968   * with the attachment (except the main post).
6969   *
6970   * The attachment is moved to the Trash instead of permanently deleted unless Trash
6971   * for media is disabled, item is already in the Trash, or $force_delete is true.
6972   *
6973   * @since 2.0.0
6974   *
6975   * @global wpdb $wpdb WordPress database abstraction object.
6976   *
6977   * @param int  $post_id      Attachment ID.
6978   * @param bool $force_delete Optional. Whether to bypass Trash and force deletion.
6979   *                           Default false.
6980   * @return WP_Post|false|null Post data on success, false or null on failure.
6981   */
6982  function wp_delete_attachment( $post_id, $force_delete = false ) {
6983      global $wpdb;
6984  
6985      $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) );
6986  
6987      if ( ! $post ) {
6988          return $post;
6989      }
6990  
6991      $post = get_post( $post );
6992  
6993      if ( 'attachment' !== $post->post_type ) {
6994          return false;
6995      }
6996  
6997      if ( ! $force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' !== $post->post_status ) {
6998          return wp_trash_post( $post_id );
6999      }
7000  
7001      /**
7002       * Filters whether an attachment deletion should take place.
7003       *
7004       * @since 5.5.0
7005       *
7006       * @param WP_Post|false|null $delete       Whether to go forward with deletion.
7007       * @param WP_Post            $post         Post object.
7008       * @param bool               $force_delete Whether to bypass the Trash.
7009       */
7010      $check = apply_filters( 'pre_delete_attachment', null, $post, $force_delete );
7011      if ( null !== $check ) {
7012          return $check;
7013      }
7014  
7015      delete_post_meta( $post_id, '_wp_trash_meta_status' );
7016      delete_post_meta( $post_id, '_wp_trash_meta_time' );
7017  
7018      $meta         = wp_get_attachment_metadata( $post_id );
7019      $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
7020      $file         = get_attached_file( $post_id );
7021  
7022      if ( is_multisite() && is_string( $file ) && ! empty( $file ) ) {
7023          clean_dirsize_cache( $file );
7024      }
7025  
7026      /**
7027       * Fires before an attachment is deleted, at the start of wp_delete_attachment().
7028       *
7029       * @since 2.0.0
7030       * @since 5.5.0 Added the `$post` parameter.
7031       *
7032       * @param int     $post_id Attachment ID.
7033       * @param WP_Post $post    Post object.
7034       */
7035      do_action( 'delete_attachment', $post_id, $post );
7036  
7037      wp_delete_object_term_relationships( $post_id, array( 'category', 'post_tag' ) );
7038      wp_delete_object_term_relationships( $post_id, get_object_taxonomies( $post->post_type ) );
7039  
7040      // Delete all for any posts.
7041      delete_metadata( 'post', 0, '_thumbnail_id', $post_id, true );
7042  
7043      wp_defer_comment_counting( true );
7044  
7045      $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d ORDER BY comment_ID DESC", $post_id ) );
7046      foreach ( $comment_ids as $comment_id ) {
7047          wp_delete_comment( $comment_id, true );
7048      }
7049  
7050      wp_defer_comment_counting( false );
7051  
7052      $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ) );
7053      foreach ( $post_meta_ids as $mid ) {
7054          delete_metadata_by_mid( 'post', $mid );
7055      }
7056  
7057      /** This action is documented in wp-includes/post.php */
7058      do_action( 'delete_post', $post_id, $post );
7059      $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
7060      if ( ! $result ) {
7061          return false;
7062      }
7063      /** This action is documented in wp-includes/post.php */
7064      do_action( 'deleted_post', $post_id, $post );
7065  
7066      wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file );
7067  
7068      clean_post_cache( $post );
7069  
7070      return $post;
7071  }
7072  
7073  /**
7074   * Deletes all files that belong to the given attachment.
7075   *
7076   * @since 4.9.7
7077   *
7078   * @global wpdb $wpdb WordPress database abstraction object.
7079   *
7080   * @param int    $post_id      Attachment ID.
7081   * @param array  $meta         The attachment's meta data.
7082   * @param array  $backup_sizes The meta data for the attachment's backup images.
7083   * @param string $file         Absolute path to the attachment's file.
7084   * @return bool True on success, false on failure.
7085   */
7086  function wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file ) {
7087      global $wpdb;
7088  
7089      $uploadpath = wp_get_upload_dir();
7090      $deleted    = true;
7091  
7092      if ( ! empty( $meta['thumb'] ) ) {
7093          // Don't delete the thumb if another attachment uses it.
7094          if ( ! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', $post_id ) ) ) {
7095              $thumbfile = str_replace( wp_basename( $file ), $meta['thumb'], $file );
7096  
7097              if ( ! empty( $thumbfile ) ) {
7098                  $thumbfile = path_join( $uploadpath['basedir'], $thumbfile );
7099                  $thumbdir  = path_join( $uploadpath['basedir'], dirname( $file ) );
7100  
7101                  if ( ! wp_delete_file_from_directory( $thumbfile, $thumbdir ) ) {
7102                      $deleted = false;
7103                  }
7104              }
7105          }
7106      }
7107  
7108      // Remove intermediate and backup images if there are any.
7109      if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
7110          $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7111  
7112          foreach ( $meta['sizes'] as $size => $sizeinfo ) {
7113              $intermediate_file = str_replace( wp_basename( $file ), $sizeinfo['file'], $file );
7114  
7115              if ( ! empty( $intermediate_file ) ) {
7116                  $intermediate_file = path_join( $uploadpath['basedir'], $intermediate_file );
7117  
7118                  if ( ! wp_delete_file_from_directory( $intermediate_file, $intermediate_dir ) ) {
7119                      $deleted = false;
7120                  }
7121              }
7122          }
7123      }
7124  
7125      if ( ! empty( $meta['original_image'] ) ) {
7126          if ( empty( $intermediate_dir ) ) {
7127              $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7128          }
7129  
7130          $original_image = str_replace( wp_basename( $file ), $meta['original_image'], $file );
7131  
7132          if ( ! empty( $original_image ) ) {
7133              $original_image = path_join( $uploadpath['basedir'], $original_image );
7134  
7135              if ( ! wp_delete_file_from_directory( $original_image, $intermediate_dir ) ) {
7136                  $deleted = false;
7137              }
7138          }
7139      }
7140  
7141      /*
7142       * Delete the source-format companion file. The client-side media flow can
7143       * sideload a source-format original (such as a HEIC file) alongside a
7144       * web-viewable derivative, recording its filename under the 'source_image'
7145       * key. This is kept separate from 'original_image', which continues to
7146       * point at the derivative.
7147       */
7148      if ( ! empty( $meta['source_image'] ) && is_string( $meta['source_image'] ) ) {
7149          if ( empty( $intermediate_dir ) ) {
7150              $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7151          }
7152  
7153          $source_image = str_replace( wp_basename( $file ), $meta['source_image'], $file );
7154  
7155          if ( ! empty( $source_image ) ) {
7156              $source_image = path_join( $uploadpath['basedir'], $source_image );
7157  
7158              if ( ! wp_delete_file_from_directory( $source_image, $intermediate_dir ) ) {
7159                  $deleted = false;
7160              }
7161          }
7162      }
7163  
7164      /*
7165       * Delete the animated-GIF video companions. When the client-side media flow
7166       * converts an opaque animated GIF to a web-safe video, the converted MP4/WebM
7167       * and a static first-frame JPEG poster are sideloaded alongside the GIF and
7168       * recorded under the 'animated_video' and 'animated_video_poster' keys. These
7169       * are kept separate from 'original_image', which continues to point at the GIF.
7170       */
7171      foreach ( array( 'animated_video', 'animated_video_poster' ) as $companion_key ) {
7172          if ( empty( $meta[ $companion_key ] ) || ! is_string( $meta[ $companion_key ] ) ) {
7173              continue;
7174          }
7175  
7176          if ( empty( $intermediate_dir ) ) {
7177              $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7178          }
7179  
7180          $companion_file = str_replace( wp_basename( $file ), $meta[ $companion_key ], $file );
7181  
7182          if ( ! empty( $companion_file ) ) {
7183              $companion_file = path_join( $uploadpath['basedir'], $companion_file );
7184  
7185              if ( ! wp_delete_file_from_directory( $companion_file, $intermediate_dir ) ) {
7186                  $deleted = false;
7187              }
7188          }
7189      }
7190  
7191      if ( is_array( $backup_sizes ) ) {
7192          $del_dir = path_join( $uploadpath['basedir'], dirname( $meta['file'] ) );
7193  
7194          foreach ( $backup_sizes as $size ) {
7195              $del_file = path_join( dirname( $meta['file'] ), $size['file'] );
7196  
7197              if ( ! empty( $del_file ) ) {
7198                  $del_file = path_join( $uploadpath['basedir'], $del_file );
7199  
7200                  if ( ! wp_delete_file_from_directory( $del_file, $del_dir ) ) {
7201                      $deleted = false;
7202                  }
7203              }
7204          }
7205      }
7206  
7207      if ( ! wp_delete_file_from_directory( $file, $uploadpath['basedir'] ) ) {
7208          $deleted = false;
7209      }
7210  
7211      return $deleted;
7212  }
7213  
7214  /**
7215   * Retrieves attachment metadata for attachment ID.
7216   *
7217   * @since 2.1.0
7218   * @since 6.0.0 The `$filesize` value was added to the returned array.
7219   * @since 7.1.0 `false` is now returned if the metadata is not an array, and when the result is
7220   *              filtered the `sizes` key is always an array when present.
7221   *
7222   * @param int  $attachment_id Attachment post ID. Defaults to global $post.
7223   * @param bool $unfiltered    Optional. If true, filters are not run. Default false.
7224   * @return array|false {
7225   *     Attachment metadata. False on failure.
7226   *
7227   *     @type int    $width      The width of the attachment.
7228   *     @type int    $height     The height of the attachment.
7229   *     @type string $file       The file path relative to `wp-content/uploads`.
7230   *     @type array  $sizes      Keys are size slugs, each value is an array containing
7231   *                              'file', 'width', 'height', and 'mime-type'.
7232   *     @type array  $image_meta Image metadata.
7233   *     @type int    $filesize   File size of the attachment.
7234   * }
7235   *
7236   * @phpstan-return array{
7237   *                     width?: int<1, max>,
7238   *                     height?: int<1, max>,
7239   *                     file?: non-empty-string,
7240   *                     filesize?: int<0, max>,
7241   *                     original_image?: non-empty-string,
7242   *                     source_image?: non-empty-string,
7243   *                     sizes?: array<non-empty-string, array{
7244   *                                                         file: non-empty-string,
7245   *                                                         width: int<1, max>,
7246   *                                                         height: int<1, max>,
7247   *                                                         'mime-type': non-empty-string,
7248   *                                                         filesize?: int<0, max>,
7249   *                                                         ...
7250   *                                                     }>,
7251   *                     image_meta?: array{
7252   *                                      aperture: numeric-string|int,
7253   *                                      credit: string,
7254   *                                      camera: string,
7255   *                                      caption: string,
7256   *                                      created_timestamp: numeric-string|int,
7257   *                                      copyright: string,
7258   *                                      focal_length: numeric-string|int,
7259   *                                      iso: numeric-string|int,
7260   *                                      shutter_speed: numeric-string|int,
7261   *                                      title: string,
7262   *                                      orientation: numeric-string|int,
7263   *                                      keywords: list<string>,
7264   *                                      alt: string,
7265   *                                  },
7266   *                     ...
7267   *                 }|false
7268   */
7269  function wp_get_attachment_metadata( $attachment_id = 0, $unfiltered = false ) {
7270      $attachment_id = (int) $attachment_id;
7271  
7272      if ( ! $attachment_id ) {
7273          $post = get_post();
7274  
7275          if ( ! $post ) {
7276              return false;
7277          }
7278  
7279          $attachment_id = $post->ID;
7280      }
7281  
7282      $data = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
7283  
7284      if ( ! is_array( $data ) || ! $data ) {
7285          return false;
7286      }
7287  
7288      if ( $unfiltered ) {
7289          return $data;
7290      }
7291  
7292      /**
7293       * Filters the attachment meta data.
7294       *
7295       * @since 2.1.0
7296       *
7297       * @param array $data          Array of meta data for the given attachment.
7298       * @param int   $attachment_id Attachment post ID.
7299       */
7300      $data = apply_filters( 'wp_get_attachment_metadata', $data, $attachment_id );
7301  
7302      if ( ! is_array( $data ) ) {
7303          return false;
7304      }
7305  
7306      if ( array_key_exists( 'sizes', $data ) && ! is_array( $data['sizes'] ) ) {
7307          $data['sizes'] = array();
7308      }
7309  
7310      return $data;
7311  }
7312  
7313  /**
7314   * Updates metadata for an attachment.
7315   *
7316   * @since 2.1.0
7317   *
7318   * @param int   $attachment_id Attachment post ID.
7319   * @param array $data          Attachment meta data.
7320   * @return int|bool Whether the metadata was successfully updated.
7321   *                  True on success, the Meta ID if the key didn't exist.
7322   *                  False if $post is invalid, on failure, or if $data is the same as the existing metadata.
7323   */
7324  function wp_update_attachment_metadata( $attachment_id, $data ) {
7325      $attachment_id = (int) $attachment_id;
7326  
7327      $post = get_post( $attachment_id );
7328  
7329      if ( ! $post ) {
7330          return false;
7331      }
7332  
7333      /**
7334       * Filters the updated attachment meta data.
7335       *
7336       * @since 2.1.0
7337       *
7338       * @param array $data          Array of updated attachment meta data.
7339       * @param int   $attachment_id Attachment post ID.
7340       */
7341      $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
7342      if ( $data ) {
7343          return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
7344      } else {
7345          return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
7346      }
7347  }
7348  
7349  /**
7350   * Retrieves the URL for an attachment.
7351   *
7352   * @since 2.1.0
7353   *
7354   * @global string $pagenow The filename of the current screen.
7355   *
7356   * @param int $attachment_id Optional. Attachment post ID. Defaults to global $post.
7357   * @return string|false Attachment URL, otherwise false.
7358   */
7359  function wp_get_attachment_url( $attachment_id = 0 ) {
7360      global $pagenow;
7361  
7362      $attachment_id = (int) $attachment_id;
7363  
7364      $post = get_post( $attachment_id );
7365  
7366      if ( ! $post ) {
7367          return false;
7368      }
7369  
7370      if ( 'attachment' !== $post->post_type ) {
7371          return false;
7372      }
7373  
7374      $url = '';
7375      // Get attached file.
7376      $file = get_post_meta( $post->ID, '_wp_attached_file', true );
7377      if ( $file ) {
7378          // Get upload directory.
7379          $uploads = wp_get_upload_dir();
7380          if ( $uploads && false === $uploads['error'] ) {
7381              // Check that the upload base exists in the file location.
7382              if ( str_starts_with( $file, $uploads['basedir'] ) ) {
7383                  // Replace file location with url location.
7384                  $url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file );
7385              } elseif ( str_contains( $file, 'wp-content/uploads' ) ) {
7386                  // Get the directory name relative to the basedir (back compat for pre-2.7 uploads).
7387                  $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . wp_basename( $file );
7388              } else {
7389                  // It's a newly-uploaded file, therefore $file is relative to the basedir.
7390                  $url = $uploads['baseurl'] . "/$file";
7391              }
7392          }
7393      }
7394  
7395      /*
7396       * If any of the above options failed, Fallback on the GUID as used pre-2.7,
7397       * not recommended to rely upon this.
7398       */
7399      if ( ! $url ) {
7400          $url = get_the_guid( $post->ID );
7401      }
7402  
7403      // On SSL front end, URLs should be HTTPS.
7404      if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $pagenow ) {
7405          $url = set_url_scheme( $url );
7406      }
7407  
7408      /**
7409       * Filters the attachment URL.
7410       *
7411       * @since 2.1.0
7412       *
7413       * @param string $url           URL for the given attachment.
7414       * @param int    $attachment_id Attachment post ID.
7415       */
7416      $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
7417  
7418      if ( ! $url ) {
7419          return false;
7420      }
7421  
7422      return $url;
7423  }
7424  
7425  /**
7426   * Retrieves the caption for an attachment.
7427   *
7428   * @since 4.6.0
7429   *
7430   * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
7431   * @return string|false Attachment caption on success, false on failure.
7432   */
7433  function wp_get_attachment_caption( $post_id = 0 ) {
7434      $post_id = (int) $post_id;
7435      $post    = get_post( $post_id );
7436  
7437      if ( ! $post ) {
7438          return false;
7439      }
7440  
7441      if ( 'attachment' !== $post->post_type ) {
7442          return false;
7443      }
7444  
7445      $caption = $post->post_excerpt;
7446  
7447      /**
7448       * Filters the attachment caption.
7449       *
7450       * @since 4.6.0
7451       *
7452       * @param string $caption Caption for the given attachment.
7453       * @param int    $post_id Attachment ID.
7454       */
7455      return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
7456  }
7457  
7458  /**
7459   * Retrieves URL for an attachment thumbnail.
7460   *
7461   * @since 2.1.0
7462   * @since 6.1.0 Changed to use wp_get_attachment_image_url().
7463   *
7464   * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
7465   * @return string|false Thumbnail URL on success, false on failure.
7466   */
7467  function wp_get_attachment_thumb_url( $post_id = 0 ) {
7468      $post_id = (int) $post_id;
7469  
7470      /*
7471       * This uses image_downsize() which also looks for the (very) old format $image_meta['thumb']
7472       * when the newer format $image_meta['sizes']['thumbnail'] doesn't exist.
7473       */
7474      $thumbnail_url = wp_get_attachment_image_url( $post_id, 'thumbnail' );
7475  
7476      if ( empty( $thumbnail_url ) ) {
7477          return false;
7478      }
7479  
7480      /**
7481       * Filters the attachment thumbnail URL.
7482       *
7483       * @since 2.1.0
7484       *
7485       * @param string $thumbnail_url URL for the attachment thumbnail.
7486       * @param int    $post_id       Attachment ID.
7487       */
7488      return apply_filters( 'wp_get_attachment_thumb_url', $thumbnail_url, $post_id );
7489  }
7490  
7491  /**
7492   * Verifies an attachment is of a given type.
7493   *
7494   * @since 4.2.0
7495   *
7496   * @param string      $type Attachment type. Accepts `image`, `audio`, `video`, or a file extension.
7497   * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
7498   * @return bool True if an accepted type or a matching file extension, false otherwise.
7499   */
7500  function wp_attachment_is( $type, $post = null ) {
7501      $post = get_post( $post );
7502  
7503      if ( ! $post ) {
7504          return false;
7505      }
7506  
7507      $file = get_attached_file( $post->ID );
7508  
7509      if ( ! $file ) {
7510          return false;
7511      }
7512  
7513      if ( str_starts_with( $post->post_mime_type, $type . '/' ) ) {
7514          return true;
7515      }
7516  
7517      $check = wp_check_filetype( $file );
7518  
7519      if ( empty( $check['ext'] ) ) {
7520          return false;
7521      }
7522  
7523      $ext = $check['ext'];
7524  
7525      if ( 'import' !== $post->post_mime_type ) {
7526          return $type === $ext;
7527      }
7528  
7529      switch ( $type ) {
7530          case 'image':
7531              $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'webp', 'avif', 'heic' );
7532              return in_array( $ext, $image_exts, true );
7533  
7534          case 'audio':
7535              return in_array( $ext, wp_get_audio_extensions(), true );
7536  
7537          case 'video':
7538              return in_array( $ext, wp_get_video_extensions(), true );
7539  
7540          default:
7541              return $type === $ext;
7542      }
7543  }
7544  
7545  /**
7546   * Determines whether an attachment is an image.
7547   *
7548   * For more information on this and similar theme functions, check out
7549   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
7550   * Conditional Tags} article in the Theme Developer Handbook.
7551   *
7552   * @since 2.1.0
7553   * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
7554   *              allowed WP_Post object to be passed.
7555   *
7556   * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
7557   * @return bool Whether the attachment is an image.
7558   */
7559  function wp_attachment_is_image( $post = null ) {
7560      return wp_attachment_is( 'image', $post );
7561  }
7562  
7563  /**
7564   * Retrieves the icon for a MIME type or attachment.
7565   *
7566   * @since 2.1.0
7567   * @since 6.5.0 Added the `$preferred_ext` parameter.
7568   *
7569   * @param string|int $mime          MIME type or attachment ID.
7570   * @param string     $preferred_ext File format to prefer in return. Default '.png'.
7571   * @return string|false Icon, false otherwise.
7572   */
7573  function wp_mime_type_icon( $mime = 0, $preferred_ext = '.png' ) {
7574      if ( ! is_numeric( $mime ) ) {
7575          $icon = wp_cache_get( "mime_type_icon_$mime" );
7576      }
7577  
7578      // Check if preferred file format variable is present and is a validly formatted file extension.
7579      if ( ! empty( $preferred_ext ) && is_string( $preferred_ext ) && ! str_starts_with( $preferred_ext, '.' ) ) {
7580          $preferred_ext = '.' . strtolower( $preferred_ext );
7581      }
7582  
7583      $post_id = 0;
7584      if ( empty( $icon ) ) {
7585          $post_mimes = array();
7586          if ( is_numeric( $mime ) ) {
7587              $mime = (int) $mime;
7588              $post = get_post( $mime );
7589              if ( $post ) {
7590                  $post_id = (int) $post->ID;
7591                  $file    = get_attached_file( $post_id );
7592                  $ext     = preg_replace( '/^.+?\.([^.]+)$/', '$1', $file );
7593                  if ( ! empty( $ext ) ) {
7594                      $post_mimes[] = $ext;
7595                      $ext_type     = wp_ext2type( $ext );
7596                      if ( $ext_type ) {
7597                          $post_mimes[] = $ext_type;
7598                      }
7599                  }
7600                  $mime = $post->post_mime_type;
7601              } else {
7602                  $mime = 0;
7603              }
7604          } else {
7605              $post_mimes[] = $mime;
7606          }
7607  
7608          $icon_files = wp_cache_get( 'icon_files' );
7609  
7610          if ( ! is_array( $icon_files ) ) {
7611              /**
7612               * Filters the icon directory path.
7613               *
7614               * @since 2.0.0
7615               *
7616               * @param string $path Icon directory absolute path.
7617               */
7618              $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
7619  
7620              /**
7621               * Filters the icon directory URI.
7622               *
7623               * @since 2.0.0
7624               *
7625               * @param string $uri Icon directory URI.
7626               */
7627              $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
7628  
7629              /**
7630               * Filters the array of icon directory URIs.
7631               *
7632               * @since 2.5.0
7633               *
7634               * @param string[] $uris Array of icon directory URIs keyed by directory absolute path.
7635               */
7636              $dirs       = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
7637              $icon_files = array();
7638              $all_icons  = array();
7639              while ( $dirs ) {
7640                  $keys = array_keys( $dirs );
7641                  $dir  = array_shift( $keys );
7642                  $uri  = array_shift( $dirs );
7643                  $dh   = opendir( $dir );
7644                  if ( $dh ) {
7645                      while ( false !== $file = readdir( $dh ) ) {
7646                          $file = wp_basename( $file );
7647                          if ( str_starts_with( $file, '.' ) ) {
7648                              continue;
7649                          }
7650  
7651                          $ext = strtolower( substr( $file, -4 ) );
7652                          if ( ! in_array( $ext, array( '.svg', '.png', '.gif', '.jpg' ), true ) ) {
7653                              if ( is_dir( "$dir/$file" ) ) {
7654                                  $dirs[ "$dir/$file" ] = "$uri/$file";
7655                              }
7656                              continue;
7657                          }
7658                          $all_icons[ "$dir/$file" ] = "$uri/$file";
7659                          if ( $ext === $preferred_ext ) {
7660                              $icon_files[ "$dir/$file" ] = "$uri/$file";
7661                          }
7662                      }
7663                      closedir( $dh );
7664                  }
7665              }
7666              // If directory only contained icons of a non-preferred format, return those.
7667              if ( empty( $icon_files ) ) {
7668                  $icon_files = $all_icons;
7669              }
7670              wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
7671          }
7672  
7673          $types = array();
7674          // Icon wp_basename - extension = MIME wildcard.
7675          foreach ( $icon_files as $file => $uri ) {
7676              $types[ preg_replace( '/^([^.]*).*$/', '$1', wp_basename( $file ) ) ] =& $icon_files[ $file ];
7677          }
7678  
7679          if ( ! empty( $mime ) ) {
7680              $post_mimes[] = substr( $mime, 0, strpos( $mime, '/' ) );
7681              $post_mimes[] = substr( $mime, strpos( $mime, '/' ) + 1 );
7682              $post_mimes[] = str_replace( '/', '_', $mime );
7683          }
7684  
7685          $matches            = wp_match_mime_types( array_keys( $types ), $post_mimes );
7686          $matches['default'] = array( 'default' );
7687  
7688          foreach ( $matches as $match => $wilds ) {
7689              foreach ( $wilds as $wild ) {
7690                  if ( ! isset( $types[ $wild ] ) ) {
7691                      continue;
7692                  }
7693  
7694                  $icon = $types[ $wild ];
7695                  if ( ! is_numeric( $mime ) ) {
7696                      wp_cache_add( "mime_type_icon_$mime", $icon );
7697                  }
7698                  break 2;
7699              }
7700          }
7701      }
7702  
7703      /**
7704       * Filters the mime type icon.
7705       *
7706       * @since 2.1.0
7707       *
7708       * @param string $icon    Path to the mime type icon.
7709       * @param string $mime    Mime type.
7710       * @param int    $post_id Attachment ID. Will equal 0 if the function passed
7711       *                        the mime type.
7712       */
7713      return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
7714  }
7715  
7716  /**
7717   * Checks for changed slugs for published post objects and save the old slug.
7718   *
7719   * The function is used when a post object of any type is updated,
7720   * by comparing the current and previous post objects.
7721   *
7722   * If the slug was changed and not already part of the old slugs then it will be
7723   * added to the post meta field ('_wp_old_slug') for storing old slugs for that
7724   * post.
7725   *
7726   * The most logically usage of this function is redirecting changed post objects, so
7727   * that those that linked to an changed post will be redirected to the new post.
7728   *
7729   * @since 2.1.0
7730   *
7731   * @param int     $post_id     Post ID.
7732   * @param WP_Post $post        The post object.
7733   * @param WP_Post $post_before The previous post object.
7734   */
7735  function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
7736      // Don't bother if it hasn't changed.
7737      if ( $post->post_name === $post_before->post_name ) {
7738          return;
7739      }
7740  
7741      // We're only concerned with published, non-hierarchical objects.
7742      if ( ! ( 'publish' === $post->post_status || ( 'attachment' === $post->post_type && 'inherit' === $post->post_status ) )
7743          || is_post_type_hierarchical( $post->post_type )
7744      ) {
7745          return;
7746      }
7747  
7748      $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
7749  
7750      // If we haven't added this old slug before, add it now.
7751      if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs, true ) ) {
7752          add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
7753      }
7754  
7755      // If the new slug was used previously, delete it from the list.
7756      if ( in_array( $post->post_name, $old_slugs, true ) ) {
7757          delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
7758      }
7759  }
7760  
7761  /**
7762   * Checks for changed dates for published post objects and save the old date.
7763   *
7764   * The function is used when a post object of any type is updated,
7765   * by comparing the current and previous post objects.
7766   *
7767   * If the date was changed and not already part of the old dates then it will be
7768   * added to the post meta field ('_wp_old_date') for storing old dates for that
7769   * post.
7770   *
7771   * The most logically usage of this function is redirecting changed post objects, so
7772   * that those that linked to an changed post will be redirected to the new post.
7773   *
7774   * @since 4.9.3
7775   *
7776   * @param int     $post_id     Post ID.
7777   * @param WP_Post $post        The post object.
7778   * @param WP_Post $post_before The previous post object.
7779   */
7780  function wp_check_for_changed_dates( $post_id, $post, $post_before ) {
7781      $previous_date = gmdate( 'Y-m-d', strtotime( $post_before->post_date ) );
7782      $new_date      = gmdate( 'Y-m-d', strtotime( $post->post_date ) );
7783  
7784      // Don't bother if it hasn't changed.
7785      if ( $new_date === $previous_date ) {
7786          return;
7787      }
7788  
7789      // We're only concerned with published, non-hierarchical objects.
7790      if ( ! ( 'publish' === $post->post_status || ( 'attachment' === $post->post_type && 'inherit' === $post->post_status ) )
7791          || is_post_type_hierarchical( $post->post_type )
7792      ) {
7793          return;
7794      }
7795  
7796      $old_dates = (array) get_post_meta( $post_id, '_wp_old_date' );
7797  
7798      // If we haven't added this old date before, add it now.
7799      if ( ! empty( $previous_date ) && ! in_array( $previous_date, $old_dates, true ) ) {
7800          add_post_meta( $post_id, '_wp_old_date', $previous_date );
7801      }
7802  
7803      // If the new slug was used previously, delete it from the list.
7804      if ( in_array( $new_date, $old_dates, true ) ) {
7805          delete_post_meta( $post_id, '_wp_old_date', $new_date );
7806      }
7807  }
7808  
7809  /**
7810   * Retrieves the private post SQL based on capability.
7811   *
7812   * This function provides a standardized way to appropriately select on the
7813   * post_status of a post type. The function will return a piece of SQL code
7814   * that can be added to a WHERE clause; this SQL is constructed to allow all
7815   * published posts, and all private posts to which the user has access.
7816   *
7817   * @since 2.2.0
7818   * @since 4.3.0 Added the ability to pass an array to `$post_type`.
7819   *
7820   * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
7821   * @return string SQL code that can be added to a where clause.
7822   */
7823  function get_private_posts_cap_sql( $post_type ) {
7824      return get_posts_by_author_sql( $post_type, false );
7825  }
7826  
7827  /**
7828   * Retrieves the post SQL based on capability, author, and type.
7829   *
7830   * @since 3.0.0
7831   * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
7832   *
7833   * @see get_private_posts_cap_sql()
7834   * @global wpdb $wpdb WordPress database abstraction object.
7835   *
7836   * @param string|string[] $post_type   Single post type or an array of post types.
7837   * @param bool            $full        Optional. Returns a full WHERE statement instead of just
7838   *                                     an 'andalso' term. Default true.
7839   * @param int             $post_author Optional. Query posts having a single author ID. Default null.
7840   * @param bool            $public_only Optional. Only return public posts. Skips cap checks for
7841   *                                     $current_user.  Default false.
7842   * @return string SQL WHERE code that can be added to a query.
7843   */
7844  function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
7845      global $wpdb;
7846  
7847      if ( is_array( $post_type ) ) {
7848          $post_types = $post_type;
7849      } else {
7850          $post_types = array( $post_type );
7851      }
7852  
7853      $post_type_clauses = array();
7854      foreach ( $post_types as $post_type ) {
7855          $post_type_obj = get_post_type_object( $post_type );
7856  
7857          if ( ! $post_type_obj ) {
7858              continue;
7859          }
7860  
7861          /**
7862           * Filters the capability to read private posts for a custom post type
7863           * when generating SQL for getting posts by author.
7864           *
7865           * @since 2.2.0
7866           * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
7867           *
7868           * @param string $cap Capability.
7869           */
7870          $cap = apply_filters_deprecated( 'pub_priv_sql_capability', array( '' ), '3.2.0' );
7871  
7872          if ( ! $cap ) {
7873              $cap = current_user_can( $post_type_obj->cap->read_private_posts );
7874          }
7875  
7876          // Only need to check the cap if $public_only is false.
7877          $post_status_sql = "post_status = 'publish'";
7878  
7879          if ( false === $public_only ) {
7880              if ( $cap ) {
7881                  // Does the user have the capability to view private posts? Guess so.
7882                  $post_status_sql .= " OR post_status = 'private'";
7883              } elseif ( is_user_logged_in() ) {
7884                  // Users can view their own private posts.
7885                  $id = get_current_user_id();
7886                  if ( null === $post_author || ! $full ) {
7887                      $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
7888                  } elseif ( $id === (int) $post_author ) {
7889                      $post_status_sql .= " OR post_status = 'private'";
7890                  } // Else none.
7891              } // Else none.
7892          }
7893  
7894          $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
7895      }
7896  
7897      if ( empty( $post_type_clauses ) ) {
7898          return $full ? 'WHERE 1 = 0' : '1 = 0';
7899      }
7900  
7901      $sql = '( ' . implode( ' OR ', $post_type_clauses ) . ' )';
7902  
7903      if ( null !== $post_author ) {
7904          $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
7905      }
7906  
7907      if ( $full ) {
7908          $sql = 'WHERE ' . $sql;
7909      }
7910  
7911      return $sql;
7912  }
7913  
7914  /**
7915   * Retrieves the most recent time that a post on the site was published.
7916   *
7917   * The server timezone is the default and is the difference between GMT and
7918   * server time. The 'blog' value is the date when the last post was posted.
7919   * The 'gmt' is when the last post was posted in GMT formatted date.
7920   *
7921   * @since 0.71
7922   * @since 4.4.0 The `$post_type` argument was added.
7923   *
7924   * @param string $timezone  Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
7925   *                          'server' uses the server's internal timezone.
7926   *                          'blog' uses the `post_date` field, which proxies to the timezone set for the site.
7927   *                          'gmt' uses the `post_date_gmt` field.
7928   *                          Default 'server'.
7929   * @param string $post_type Optional. The post type to check. Default 'any'.
7930   * @return string The date of the last post, or false on failure.
7931   */
7932  function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
7933      $lastpostdate = _get_last_post_time( $timezone, 'date', $post_type );
7934  
7935      /**
7936       * Filters the most recent time that a post on the site was published.
7937       *
7938       * @since 2.3.0
7939       * @since 5.5.0 Added the `$post_type` parameter.
7940       *
7941       * @param string|false $lastpostdate The most recent time that a post was published,
7942       *                                   in 'Y-m-d H:i:s' format. False on failure.
7943       * @param string       $timezone     Location to use for getting the post published date.
7944       *                                   See get_lastpostdate() for accepted `$timezone` values.
7945       * @param string       $post_type    The post type to check.
7946       */
7947      return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone, $post_type );
7948  }
7949  
7950  /**
7951   * Gets the most recent time that a post on the site was modified.
7952   *
7953   * The server timezone is the default and is the difference between GMT and
7954   * server time. The 'blog' value is just when the last post was modified.
7955   * The 'gmt' is when the last post was modified in GMT time.
7956   *
7957   * @since 1.2.0
7958   * @since 4.4.0 The `$post_type` argument was added.
7959   *
7960   * @param string $timezone  Optional. The timezone for the timestamp. See get_lastpostdate()
7961   *                          for information on accepted values.
7962   *                          Default 'server'.
7963   * @param string $post_type Optional. The post type to check. Default 'any'.
7964   * @return string The timestamp in 'Y-m-d H:i:s' format, or false on failure.
7965   */
7966  function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
7967      /**
7968       * Pre-filter the return value of get_lastpostmodified() before the query is run.
7969       *
7970       * @since 4.4.0
7971       *
7972       * @param string|false $lastpostmodified The most recent time that a post was modified,
7973       *                                       in 'Y-m-d H:i:s' format, or false. Returning anything
7974       *                                       other than false will short-circuit the function.
7975       * @param string       $timezone         Location to use for getting the post modified date.
7976       *                                       See get_lastpostdate() for accepted `$timezone` values.
7977       * @param string       $post_type        The post type to check.
7978       */
7979      $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
7980  
7981      if ( false !== $lastpostmodified ) {
7982          return $lastpostmodified;
7983      }
7984  
7985      $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
7986      $lastpostdate     = get_lastpostdate( $timezone, $post_type );
7987  
7988      if ( $lastpostdate > $lastpostmodified ) {
7989          $lastpostmodified = $lastpostdate;
7990      }
7991  
7992      /**
7993       * Filters the most recent time that a post on the site was modified.
7994       *
7995       * @since 2.3.0
7996       * @since 5.5.0 Added the `$post_type` parameter.
7997       *
7998       * @param string|false $lastpostmodified The most recent time that a post was modified,
7999       *                                       in 'Y-m-d H:i:s' format. False on failure.
8000       * @param string       $timezone         Location to use for getting the post modified date.
8001       *                                       See get_lastpostdate() for accepted `$timezone` values.
8002       * @param string       $post_type        The post type to check.
8003       */
8004      return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone, $post_type );
8005  }
8006  
8007  /**
8008   * Gets the timestamp of the last time any post was modified or published.
8009   *
8010   * @since 3.1.0
8011   * @since 4.4.0 The `$post_type` argument was added.
8012   * @access private
8013   *
8014   * @global wpdb $wpdb WordPress database abstraction object.
8015   *
8016   * @param string $timezone  The timezone for the timestamp. See get_lastpostdate().
8017   *                          for information on accepted values.
8018   * @param string $field     Post field to check. Accepts 'date' or 'modified'.
8019   * @param string $post_type Optional. The post type to check. Default 'any'.
8020   * @return string|false The timestamp in 'Y-m-d H:i:s' format, or false on failure.
8021   */
8022  function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
8023      global $wpdb;
8024  
8025      if ( ! in_array( $field, array( 'date', 'modified' ), true ) ) {
8026          return false;
8027      }
8028  
8029      $timezone = strtolower( $timezone );
8030  
8031      $key = "lastpost{$field}:$timezone";
8032      if ( 'any' !== $post_type ) {
8033          $key .= ':' . sanitize_key( $post_type );
8034      }
8035  
8036      $date = wp_cache_get( $key, 'timeinfo' );
8037      if ( false !== $date ) {
8038          return $date;
8039      }
8040  
8041      if ( 'any' === $post_type ) {
8042          $post_types = get_post_types( array( 'public' => true ) );
8043          array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
8044          $post_types = "'" . implode( "', '", $post_types ) . "'";
8045      } else {
8046          $post_types = "'" . sanitize_key( $post_type ) . "'";
8047      }
8048  
8049      switch ( $timezone ) {
8050          case 'gmt':
8051              $date = $wpdb->get_var( "SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
8052              break;
8053          case 'blog':
8054              $date = $wpdb->get_var( "SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
8055              break;
8056          case 'server':
8057              $add_seconds_server = gmdate( 'Z' );
8058              $date               = $wpdb->get_var( "SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
8059              break;
8060      }
8061  
8062      if ( $date ) {
8063          wp_cache_set( $key, $date, 'timeinfo' );
8064  
8065          return $date;
8066      }
8067  
8068      return false;
8069  }
8070  
8071  /**
8072   * Updates posts in cache.
8073   *
8074   * @since 1.5.1
8075   *
8076   * @param WP_Post[] $posts Array of post objects (passed by reference).
8077   */
8078  function update_post_cache( &$posts ) {
8079      if ( ! $posts ) {
8080          return;
8081      }
8082  
8083      $data = array();
8084      foreach ( $posts as $post ) {
8085          if ( empty( $post->filter ) || 'raw' !== $post->filter ) {
8086              $post = sanitize_post( $post, 'raw' );
8087          }
8088          $data[ $post->ID ] = $post;
8089      }
8090      wp_cache_add_multiple( $data, 'posts' );
8091  }
8092  
8093  /**
8094   * Will clean the post in the cache.
8095   *
8096   * Cleaning means delete from the cache of the post. Will call to clean the term
8097   * object cache associated with the post ID.
8098   *
8099   * This function not run if $_wp_suspend_cache_invalidation is not empty. See
8100   * wp_suspend_cache_invalidation().
8101   *
8102   * @since 2.0.0
8103   *
8104   * @global bool $_wp_suspend_cache_invalidation
8105   *
8106   * @param int|WP_Post $post Post ID or post object to remove from the cache.
8107   */
8108  function clean_post_cache( $post ) {
8109      global $_wp_suspend_cache_invalidation;
8110  
8111      if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
8112          return;
8113      }
8114  
8115      $post = get_post( $post );
8116  
8117      if ( ! $post ) {
8118          return;
8119      }
8120  
8121      wp_cache_delete( $post->ID, 'posts' );
8122      wp_cache_delete( 'post_parent:' . (string) $post->ID, 'posts' );
8123      wp_cache_delete( $post->ID, 'post_meta' );
8124  
8125      clean_object_term_cache( $post->ID, $post->post_type );
8126  
8127      wp_cache_delete( 'wp_get_archives', 'general' );
8128  
8129      /**
8130       * Fires immediately after the given post's cache is cleaned.
8131       *
8132       * @since 2.5.0
8133       *
8134       * @param int     $post_id Post ID.
8135       * @param WP_Post $post    Post object.
8136       */
8137      do_action( 'clean_post_cache', $post->ID, $post );
8138  
8139      if ( 'page' === $post->post_type ) {
8140          wp_cache_delete( 'all_page_ids', 'posts' );
8141  
8142          /**
8143           * Fires immediately after the given page's cache is cleaned.
8144           *
8145           * @since 2.5.0
8146           *
8147           * @param int $post_id Post ID.
8148           */
8149          do_action( 'clean_page_cache', $post->ID );
8150      }
8151  
8152      wp_cache_set_posts_last_changed();
8153  }
8154  
8155  /**
8156   * Updates post, term, and metadata caches for a list of post objects.
8157   *
8158   * @since 1.5.0
8159   *
8160   * @param WP_Post[]       $posts             Array of post objects (passed by reference).
8161   * @param string|string[] $post_type         Optional. Single post type, 'any', or an array of post types.
8162   *                                           Default 'post'.
8163   * @param bool            $update_term_cache Optional. Whether to update the term cache. Default true.
8164   * @param bool            $update_meta_cache Optional. Whether to update the meta cache. Default true.
8165   */
8166  function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
8167      // No point in doing all this work if we didn't match any posts.
8168      if ( ! $posts ) {
8169          return;
8170      }
8171  
8172      update_post_cache( $posts );
8173  
8174      $post_ids = array();
8175      foreach ( $posts as $post ) {
8176          $post_ids[] = $post->ID;
8177      }
8178  
8179      if ( ! $post_type ) {
8180          $post_type = 'any';
8181      }
8182  
8183      if ( $update_term_cache ) {
8184          if ( is_array( $post_type ) ) {
8185              $ptypes = $post_type;
8186          } elseif ( 'any' === $post_type ) {
8187              $ptypes = array();
8188              // Just use the post_types in the supplied posts.
8189              foreach ( $posts as $post ) {
8190                  $ptypes[] = $post->post_type;
8191              }
8192              $ptypes = array_unique( $ptypes );
8193          } else {
8194              $ptypes = array( $post_type );
8195          }
8196  
8197          if ( ! empty( $ptypes ) ) {
8198              update_object_term_cache( $post_ids, $ptypes );
8199          }
8200      }
8201  
8202      if ( $update_meta_cache ) {
8203          update_postmeta_cache( $post_ids );
8204      }
8205  }
8206  
8207  /**
8208   * Updates post author user caches for a list of post objects.
8209   *
8210   * @since 6.1.0
8211   *
8212   * @param WP_Post[] $posts Array of post objects.
8213   */
8214  function update_post_author_caches( $posts ) {
8215      /*
8216       * cache_users() is a pluggable function so is not available prior
8217       * to the `plugins_loaded` hook firing. This is to ensure against
8218       * fatal errors when the function is not available.
8219       */
8220      if ( ! function_exists( 'cache_users' ) ) {
8221          return;
8222      }
8223  
8224      $author_ids = wp_list_pluck( $posts, 'post_author' );
8225      $author_ids = array_map( 'absint', $author_ids );
8226      $author_ids = array_unique( array_filter( $author_ids ) );
8227  
8228      cache_users( $author_ids );
8229  }
8230  
8231  /**
8232   * Updates parent post caches for a list of post objects.
8233   *
8234   * @since 6.1.0
8235   *
8236   * @param WP_Post[] $posts Array of post objects.
8237   */
8238  function update_post_parent_caches( $posts ) {
8239      $parent_ids = wp_list_pluck( $posts, 'post_parent' );
8240      $parent_ids = array_map( 'absint', $parent_ids );
8241      $parent_ids = array_unique( array_filter( $parent_ids ) );
8242  
8243      if ( ! empty( $parent_ids ) ) {
8244          _prime_post_caches( $parent_ids, false );
8245      }
8246  }
8247  
8248  /**
8249   * Updates metadata cache for a list of post IDs.
8250   *
8251   * Performs SQL query to retrieve the metadata for the post IDs and updates the
8252   * metadata cache for the posts. Therefore, the functions, which call this
8253   * function, do not need to perform SQL queries on their own.
8254   *
8255   * @since 2.1.0
8256   *
8257   * @param int[] $post_ids Array of post IDs.
8258   * @return array|false An array of metadata on success, false if there is nothing to update.
8259   */
8260  function update_postmeta_cache( $post_ids ) {
8261      return update_meta_cache( 'post', $post_ids );
8262  }
8263  
8264  /**
8265   * Will clean the attachment in the cache.
8266   *
8267   * Cleaning means delete from the cache. Optionally will clean the term
8268   * object cache associated with the attachment ID.
8269   *
8270   * This function will not run if $_wp_suspend_cache_invalidation is not empty.
8271   *
8272   * @since 3.0.0
8273   *
8274   * @global bool $_wp_suspend_cache_invalidation
8275   *
8276   * @param int  $id          The attachment ID in the cache to clean.
8277   * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
8278   */
8279  function clean_attachment_cache( $id, $clean_terms = false ) {
8280      global $_wp_suspend_cache_invalidation;
8281  
8282      if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
8283          return;
8284      }
8285  
8286      $id = (int) $id;
8287  
8288      wp_cache_delete( $id, 'posts' );
8289      wp_cache_delete( $id, 'post_meta' );
8290  
8291      if ( $clean_terms ) {
8292          clean_object_term_cache( $id, 'attachment' );
8293      }
8294  
8295      /**
8296       * Fires after the given attachment's cache is cleaned.
8297       *
8298       * @since 3.0.0
8299       *
8300       * @param int $id Attachment ID.
8301       */
8302      do_action( 'clean_attachment_cache', $id );
8303  }
8304  
8305  //
8306  // Hooks.
8307  //
8308  
8309  /**
8310   * Hook for managing future post transitions to published.
8311   *
8312   * @since 2.3.0
8313   * @access private
8314   *
8315   * @see wp_clear_scheduled_hook()
8316   * @global wpdb $wpdb WordPress database abstraction object.
8317   *
8318   * @param string  $new_status New post status.
8319   * @param string  $old_status Previous post status.
8320   * @param WP_Post $post       Post object.
8321   */
8322  function _transition_post_status( $new_status, $old_status, $post ) {
8323      global $wpdb;
8324  
8325      if ( 'publish' !== $old_status && 'publish' === $new_status ) {
8326          // Reset GUID if transitioning to publish and it is empty.
8327          if ( '' === get_the_guid( $post->ID ) ) {
8328              $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
8329          }
8330  
8331          /**
8332           * Fires when a post's status is transitioned from private to published.
8333           *
8334           * @since 1.5.0
8335           * @deprecated 2.3.0 Use {@see 'private_to_publish'} instead.
8336           *
8337           * @param int $post_id Post ID.
8338           */
8339          do_action_deprecated( 'private_to_published', array( $post->ID ), '2.3.0', 'private_to_publish' );
8340      }
8341  
8342      // If published posts changed clear the lastpostmodified cache.
8343      if ( 'publish' === $new_status || 'publish' === $old_status ) {
8344          foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
8345              wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
8346              wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
8347              wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
8348          }
8349      }
8350  
8351      if ( $new_status !== $old_status ) {
8352          wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
8353          wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
8354      }
8355  
8356      // Always clears the hook in case the post status bounced from future to draft.
8357      wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
8358  }
8359  
8360  /**
8361   * Hook used to schedule publication for a post marked for the future.
8362   *
8363   * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
8364   *
8365   * @since 2.3.0
8366   * @access private
8367   *
8368   * @param int     $deprecated Not used. Can be set to null. Never implemented. Not marked
8369   *                            as deprecated with _deprecated_argument() as it conflicts with
8370   *                            wp_transition_post_status() and the default filter for _future_post_hook().
8371   * @param WP_Post $post       Post object.
8372   */
8373  function _future_post_hook( $deprecated, $post ) {
8374      wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
8375      wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT' ), 'publish_future_post', array( $post->ID ) );
8376  }
8377  
8378  /**
8379   * Hook to schedule pings and enclosures when a post is published.
8380   *
8381   * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
8382   *
8383   * @since 2.3.0
8384   * @access private
8385   *
8386   * @param int $post_id The ID of the post being published.
8387   */
8388  function _publish_post_hook( $post_id ) {
8389      if ( defined( 'XMLRPC_REQUEST' ) ) {
8390          /**
8391           * Fires when _publish_post_hook() is called during an XML-RPC request.
8392           *
8393           * @since 2.1.0
8394           *
8395           * @param int $post_id Post ID.
8396           */
8397          do_action( 'xmlrpc_publish_post', $post_id );
8398      }
8399  
8400      if ( defined( 'WP_IMPORTING' ) ) {
8401          return;
8402      }
8403  
8404      if ( get_option( 'default_pingback_flag' ) ) {
8405          add_post_meta( $post_id, '_pingme', '1', true );
8406      }
8407      add_post_meta( $post_id, '_encloseme', '1', true );
8408  
8409      $to_ping = get_to_ping( $post_id );
8410      if ( ! empty( $to_ping ) ) {
8411          add_post_meta( $post_id, '_trackbackme', '1' );
8412      }
8413  
8414      if ( ! wp_next_scheduled( 'do_pings' ) ) {
8415          wp_schedule_single_event( time(), 'do_pings' );
8416      }
8417  }
8418  
8419  /**
8420   * Returns the ID of the post's parent.
8421   *
8422   * @since 3.1.0
8423   * @since 5.9.0 The `$post` parameter was made optional.
8424   *
8425   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
8426   * @return int|false Post parent ID (which can be 0 if there is no parent),
8427   *                   or false if the post does not exist.
8428   */
8429  function wp_get_post_parent_id( $post = null ) {
8430      $post = get_post( $post );
8431  
8432      if ( ! $post || is_wp_error( $post ) ) {
8433          return false;
8434      }
8435  
8436      return (int) $post->post_parent;
8437  }
8438  
8439  /**
8440   * Checks the given subset of the post hierarchy for hierarchy loops.
8441   *
8442   * Prevents loops from forming and breaks those that it finds. Attached
8443   * to the {@see 'wp_insert_post_parent'} filter.
8444   *
8445   * @since 3.1.0
8446   *
8447   * @see wp_find_hierarchy_loop()
8448   *
8449   * @param int $post_parent ID of the parent for the post we're checking.
8450   * @param int $post_id     ID of the post we're checking.
8451   * @return int The new post_parent for the post, 0 otherwise.
8452   */
8453  function wp_check_post_hierarchy_for_loops( $post_parent, $post_id ) {
8454      // Nothing fancy here - bail.
8455      if ( ! $post_parent ) {
8456          return 0;
8457      }
8458  
8459      // New post can't cause a loop.
8460      if ( ! $post_id ) {
8461          return $post_parent;
8462      }
8463  
8464      // Can't be its own parent.
8465      if ( $post_parent === $post_id ) {
8466          return 0;
8467      }
8468  
8469      // Now look for larger loops.
8470      $loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_id, $post_parent );
8471      if ( ! $loop ) {
8472          return $post_parent; // No loop.
8473      }
8474  
8475      // Setting $post_parent to the given value causes a loop.
8476      if ( isset( $loop[ $post_id ] ) ) {
8477          return 0;
8478      }
8479  
8480      // There's a loop, but it doesn't contain $post_id. Break the loop.
8481      foreach ( array_keys( $loop ) as $loop_member ) {
8482          wp_update_post(
8483              array(
8484                  'ID'          => $loop_member,
8485                  'post_parent' => 0,
8486              )
8487          );
8488      }
8489  
8490      return $post_parent;
8491  }
8492  
8493  /**
8494   * Sets the post thumbnail (featured image) for the given post.
8495   *
8496   * @since 3.1.0
8497   *
8498   * @param int|WP_Post $post         Post ID or post object where thumbnail should be attached.
8499   * @param int         $thumbnail_id Thumbnail to attach.
8500   * @return int|bool Post meta ID if the key didn't exist (ie. this is the first time that
8501   *                  a thumbnail has been saved for the post), true on successful update,
8502   *                  false on failure or if the value passed is the same as the one that
8503   *                  is already in the database.
8504   */
8505  function set_post_thumbnail( $post, $thumbnail_id ) {
8506      $post         = get_post( $post );
8507      $thumbnail_id = absint( $thumbnail_id );
8508      if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
8509          if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) {
8510              return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
8511          } else {
8512              return delete_post_meta( $post->ID, '_thumbnail_id' );
8513          }
8514      }
8515      return false;
8516  }
8517  
8518  /**
8519   * Removes the thumbnail (featured image) from the given post.
8520   *
8521   * @since 3.3.0
8522   *
8523   * @param int|WP_Post $post Post ID or post object from which the thumbnail should be removed.
8524   * @return bool True on success, false on failure.
8525   */
8526  function delete_post_thumbnail( $post ) {
8527      $post = get_post( $post );
8528      if ( $post ) {
8529          return delete_post_meta( $post->ID, '_thumbnail_id' );
8530      }
8531      return false;
8532  }
8533  
8534  /**
8535   * Deletes auto-drafts for new posts that are > 7 days old.
8536   *
8537   * @since 3.4.0
8538   *
8539   * @global wpdb $wpdb WordPress database abstraction object.
8540   */
8541  function wp_delete_auto_drafts() {
8542      global $wpdb;
8543  
8544      // Cleanup old auto-drafts more than 7 days old.
8545      $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
8546      foreach ( (array) $old_posts as $delete ) {
8547          // Force delete.
8548          wp_delete_post( $delete, true );
8549      }
8550  }
8551  
8552  /**
8553   * Queues posts for lazy-loading of term meta.
8554   *
8555   * @since 4.5.0
8556   *
8557   * @param WP_Post[] $posts Array of WP_Post objects.
8558   */
8559  function wp_queue_posts_for_term_meta_lazyload( $posts ) {
8560      $post_type_taxonomies = array();
8561      $prime_post_terms     = array();
8562      foreach ( $posts as $post ) {
8563          if ( ! ( $post instanceof WP_Post ) ) {
8564              continue;
8565          }
8566  
8567          if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
8568              $post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
8569          }
8570  
8571          foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
8572              $prime_post_terms[ $taxonomy ][] = $post->ID;
8573          }
8574      }
8575  
8576      $term_ids = array();
8577      if ( $prime_post_terms ) {
8578          foreach ( $prime_post_terms as $taxonomy => $post_ids ) {
8579              $cached_term_ids = wp_cache_get_multiple( $post_ids, "{$taxonomy}_relationships" );
8580              if ( is_array( $cached_term_ids ) ) {
8581                  $cached_term_ids = array_filter( $cached_term_ids );
8582                  foreach ( $cached_term_ids as $_term_ids ) {
8583                      // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
8584                      foreach ( $_term_ids as $term_id ) {
8585                          if ( is_numeric( $term_id ) ) {
8586                              $term_ids[] = (int) $term_id;
8587                          } elseif ( isset( $term_id->term_id ) ) {
8588                              $term_ids[] = (int) $term_id->term_id;
8589                          }
8590                      }
8591                  }
8592              }
8593          }
8594          $term_ids = array_unique( $term_ids );
8595      }
8596  
8597      wp_lazyload_term_meta( $term_ids );
8598  }
8599  
8600  /**
8601   * Updates the custom taxonomies' term counts when a post's status is changed.
8602   *
8603   * For example, default posts term counts (for custom taxonomies) don't include
8604   * private / draft posts.
8605   *
8606   * @since 3.3.0
8607   * @access private
8608   *
8609   * @param string  $new_status New post status.
8610   * @param string  $old_status Old post status.
8611   * @param WP_Post $post       Post object.
8612   */
8613  function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
8614      if ( $new_status === $old_status ) {
8615          return;
8616      }
8617  
8618      // Update counts for the post's terms.
8619      foreach ( (array) get_object_taxonomies( $post->post_type, 'objects' ) as $taxonomy ) {
8620          /** This filter is documented in wp-includes/taxonomy.php */
8621          $counted_statuses = apply_filters( 'update_post_term_count_statuses', array( 'publish' ), $taxonomy );
8622  
8623          /*
8624           * Do not recalculate term count if both the old and new status are not included in term counts.
8625           * This accounts for a transition such as draft -> pending.
8626           */
8627          if ( ! in_array( $old_status, $counted_statuses, true ) && ! in_array( $new_status, $counted_statuses, true ) ) {
8628              continue;
8629          }
8630  
8631          /*
8632           * Do not recalculate term count if both the old and new status are included in term counts.
8633           *
8634           * This accounts for transitioning between statuses which are both included in term counts. This can only occur
8635           * if the `update_post_term_count_statuses` filter is in use to count more than just the 'publish' status.
8636           */
8637          if ( in_array( $old_status, $counted_statuses, true ) && in_array( $new_status, $counted_statuses, true ) ) {
8638              continue;
8639          }
8640  
8641          $tt_ids = wp_get_object_terms( $post->ID, $taxonomy->name, array( 'fields' => 'tt_ids' ) );
8642          wp_update_term_count( $tt_ids, $taxonomy->name );
8643      }
8644  }
8645  
8646  /**
8647   * Adds any posts from the given IDs to the cache that do not already exist in cache.
8648   *
8649   * @since 3.4.0
8650   * @since 6.1.0 This function is no longer marked as "private".
8651   *
8652   * @see update_post_cache()
8653   * @see update_postmeta_cache()
8654   * @see update_object_term_cache()
8655   *
8656   * @global wpdb $wpdb WordPress database abstraction object.
8657   *
8658   * @param int[] $ids               ID list.
8659   * @param bool  $update_term_cache Optional. Whether to update the term cache. Default true.
8660   * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
8661   */
8662  function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
8663      global $wpdb;
8664  
8665      $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
8666      if ( ! empty( $non_cached_ids ) ) {
8667          $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
8668  
8669          if ( $fresh_posts ) {
8670              // Despite the name, update_post_cache() expects an array rather than a single post.
8671              update_post_cache( $fresh_posts );
8672          }
8673      }
8674  
8675      if ( $update_meta_cache ) {
8676          update_postmeta_cache( $ids );
8677      }
8678  
8679      if ( $update_term_cache ) {
8680          $post_types = array_map( 'get_post_type', $ids );
8681          $post_types = array_unique( $post_types );
8682          update_object_term_cache( $ids, $post_types );
8683      }
8684  }
8685  
8686  /**
8687   * Prime the cache containing the parent ID of various post objects.
8688   *
8689   * @since 6.4.0
8690   *
8691   * @global wpdb $wpdb WordPress database abstraction object.
8692   *
8693   * @param int[] $ids ID list.
8694   */
8695  function _prime_post_parent_id_caches( array $ids ) {
8696      global $wpdb;
8697  
8698      $ids = array_filter( $ids, '_validate_cache_id' );
8699      $ids = array_unique( array_map( 'intval', $ids ), SORT_NUMERIC );
8700  
8701      if ( empty( $ids ) ) {
8702          return;
8703      }
8704  
8705      $cache_keys = array();
8706      foreach ( $ids as $id ) {
8707          $cache_keys[ $id ] = 'post_parent:' . (string) $id;
8708      }
8709  
8710      $cached_data = wp_cache_get_multiple( array_values( $cache_keys ), 'posts' );
8711  
8712      $non_cached_ids = array();
8713      foreach ( $cache_keys as $id => $cache_key ) {
8714          if ( false === $cached_data[ $cache_key ] ) {
8715              $non_cached_ids[] = $id;
8716          }
8717      }
8718  
8719      if ( ! empty( $non_cached_ids ) ) {
8720          $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.ID, $wpdb->posts.post_parent FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
8721  
8722          if ( $fresh_posts ) {
8723              $post_parent_data = array();
8724              foreach ( $fresh_posts as $fresh_post ) {
8725                  $post_parent_data[ 'post_parent:' . (string) $fresh_post->ID ] = (int) $fresh_post->post_parent;
8726              }
8727  
8728              wp_cache_add_multiple( $post_parent_data, 'posts' );
8729          }
8730      }
8731  }
8732  
8733  /**
8734   * Adds a suffix if any trashed posts have a given slug.
8735   *
8736   * Store its desired (i.e. current) slug so it can try to reclaim it
8737   * if the post is untrashed.
8738   *
8739   * For internal use.
8740   *
8741   * @since 4.5.0
8742   * @access private
8743   *
8744   * @param string $post_name Post slug.
8745   * @param int    $post_id   Optional. Post ID that should be ignored. Default 0.
8746   */
8747  function wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_id = 0 ) {
8748      $trashed_posts_with_desired_slug = get_posts(
8749          array(
8750              'name'         => $post_name,
8751              'post_status'  => 'trash',
8752              'post_type'    => 'any',
8753              'nopaging'     => true,
8754              'post__not_in' => array( $post_id ),
8755          )
8756      );
8757  
8758      if ( ! empty( $trashed_posts_with_desired_slug ) ) {
8759          foreach ( $trashed_posts_with_desired_slug as $_post ) {
8760              wp_add_trashed_suffix_to_post_name_for_post( $_post );
8761          }
8762      }
8763  }
8764  
8765  /**
8766   * Adds a trashed suffix for a given post.
8767   *
8768   * Store its desired (i.e. current) slug so it can try to reclaim it
8769   * if the post is untrashed.
8770   *
8771   * For internal use.
8772   *
8773   * @since 4.5.0
8774   * @access private
8775   *
8776   * @global wpdb $wpdb WordPress database abstraction object.
8777   *
8778   * @param WP_Post $post The post.
8779   * @return string New slug for the post.
8780   */
8781  function wp_add_trashed_suffix_to_post_name_for_post( $post ) {
8782      global $wpdb;
8783  
8784      $post = get_post( $post );
8785  
8786      if ( str_ends_with( $post->post_name, '__trashed' ) ) {
8787          return $post->post_name;
8788      }
8789      add_post_meta( $post->ID, '_wp_desired_post_slug', $post->post_name );
8790      $post_name = wp_truncate_slug( $post->post_name, 191 ) . '__trashed';
8791      $wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), array( 'ID' => $post->ID ) );
8792      clean_post_cache( $post->ID );
8793      return $post_name;
8794  }
8795  
8796  /**
8797   * Sets the last changed time for the 'posts' cache group.
8798   *
8799   * @since 5.0.0
8800   */
8801  function wp_cache_set_posts_last_changed() {
8802      wp_cache_set_last_changed( 'posts' );
8803  }
8804  
8805  /**
8806   * Gets all available post MIME types for a given post type.
8807   *
8808   * @since 2.5.0
8809   *
8810   * @global wpdb $wpdb WordPress database abstraction object.
8811   *
8812   * @param string $type
8813   * @return string[] An array of MIME types.
8814   */
8815  function get_available_post_mime_types( $type = 'attachment' ) {
8816      global $wpdb;
8817  
8818      /**
8819       * Filters the list of available post MIME types for the given post type.
8820       *
8821       * @since 6.4.0
8822       *
8823       * @param string[]|null $mime_types An array of MIME types. Default null.
8824       * @param string        $type       The post type name. Usually 'attachment' but can be any post type.
8825       */
8826      $mime_types = apply_filters( 'pre_get_available_post_mime_types', null, $type );
8827  
8828      if ( ! is_array( $mime_types ) ) {
8829          $mime_types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s AND post_mime_type != ''", $type ) );
8830      }
8831  
8832      // Remove nulls from returned $mime_types.
8833      return array_values( array_filter( $mime_types ) );
8834  }
8835  
8836  /**
8837   * Retrieves the path to an uploaded image file.
8838   *
8839   * Similar to `get_attached_file()` however some images may have been processed after uploading
8840   * to make them suitable for web use. In this case the attached "full" size file is usually replaced
8841   * with a scaled down version of the original image. This function always returns the path
8842   * to the originally uploaded image file.
8843   *
8844   * @since 5.3.0
8845   * @since 5.4.0 Added the `$unfiltered` parameter.
8846   *
8847   * @param int  $attachment_id Attachment ID.
8848   * @param bool $unfiltered    Optional. Passed through to `get_attached_file()`. Default false.
8849   * @return string|false Path to the original image file or false if the attachment is not an image.
8850   */
8851  function wp_get_original_image_path( $attachment_id, $unfiltered = false ) {
8852      if ( ! wp_attachment_is_image( $attachment_id ) ) {
8853          return false;
8854      }
8855  
8856      $image_meta = wp_get_attachment_metadata( $attachment_id );
8857      $image_file = get_attached_file( $attachment_id, $unfiltered );
8858  
8859      if ( empty( $image_meta['original_image'] ) ) {
8860          $original_image = $image_file;
8861      } else {
8862          $original_image = path_join( dirname( $image_file ), $image_meta['original_image'] );
8863      }
8864  
8865      /**
8866       * Filters the path to the original image.
8867       *
8868       * @since 5.3.0
8869       *
8870       * @param string $original_image Path to original image file.
8871       * @param int    $attachment_id  Attachment ID.
8872       */
8873      return apply_filters( 'wp_get_original_image_path', $original_image, $attachment_id );
8874  }
8875  
8876  /**
8877   * Retrieves the URL to an original attachment image.
8878   *
8879   * Similar to `wp_get_attachment_url()` however some images may have been
8880   * processed after uploading. In this case this function returns the URL
8881   * to the originally uploaded image file.
8882   *
8883   * @since 5.3.0
8884   *
8885   * @param int $attachment_id Attachment post ID.
8886   * @return string|false Attachment image URL, false on error or if the attachment is not an image.
8887   */
8888  function wp_get_original_image_url( $attachment_id ) {
8889      if ( ! wp_attachment_is_image( $attachment_id ) ) {
8890          return false;
8891      }
8892  
8893      $image_url = wp_get_attachment_url( $attachment_id );
8894  
8895      if ( ! $image_url ) {
8896          return false;
8897      }
8898  
8899      $image_meta = wp_get_attachment_metadata( $attachment_id );
8900  
8901      if ( empty( $image_meta['original_image'] ) ) {
8902          $original_image_url = $image_url;
8903      } else {
8904          $original_image_url = path_join( dirname( $image_url ), $image_meta['original_image'] );
8905      }
8906  
8907      /**
8908       * Filters the URL to the original attachment image.
8909       *
8910       * @since 5.3.0
8911       *
8912       * @param string $original_image_url URL to original image.
8913       * @param int    $attachment_id      Attachment ID.
8914       */
8915      return apply_filters( 'wp_get_original_image_url', $original_image_url, $attachment_id );
8916  }
8917  
8918  /**
8919   * Retrieves the edit root of an attachment: the attachment its chain of edits started from.
8920   *
8921   * Editing an image through the `wp/v2/media/<id>/edit` REST endpoint does not change the
8922   * image that was edited. It saves the result as a brand new attachment, so a site can end
8923   * up with a chain of attachments: an upload, a crop of it, a crop of that crop, and so on.
8924   *
8925   * Every attachment created that way stores the ID of the attachment at the top of its chain,
8926   * so this function can find the edit root in one lookup no matter how long the chain is.
8927   *
8928   * Attachments that were uploaded rather than created by editing have no chain of their own,
8929   * and this returns 0 for them.
8930   *
8931   * @since 7.2.0
8932   *
8933   * @param int $attachment_id Attachment ID.
8934   * @return int ID of the attachment the chain of edits started from, or 0 when none is recorded.
8935   */
8936  function wp_get_edit_root_attachment_id( $attachment_id ) {
8937      $edit_root_id = (int) get_post_meta( $attachment_id, '_wp_attachment_edit_root_id', true );
8938  
8939      // An attachment recorded as its own edit root is a broken record rather than a chain.
8940      if ( $edit_root_id <= 0 || $edit_root_id === (int) $attachment_id ) {
8941          return 0;
8942      }
8943  
8944      return $edit_root_id;
8945  }
8946  
8947  /**
8948   * Clears the recorded edit root ID from any attachment pointing at a deleted one.
8949   *
8950   * Without this, attachments created by editing the deleted image would keep pointing at an
8951   * ID that no longer exists, and could later point at an unrelated attachment if WordPress
8952   * reuses that ID.
8953   *
8954   * This only runs when an attachment is deleted for good. On sites where media goes to the
8955   * trash first, attachments keep pointing at the trashed edit root until the trash is emptied.
8956   *
8957   * @since 7.2.0
8958   *
8959   * @access private
8960   *
8961   * @param int $post_id Attachment ID being deleted.
8962   */
8963  function _wp_delete_edit_root_attachment_id( $post_id ) {
8964      $post_id = (int) $post_id;
8965  
8966      if ( $post_id <= 0 ) {
8967          return;
8968      }
8969  
8970      /*
8971       * Deletes the meta from every attachment recording this ID as its edit root. The meta key
8972       * is indexed, so this only scans the rows for attachments created by editing an image,
8973       * and it avoids searching the serialized attachment metadata for the ID.
8974       */
8975      delete_metadata( 'post', 0, '_wp_attachment_edit_root_id', $post_id, true );
8976  }
8977  
8978  /**
8979   * Filters callback which sets the status of an untrashed post to its previous status.
8980   *
8981   * This can be used as a callback on the `wp_untrash_post_status` filter.
8982   *
8983   * @since 5.6.0
8984   *
8985   * @param string $new_status      The new status of the post being restored.
8986   * @param int    $post_id         The ID of the post being restored.
8987   * @param string $previous_status The status of the post at the point where it was trashed.
8988   * @return string The new status of the post.
8989   */
8990  function wp_untrash_post_set_previous_status( $new_status, $post_id, $previous_status ) {
8991      return $previous_status;
8992  }
8993  
8994  /**
8995   * Returns whether the post can be edited in the block editor.
8996   *
8997   * @since 5.0.0
8998   * @since 6.1.0 Moved to wp-includes from wp-admin.
8999   *
9000   * @param int|WP_Post $post Post ID or WP_Post object.
9001   * @return bool Whether the post can be edited in the block editor.
9002   */
9003  function use_block_editor_for_post( $post ) {
9004      $post = get_post( $post );
9005  
9006      if ( ! $post ) {
9007          return false;
9008      }
9009  
9010      // We're in the meta box loader, so don't use the block editor.
9011      if ( is_admin() && isset( $_GET['meta-box-loader'] ) ) {
9012          check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
9013          return false;
9014      }
9015  
9016      $use_block_editor = use_block_editor_for_post_type( $post->post_type );
9017  
9018      /**
9019       * Filters whether a post is able to be edited in the block editor.
9020       *
9021       * @since 5.0.0
9022       *
9023       * @param bool    $use_block_editor Whether the post can be edited or not.
9024       * @param WP_Post $post             The post being checked.
9025       */
9026      return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
9027  }
9028  
9029  /**
9030   * Returns whether a post type is compatible with the block editor.
9031   *
9032   * The block editor depends on the REST API, and if the post type is not shown in the
9033   * REST API, then it won't work with the block editor.
9034   *
9035   * @since 5.0.0
9036   * @since 6.1.0 Moved to wp-includes from wp-admin.
9037   *
9038   * @param string $post_type The post type.
9039   * @return bool Whether the post type can be edited with the block editor.
9040   */
9041  function use_block_editor_for_post_type( $post_type ) {
9042      if ( ! post_type_exists( $post_type ) ) {
9043          return false;
9044      }
9045  
9046      if ( ! post_type_supports( $post_type, 'editor' ) ) {
9047          return false;
9048      }
9049  
9050      $post_type_object = get_post_type_object( $post_type );
9051      if ( $post_type_object && ! $post_type_object->show_in_rest ) {
9052          return false;
9053      }
9054  
9055      /**
9056       * Filters whether a post is able to be edited in the block editor.
9057       *
9058       * @since 5.0.0
9059       *
9060       * @param bool   $use_block_editor  Whether the post type can be edited or not. Default true.
9061       * @param string $post_type         The post type being checked.
9062       */
9063      return apply_filters( 'use_block_editor_for_post_type', true, $post_type );
9064  }
9065  
9066  /**
9067   * Registers any additional post meta fields.
9068   *
9069   * @since 6.3.0 Adds `wp_pattern_sync_status` meta field to the wp_block post type so an unsynced option can be added.
9070   *
9071   * @link https://github.com/WordPress/gutenberg/pull/51144
9072   */
9073  function wp_create_initial_post_meta() {
9074      register_post_meta(
9075          'wp_block',
9076          'wp_pattern_sync_status',
9077          array(
9078              'sanitize_callback' => 'sanitize_text_field',
9079              'single'            => true,
9080              'type'              => 'string',
9081              'show_in_rest'      => array(
9082                  'schema' => array(
9083                      'type' => 'string',
9084                      'enum' => array( 'partial', 'unsynced' ),
9085                  ),
9086              ),
9087          )
9088      );
9089  }


Generated : Wed Oct 14 08:20:33 2026 Cross-referenced by PHPXref