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


Generated : Thu Nov 12 08:20:02 2026 Cross-referenced by PHPXref