[ 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|decimal-int-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   *         ? decimal-int-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   *         ? decimal-int-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   *         ? decimal-int-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|int $args {
4712   *     Optional. Arguments to retrieve posts. See {@see get_posts()} and
4713   *     {@see WP_Query::parse_query()} for all available arguments. Those listed here
4714   *     have defaults that differ. Passing an integer number of posts is deprecated
4715   *     since 3.1.0. Default empty array.
4716   *
4717   *     @type int             $numberposts Total number of posts to retrieve. Accepts -1 for all.
4718   *                                        Default 10.
4719   *     @type int             $offset      The number of posts to offset before retrieval. Default 0.
4720   *     @type string|array    $orderby     Sort retrieved posts by parameter. Default 'post_date'.
4721   *     @type string|string[] $post_status A post status (string) or array of post statuses.
4722   *                                        Default 'draft, publish, future, pending, private'.
4723   * }
4724   * @param string    $output Optional. The required return type. One of OBJECT or ARRAY_A, which
4725   *                          correspond to a WP_Post object or an associative array, respectively.
4726   *                          Default ARRAY_A.
4727   * @return array|false Array of recent posts, where the type of each element is determined
4728   *                     by the `$output` parameter. Empty array on failure.
4729   *
4730   * @phpstan-param positive-int|array{
4731   *     numberposts?: int,
4732   *     offset?: int,
4733   *     orderby?: string|array<mixed>,
4734   *     post_status?: string|string[],
4735   *     category?: int|string,
4736   *     include?: int[],
4737   *     exclude?: int[],
4738   *     suppress_filters?: bool,
4739   *     fields?: ''|'all',
4740   *     ...
4741   * } $args
4742   * @phpstan-param 'OBJECT'|'ARRAY_A' $output
4743   * @phpstan-return (
4744   *     $output is 'ARRAY_A' ? array<int, non-empty-array<string, mixed>> : WP_Post[]|false
4745   * )
4746   */
4747  function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
4748  
4749      if ( is_numeric( $args ) ) {
4750          _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
4751          $args = array( 'numberposts' => absint( $args ) );
4752      }
4753  
4754      // Set default arguments.
4755      $defaults = array(
4756          'numberposts'      => 10,
4757          'offset'           => 0,
4758          'category'         => 0,
4759          'orderby'          => 'post_date',
4760          'order'            => 'DESC',
4761          'include'          => array(),
4762          'exclude'          => array(),
4763          'meta_key'         => '',
4764          'meta_value'       => '',
4765          'post_type'        => 'post',
4766          'post_status'      => 'draft, publish, future, pending, private',
4767          'suppress_filters' => true,
4768      );
4769  
4770      /** @var array{ numberposts: int, category: int|string, include: int[], exclude: int[], suppress_filters: bool, fields?: ''|'all', ... } $parsed_args */
4771      $parsed_args = wp_parse_args( $args, $defaults );
4772  
4773      $results = get_posts( $parsed_args );
4774  
4775      // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
4776      if ( ARRAY_A === $output ) {
4777          $posts = array();
4778          foreach ( $results as $key => $result ) {
4779              /** @var non-empty-array<string, mixed> $object_vars */
4780              $object_vars   = get_object_vars( $result );
4781              $posts[ $key ] = $object_vars;
4782          }
4783          return $posts;
4784      }
4785  
4786      return $results ? $results : false;
4787  }
4788  
4789  /**
4790   * Inserts or updates a post in the database.
4791   *
4792   * If the `$postarr` parameter contains an 'ID', the corresponding post will be updated.
4793   * If not, a new post will be created using the values provided.
4794   *
4795   * You can set the post date manually, by setting the values for 'post_date'
4796   * and 'post_date_gmt' keys. You can close the comments or open the comments by
4797   * setting the value for 'comment_status' key.
4798   *
4799   * @since 1.0.0
4800   * @since 2.6.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
4801   * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
4802   * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
4803   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
4804   *
4805   * @see sanitize_post()
4806   * @global wpdb $wpdb WordPress database abstraction object.
4807   *
4808   * @param array $postarr {
4809   *     An array of elements that make up a post to update or insert.
4810   *
4811   *     @type int    $ID                    The post ID. If equal to something other than 0,
4812   *                                         the post with that ID will be updated. Default 0.
4813   *     @type int    $post_author           The ID of the user who added the post. Default is
4814   *                                         the current user ID.
4815   *     @type string $post_date             The date of the post. Default is the current time.
4816   *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
4817   *                                         the value of `$post_date`.
4818   *     @type string $post_content          The post content. Default empty.
4819   *     @type string $post_content_filtered The filtered post content. Default empty.
4820   *     @type string $post_title            The post title. Default empty.
4821   *     @type string $post_excerpt          The post excerpt. Default empty.
4822   *     @type string $post_status           The post status. Default 'draft'.
4823   *     @type string $post_type             The post type. Default 'post'.
4824   *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
4825   *                                         Default is the value of 'default_comment_status' option.
4826   *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
4827   *                                         Default is the value of 'default_ping_status' option.
4828   *     @type string $post_password         The password to access the post. Default empty.
4829   *     @type string $post_name             The post name. Default is the sanitized post title
4830   *                                         when creating a new post.
4831   *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
4832   *                                         Default empty.
4833   *     @type string $pinged                Space or carriage return-separated list of URLs that have
4834   *                                         been pinged. Default empty.
4835   *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
4836   *     @type int    $menu_order            The order the post should be displayed in. Default 0.
4837   *     @type string $post_mime_type        The mime type of the post. Default empty.
4838   *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
4839   *     @type int    $import_id             The post ID to be used when inserting a new post.
4840   *                                         If specified, must not match any existing post ID. Default 0.
4841   *     @type int[]  $post_category         Array of category IDs.
4842   *                                         Defaults to value of the 'default_category' option.
4843   *     @type array  $tags_input            Array of tag names, slugs, or IDs. Default empty.
4844   *     @type array  $tax_input             An array of taxonomy terms keyed by their taxonomy name.
4845   *                                         If the taxonomy is hierarchical, the term list needs to be
4846   *                                         either an array of term IDs or a comma-separated string of IDs.
4847   *                                         If the taxonomy is non-hierarchical, the term list can be an array
4848   *                                         that contains term names or slugs, or a comma-separated string
4849   *                                         of names or slugs. This is because, in hierarchical taxonomy,
4850   *                                         child terms can have the same names with different parent terms,
4851   *                                         so the only way to connect them is using ID. Default empty.
4852   *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
4853   *     @type string $page_template         Page template to use.
4854   * }
4855   * @param bool  $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
4856   * @param bool  $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
4857   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
4858   *
4859   * @phpstan-return (
4860   *     $wp_error is false ? int : int|WP_Error
4861   * )
4862   */
4863  function wp_insert_post( $postarr, $wp_error = false, $fire_after_hooks = true ) {
4864      global $wpdb;
4865  
4866      // Capture original pre-sanitized array for passing into filters.
4867      $unsanitized_postarr = $postarr;
4868  
4869      $user_id = get_current_user_id();
4870  
4871      $defaults = array(
4872          'post_author'           => $user_id,
4873          'post_content'          => '',
4874          'post_content_filtered' => '',
4875          'post_title'            => '',
4876          'post_excerpt'          => '',
4877          'post_status'           => 'draft',
4878          'post_type'             => 'post',
4879          'comment_status'        => '',
4880          'ping_status'           => '',
4881          'post_password'         => '',
4882          'to_ping'               => '',
4883          'pinged'                => '',
4884          'post_parent'           => 0,
4885          'menu_order'            => 0,
4886          'guid'                  => '',
4887          'import_id'             => 0,
4888          'context'               => '',
4889          'post_date'             => '',
4890          'post_date_gmt'         => '',
4891      );
4892  
4893      $postarr = wp_parse_args( $postarr, $defaults );
4894  
4895      unset( $postarr['filter'] );
4896  
4897      $postarr = sanitize_post( $postarr, 'db' );
4898  
4899      // Are we updating or creating?
4900      $post_id = 0;
4901      $update  = false;
4902      $guid    = $postarr['guid'];
4903  
4904      if ( ! empty( $postarr['ID'] ) ) {
4905          $update = true;
4906  
4907          // Get the post ID and GUID.
4908          $post_id     = $postarr['ID'];
4909          $post_before = get_post( $post_id );
4910  
4911          if ( is_null( $post_before ) ) {
4912              if ( $wp_error ) {
4913                  return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
4914              }
4915              return 0;
4916          }
4917  
4918          $guid            = get_post_field( 'guid', $post_id );
4919          $previous_status = get_post_field( 'post_status', $post_id );
4920      } else {
4921          $previous_status = 'new';
4922          $post_before     = null;
4923      }
4924  
4925      $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
4926  
4927      $post_title   = $postarr['post_title'];
4928      $post_content = $postarr['post_content'];
4929      $post_excerpt = $postarr['post_excerpt'];
4930  
4931      if ( isset( $postarr['post_name'] ) ) {
4932          $post_name = $postarr['post_name'];
4933      } elseif ( $update ) {
4934          // For an update, don't modify the post_name if it wasn't supplied as an argument.
4935          $post_name = $post_before->post_name;
4936      }
4937  
4938      $maybe_empty = 'attachment' !== $post_type
4939          && ! $post_content && ! $post_title && ! $post_excerpt
4940          && post_type_supports( $post_type, 'editor' )
4941          && post_type_supports( $post_type, 'title' )
4942          && post_type_supports( $post_type, 'excerpt' );
4943  
4944      /**
4945       * Filters whether the post should be considered "empty".
4946       *
4947       * The post is considered "empty" if both:
4948       * 1. The post type supports the title, editor, and excerpt fields
4949       * 2. The title, editor, and excerpt fields are all empty
4950       *
4951       * Returning a truthy value from the filter will effectively short-circuit
4952       * the new post being inserted and return 0. If $wp_error is true, a WP_Error
4953       * will be returned instead.
4954       *
4955       * @since 3.3.0
4956       *
4957       * @param bool  $maybe_empty Whether the post should be considered "empty".
4958       * @param array $postarr     Array of post data.
4959       */
4960      if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
4961          if ( $wp_error ) {
4962              return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
4963          } else {
4964              return 0;
4965          }
4966      }
4967  
4968      $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
4969  
4970      if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash', 'auto-draft' ), true ) ) {
4971          $post_status = 'inherit';
4972      }
4973  
4974      if ( ! empty( $postarr['post_category'] ) ) {
4975          // Filter out empty terms.
4976          $post_category = array_filter( $postarr['post_category'] );
4977      } elseif ( $update && ! isset( $postarr['post_category'] ) ) {
4978          $post_category = $post_before->post_category;
4979      }
4980  
4981      // Make sure we set a valid category.
4982      if ( empty( $post_category ) || 0 === count( $post_category ) || ! is_array( $post_category ) ) {
4983          // 'post' requires at least one category.
4984          if ( 'post' === $post_type && 'auto-draft' !== $post_status ) {
4985              $post_category = array( get_option( 'default_category' ) );
4986          } else {
4987              $post_category = array();
4988          }
4989      }
4990  
4991      /*
4992       * Don't allow contributors to set the post slug for pending review posts.
4993       *
4994       * For new posts check the primitive capability, for updates check the meta capability.
4995       */
4996      if ( 'pending' === $post_status ) {
4997          $post_type_object = get_post_type_object( $post_type );
4998  
4999          if ( ! $update && $post_type_object && ! current_user_can( $post_type_object->cap->publish_posts ) ) {
5000              $post_name = '';
5001          } elseif ( $update && ! current_user_can( 'publish_post', $post_id ) ) {
5002              $post_name = '';
5003          }
5004      }
5005  
5006      /*
5007       * Create a valid post name. Drafts and pending posts are allowed to have
5008       * an empty post name.
5009       */
5010      if ( empty( $post_name ) ) {
5011          if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true ) ) {
5012              $post_name = sanitize_title( $post_title );
5013          } else {
5014              $post_name = '';
5015          }
5016      } else {
5017          // On updates, we need to check to see if it's using the old, fixed sanitization context.
5018          $check_name = sanitize_title( $post_name, '', 'old-save' );
5019  
5020          if ( $update
5021              && strtolower( urlencode( $post_name ) ) === $check_name
5022              && get_post_field( 'post_name', $post_id ) === $check_name
5023          ) {
5024              $post_name = $check_name;
5025          } else { // New post, or slug has changed.
5026              $post_name = sanitize_title( $post_name );
5027          }
5028      }
5029  
5030      /*
5031       * Resolve the post date from any provided post date or post date GMT strings;
5032       * if none are provided, the date will be set to now.
5033       */
5034      $post_date = wp_resolve_post_date( $postarr['post_date'], $postarr['post_date_gmt'] );
5035  
5036      if ( ! $post_date ) {
5037          if ( $wp_error ) {
5038              return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
5039          } else {
5040              return 0;
5041          }
5042      }
5043  
5044      if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' === $postarr['post_date_gmt'] ) {
5045          if ( ! in_array( $post_status, get_post_stati( array( 'date_floating' => true ) ), true ) ) {
5046              $post_date_gmt = get_gmt_from_date( $post_date );
5047          } else {
5048              $post_date_gmt = '0000-00-00 00:00:00';
5049          }
5050      } else {
5051          $post_date_gmt = $postarr['post_date_gmt'];
5052      }
5053  
5054      if ( $update || '0000-00-00 00:00:00' === $post_date ) {
5055          $post_modified     = current_time( 'mysql' );
5056          $post_modified_gmt = current_time( 'mysql', true );
5057      } else {
5058          $post_modified     = $post_date;
5059          $post_modified_gmt = $post_date_gmt;
5060      }
5061  
5062      if ( 'attachment' !== $post_type ) {
5063          $now = gmdate( 'Y-m-d H:i:s' );
5064  
5065          if ( 'publish' === $post_status ) {
5066              if ( strtotime( $post_date_gmt ) - strtotime( $now ) >= MINUTE_IN_SECONDS ) {
5067                  $post_status = 'future';
5068              }
5069          } elseif ( 'future' === $post_status ) {
5070              if ( strtotime( $post_date_gmt ) - strtotime( $now ) < MINUTE_IN_SECONDS ) {
5071                  $post_status = 'publish';
5072              }
5073          }
5074      }
5075  
5076      // Comment status.
5077      if ( empty( $postarr['comment_status'] ) ) {
5078          if ( $update ) {
5079              $comment_status = 'closed';
5080          } else {
5081              $comment_status = get_default_comment_status( $post_type );
5082          }
5083      } else {
5084          $comment_status = $postarr['comment_status'];
5085      }
5086  
5087      // These variables are needed by compact() later.
5088      $post_content_filtered = $postarr['post_content_filtered'];
5089      $post_author           = $postarr['post_author'] ?? $user_id;
5090      $ping_status           = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
5091      $to_ping               = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
5092      $pinged                = $postarr['pinged'] ?? '';
5093      $import_id             = $postarr['import_id'] ?? 0;
5094  
5095      /*
5096       * The 'wp_insert_post_parent' filter expects all variables to be present.
5097       * Previously, these variables would have already been extracted
5098       */
5099      if ( isset( $postarr['menu_order'] ) ) {
5100          $menu_order = (int) $postarr['menu_order'];
5101      } else {
5102          $menu_order = 0;
5103      }
5104  
5105      $post_password = $postarr['post_password'] ?? '';
5106      if ( 'private' === $post_status ) {
5107          $post_password = '';
5108      }
5109  
5110      if ( isset( $postarr['post_parent'] ) ) {
5111          $post_parent = (int) $postarr['post_parent'];
5112      } else {
5113          $post_parent = 0;
5114      }
5115  
5116      $new_postarr = array_merge(
5117          array(
5118              'ID' => $post_id,
5119          ),
5120          compact( array_diff( array_keys( $defaults ), array( 'context', 'filter' ) ) )
5121      );
5122  
5123      /**
5124       * Filters the post parent -- used to check for and prevent hierarchy loops.
5125       *
5126       * @since 3.1.0
5127       *
5128       * @param int   $post_parent Post parent ID.
5129       * @param int   $post_id     Post ID.
5130       * @param array $new_postarr Array of parsed post data.
5131       * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
5132       */
5133      $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_id, $new_postarr, $postarr );
5134  
5135      /*
5136       * If the post is being untrashed and it has a desired slug stored in post meta,
5137       * reassign it.
5138       */
5139      if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
5140          $desired_post_slug = get_post_meta( $post_id, '_wp_desired_post_slug', true );
5141  
5142          if ( $desired_post_slug ) {
5143              delete_post_meta( $post_id, '_wp_desired_post_slug' );
5144              $post_name = $desired_post_slug;
5145          }
5146      }
5147  
5148      // If a trashed post has the desired slug, change it and let this post have it.
5149      if ( 'trash' !== $post_status && $post_name ) {
5150          /**
5151           * Filters whether or not to add a `__trashed` suffix to the name of trashed posts that match the name of the updated post.
5152           *
5153           * @since 5.4.0
5154           *
5155           * @param bool   $add_trashed_suffix Whether to attempt to add the suffix.
5156           * @param string $post_name          The name of the post being updated.
5157           * @param int    $post_id            Post ID.
5158           */
5159          $add_trashed_suffix = apply_filters( 'add_trashed_suffix_to_trashed_posts', true, $post_name, $post_id );
5160  
5161          if ( $add_trashed_suffix ) {
5162              wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_id );
5163          }
5164      }
5165  
5166      // When trashing an existing post, change its slug to allow non-trashed posts to use it.
5167      if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
5168          $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_id );
5169      }
5170  
5171      $post_name = wp_unique_post_slug( $post_name, $post_id, $post_status, $post_type, $post_parent );
5172  
5173      // Don't unslash.
5174      $post_mime_type = $postarr['post_mime_type'] ?? '';
5175  
5176      // Expected_slashed (everything!).
5177      $data = compact(
5178          'post_author',
5179          'post_date',
5180          'post_date_gmt',
5181          'post_content',
5182          'post_content_filtered',
5183          'post_title',
5184          'post_excerpt',
5185          'post_status',
5186          'post_type',
5187          'comment_status',
5188          'ping_status',
5189          'post_password',
5190          'post_name',
5191          'to_ping',
5192          'pinged',
5193          'post_modified',
5194          'post_modified_gmt',
5195          'post_parent',
5196          'menu_order',
5197          'post_mime_type',
5198          'guid'
5199      );
5200  
5201      $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
5202  
5203      foreach ( $emoji_fields as $emoji_field ) {
5204          if ( isset( $data[ $emoji_field ] ) ) {
5205              $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
5206  
5207              // The 'utf8' character set is a deprecated alias of 'utf8mb3'. See <https://dev.mysql.com/doc/refman/8.4/en/charset-unicode-utf8.html>.
5208              if ( 'utf8' === $charset || 'utf8mb3' === $charset ) {
5209                  $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
5210              }
5211          }
5212      }
5213  
5214      if ( 'attachment' === $post_type ) {
5215          /**
5216           * Filters attachment post data before it is updated in or added to the database.
5217           *
5218           * @since 3.9.0
5219           * @since 5.4.1 The `$unsanitized_postarr` parameter was added.
5220           * @since 6.0.0 The `$update` parameter was added.
5221           *
5222           * @param array $data                An array of slashed, sanitized, and processed attachment post data.
5223           * @param array $postarr             An array of slashed and sanitized attachment post data, but not processed.
5224           * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed attachment post data
5225           *                                   as originally passed to wp_insert_post().
5226           * @param bool  $update              Whether this is an existing attachment post being updated.
5227           */
5228          $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr, $unsanitized_postarr, $update );
5229      } else {
5230          /**
5231           * Filters slashed post data just before it is inserted into the database.
5232           *
5233           * @since 2.7.0
5234           * @since 5.4.1 The `$unsanitized_postarr` parameter was added.
5235           * @since 6.0.0 The `$update` parameter was added.
5236           *
5237           * @param array $data                An array of slashed, sanitized, and processed post data.
5238           * @param array $postarr             An array of sanitized (and slashed) but otherwise unmodified post data.
5239           * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as
5240           *                                   originally passed to wp_insert_post().
5241           * @param bool  $update              Whether this is an existing post being updated.
5242           */
5243          $data = apply_filters( 'wp_insert_post_data', $data, $postarr, $unsanitized_postarr, $update );
5244      }
5245  
5246      $data  = wp_unslash( $data );
5247      $where = array( 'ID' => $post_id );
5248  
5249      if ( $update ) {
5250          /**
5251           * Fires immediately before an existing post is updated in the database.
5252           *
5253           * @since 2.5.0
5254           *
5255           * @param int   $post_id Post ID.
5256           * @param array $data    Array of unslashed post data.
5257           */
5258          do_action( 'pre_post_update', $post_id, $data );
5259  
5260          if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
5261              if ( $wp_error ) {
5262                  if ( 'attachment' === $post_type ) {
5263                      $message = __( 'Could not update attachment in the database.' );
5264                  } else {
5265                      $message = __( 'Could not update post in the database.' );
5266                  }
5267  
5268                  return new WP_Error( 'db_update_error', $message, $wpdb->last_error );
5269              } else {
5270                  return 0;
5271              }
5272          }
5273      } else {
5274          // If there is a suggested ID, use it if not already present.
5275          if ( ! empty( $import_id ) ) {
5276              $import_id = (int) $import_id;
5277  
5278              if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id ) ) ) {
5279                  $data['ID'] = $import_id;
5280              }
5281          }
5282  
5283          /**
5284           * Fires immediately before a new post is inserted in the database.
5285           *
5286           * @since 6.9.0
5287           *
5288           * @param array $data Array of unslashed post data.
5289           */
5290          do_action( 'pre_post_insert', $data );
5291  
5292          if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
5293              if ( $wp_error ) {
5294                  if ( 'attachment' === $post_type ) {
5295                      $message = __( 'Could not insert attachment into the database.' );
5296                  } else {
5297                      $message = __( 'Could not insert post into the database.' );
5298                  }
5299  
5300                  return new WP_Error( 'db_insert_error', $message, $wpdb->last_error );
5301              } else {
5302                  return 0;
5303              }
5304          }
5305  
5306          $post_id = (int) $wpdb->insert_id;
5307  
5308          // Use the newly generated $post_id.
5309          $where = array( 'ID' => $post_id );
5310      }
5311  
5312      if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ), true ) ) {
5313          $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_id ), $post_id, $data['post_status'], $post_type, $post_parent );
5314  
5315          $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
5316          clean_post_cache( $post_id );
5317      }
5318  
5319      if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
5320          wp_set_post_categories( $post_id, $post_category );
5321      }
5322  
5323      if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
5324          wp_set_post_tags( $post_id, $postarr['tags_input'] );
5325      }
5326  
5327      // Add default term for all associated custom taxonomies.
5328      if ( 'auto-draft' !== $post_status ) {
5329          foreach ( get_object_taxonomies( $post_type, 'object' ) as $taxonomy => $tax_object ) {
5330  
5331              if ( ! empty( $tax_object->default_term ) ) {
5332  
5333                  // Filter out empty terms.
5334                  if ( isset( $postarr['tax_input'][ $taxonomy ] ) && is_array( $postarr['tax_input'][ $taxonomy ] ) ) {
5335                      $postarr['tax_input'][ $taxonomy ] = array_filter( $postarr['tax_input'][ $taxonomy ] );
5336                  }
5337  
5338                  // Passed custom taxonomy list overwrites the existing list if not empty.
5339                  $terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
5340                  if ( ! empty( $terms ) && empty( $postarr['tax_input'][ $taxonomy ] ) ) {
5341                      $postarr['tax_input'][ $taxonomy ] = $terms;
5342                  }
5343  
5344                  if ( empty( $postarr['tax_input'][ $taxonomy ] ) ) {
5345                      $default_term_id = get_option( 'default_term_' . $taxonomy );
5346                      if ( ! empty( $default_term_id ) ) {
5347                          $postarr['tax_input'][ $taxonomy ] = array( (int) $default_term_id );
5348                      }
5349                  }
5350              }
5351          }
5352      }
5353  
5354      // New-style support for all custom taxonomies.
5355      if ( ! empty( $postarr['tax_input'] ) ) {
5356          foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
5357              $taxonomy_obj = get_taxonomy( $taxonomy );
5358  
5359              if ( ! $taxonomy_obj ) {
5360                  /* translators: %s: Taxonomy name. */
5361                  _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
5362                  continue;
5363              }
5364  
5365              // array = hierarchical, string = non-hierarchical.
5366              if ( is_array( $tags ) ) {
5367                  $tags = array_filter( $tags );
5368              }
5369  
5370              if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
5371                  wp_set_post_terms( $post_id, $tags, $taxonomy );
5372              }
5373          }
5374      }
5375  
5376      if ( ! empty( $postarr['meta_input'] ) ) {
5377          foreach ( $postarr['meta_input'] as $field => $value ) {
5378              update_post_meta( $post_id, $field, $value );
5379          }
5380      }
5381  
5382      $current_guid = get_post_field( 'guid', $post_id );
5383  
5384      // Set GUID.
5385      if ( ! $update && '' === $current_guid ) {
5386          $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_id ) ), $where );
5387      }
5388  
5389      if ( 'attachment' === $postarr['post_type'] ) {
5390          if ( ! empty( $postarr['file'] ) ) {
5391              update_attached_file( $post_id, $postarr['file'] );
5392          }
5393  
5394          if ( ! empty( $postarr['context'] ) ) {
5395              add_post_meta( $post_id, '_wp_attachment_context', $postarr['context'], true );
5396          }
5397      }
5398  
5399      // Set or remove featured image.
5400      if ( isset( $postarr['_thumbnail_id'] ) ) {
5401          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
5402  
5403          if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
5404              if ( wp_attachment_is( 'audio', $post_id ) ) {
5405                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
5406              } elseif ( wp_attachment_is( 'video', $post_id ) ) {
5407                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
5408              }
5409          }
5410  
5411          if ( $thumbnail_support ) {
5412              $thumbnail_id = (int) $postarr['_thumbnail_id'];
5413              if ( -1 === $thumbnail_id ) {
5414                  delete_post_thumbnail( $post_id );
5415              } else {
5416                  set_post_thumbnail( $post_id, $thumbnail_id );
5417              }
5418          }
5419      }
5420  
5421      clean_post_cache( $post_id );
5422  
5423      $post = get_post( $post_id );
5424  
5425      if ( ! empty( $postarr['page_template'] ) ) {
5426          $post->page_template = $postarr['page_template'];
5427          $page_templates      = wp_get_theme()->get_page_templates( $post );
5428  
5429          if ( 'default' !== $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
5430              if ( $wp_error ) {
5431                  return new WP_Error( 'invalid_page_template', __( 'Invalid page template.' ) );
5432              }
5433  
5434              update_post_meta( $post_id, '_wp_page_template', 'default' );
5435          } else {
5436              update_post_meta( $post_id, '_wp_page_template', $postarr['page_template'] );
5437          }
5438      }
5439  
5440      if ( 'attachment' !== $postarr['post_type'] ) {
5441          wp_transition_post_status( $data['post_status'], $previous_status, $post );
5442      } else {
5443          if ( $update ) {
5444              /**
5445               * Fires once an existing attachment has been updated.
5446               *
5447               * @since 2.0.0
5448               *
5449               * @param int $post_id Attachment ID.
5450               */
5451              do_action( 'edit_attachment', $post_id );
5452  
5453              $post_after = get_post( $post_id );
5454  
5455              /**
5456               * Fires once an existing attachment has been updated.
5457               *
5458               * @since 4.4.0
5459               *
5460               * @param int     $post_id      Post ID.
5461               * @param WP_Post $post_after   Post object following the update.
5462               * @param WP_Post $post_before  Post object before the update.
5463               */
5464              do_action( 'attachment_updated', $post_id, $post_after, $post_before );
5465          } else {
5466  
5467              /**
5468               * Fires once an attachment has been added.
5469               *
5470               * @since 2.0.0
5471               *
5472               * @param int $post_id Attachment ID.
5473               */
5474              do_action( 'add_attachment', $post_id );
5475          }
5476  
5477          return $post_id;
5478      }
5479  
5480      if ( $update ) {
5481          /**
5482           * Fires once an existing post has been updated.
5483           *
5484           * The dynamic portion of the hook name, `$post->post_type`, refers to
5485           * the post type slug.
5486           *
5487           * Possible hook names include:
5488           *
5489           *  - `edit_post_post`
5490           *  - `edit_post_page`
5491           *
5492           * @since 5.1.0
5493           *
5494           * @param int     $post_id Post ID.
5495           * @param WP_Post $post    Post object.
5496           */
5497          do_action( "edit_post_{$post->post_type}", $post_id, $post );
5498  
5499          /**
5500           * Fires once an existing post has been updated.
5501           *
5502           * @since 1.2.0
5503           *
5504           * @param int     $post_id Post ID.
5505           * @param WP_Post $post    Post object.
5506           */
5507          do_action( 'edit_post', $post_id, $post );
5508  
5509          $post_after = get_post( $post_id );
5510  
5511          /**
5512           * Fires once an existing post has been updated.
5513           *
5514           * @since 3.0.0
5515           *
5516           * @param int     $post_id      Post ID.
5517           * @param WP_Post $post_after   Post object following the update.
5518           * @param WP_Post $post_before  Post object before the update.
5519           */
5520          do_action( 'post_updated', $post_id, $post_after, $post_before );
5521      }
5522  
5523      /**
5524       * Fires once a post has been saved.
5525       *
5526       * The dynamic portion of the hook name, `$post->post_type`, refers to
5527       * the post type slug.
5528       *
5529       * Possible hook names include:
5530       *
5531       *  - `save_post_post`
5532       *  - `save_post_page`
5533       *
5534       * @since 3.7.0
5535       *
5536       * @param int     $post_id Post ID.
5537       * @param WP_Post $post    Post object.
5538       * @param bool    $update  Whether this is an existing post being updated.
5539       */
5540      do_action( "save_post_{$post->post_type}", $post_id, $post, $update );
5541  
5542      /**
5543       * Fires once a post has been saved.
5544       *
5545       * @since 1.5.0
5546       *
5547       * @param int     $post_id Post ID.
5548       * @param WP_Post $post    Post object.
5549       * @param bool    $update  Whether this is an existing post being updated.
5550       */
5551      do_action( 'save_post', $post_id, $post, $update );
5552  
5553      /**
5554       * Fires once a post has been saved.
5555       *
5556       * @since 2.0.0
5557       *
5558       * @param int     $post_id Post ID.
5559       * @param WP_Post $post    Post object.
5560       * @param bool    $update  Whether this is an existing post being updated.
5561       */
5562      do_action( 'wp_insert_post', $post_id, $post, $update );
5563  
5564      if ( $fire_after_hooks ) {
5565          wp_after_insert_post( $post, $update, $post_before );
5566      }
5567  
5568      return $post_id;
5569  }
5570  
5571  /**
5572   * Updates a post with new post data.
5573   *
5574   * The date does not have to be set for drafts. You can set the date and it will
5575   * not be overridden.
5576   *
5577   * @since 1.0.0
5578   * @since 3.5.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
5579   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
5580   *
5581   * @param array|object $postarr          Optional. Post data. Arrays are expected to be escaped,
5582   *                                       objects are not. See wp_insert_post() for accepted arguments.
5583   *                                       Default array.
5584   * @param bool         $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
5585   * @param bool         $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
5586   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
5587   *
5588   * @phpstan-return (
5589   *     $wp_error is false ? int : int|WP_Error
5590   * )
5591   */
5592  function wp_update_post( $postarr = array(), $wp_error = false, $fire_after_hooks = true ) {
5593      if ( is_object( $postarr ) ) {
5594          // Non-escaped post was passed.
5595          $postarr = get_object_vars( $postarr );
5596          $postarr = wp_slash( $postarr );
5597      }
5598  
5599      // First, get all of the original fields.
5600      $post = get_post( $postarr['ID'], ARRAY_A );
5601  
5602      if ( is_null( $post ) ) {
5603          if ( $wp_error ) {
5604              return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
5605          }
5606          return 0;
5607      }
5608  
5609      // Escape data pulled from DB.
5610      $post = wp_slash( $post );
5611  
5612      // Passed post category list overwrites existing category list if not empty.
5613      if ( isset( $postarr['post_category'] ) && is_array( $postarr['post_category'] )
5614          && count( $postarr['post_category'] ) > 0
5615      ) {
5616          $post_cats = $postarr['post_category'];
5617      } else {
5618          $post_cats = $post['post_category'];
5619      }
5620  
5621      // Drafts shouldn't be assigned a date unless explicitly done so by the user.
5622      if ( isset( $post['post_status'] )
5623          && in_array( $post['post_status'], array( 'draft', 'pending', 'auto-draft' ), true )
5624          && empty( $postarr['edit_date'] ) && ( '0000-00-00 00:00:00' === $post['post_date_gmt'] )
5625      ) {
5626          $clear_date = true;
5627      } else {
5628          $clear_date = false;
5629      }
5630  
5631      // Merge old and new fields with new fields overwriting old ones.
5632      $postarr                  = array_merge( $post, $postarr );
5633      $postarr['post_category'] = $post_cats;
5634      if ( $clear_date ) {
5635          $postarr['post_date']     = current_time( 'mysql' );
5636          $postarr['post_date_gmt'] = '';
5637      }
5638  
5639      if ( 'attachment' === $postarr['post_type'] ) {
5640          return wp_insert_attachment( $postarr, false, 0, $wp_error );
5641      }
5642  
5643      // Discard 'tags_input' parameter if it's the same as existing post tags.
5644      if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $postarr['post_type'], 'post_tag' ) ) {
5645          $tags      = get_the_terms( $postarr['ID'], 'post_tag' );
5646          $tag_names = array();
5647  
5648          if ( $tags && ! is_wp_error( $tags ) ) {
5649              $tag_names = wp_list_pluck( $tags, 'name' );
5650          }
5651  
5652          if ( $postarr['tags_input'] === $tag_names ) {
5653              unset( $postarr['tags_input'] );
5654          }
5655      }
5656  
5657      return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
5658  }
5659  
5660  /**
5661   * Publishes a post by transitioning the post status.
5662   *
5663   * @since 2.1.0
5664   *
5665   * @global wpdb $wpdb WordPress database abstraction object.
5666   *
5667   * @param int|WP_Post $post Post ID or post object.
5668   */
5669  function wp_publish_post( $post ) {
5670      global $wpdb;
5671  
5672      $post = get_post( $post );
5673  
5674      if ( ! $post ) {
5675          return;
5676      }
5677  
5678      if ( 'publish' === $post->post_status ) {
5679          return;
5680      }
5681  
5682      $post_before = get_post( $post->ID );
5683  
5684      // Ensure at least one term is applied for taxonomies with a default term.
5685      foreach ( get_object_taxonomies( $post->post_type, 'object' ) as $taxonomy => $tax_object ) {
5686          // Skip taxonomy if no default term is set.
5687          if (
5688              'category' !== $taxonomy &&
5689              empty( $tax_object->default_term )
5690          ) {
5691              continue;
5692          }
5693  
5694          // Do not modify previously set terms.
5695          if ( ! empty( get_the_terms( $post, $taxonomy ) ) ) {
5696              continue;
5697          }
5698  
5699          if ( 'category' === $taxonomy ) {
5700              $default_term_id = (int) get_option( 'default_category', 0 );
5701          } else {
5702              $default_term_id = (int) get_option( 'default_term_' . $taxonomy, 0 );
5703          }
5704  
5705          if ( ! $default_term_id ) {
5706              continue;
5707          }
5708          wp_set_post_terms( $post->ID, array( $default_term_id ), $taxonomy );
5709      }
5710  
5711      $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
5712  
5713      clean_post_cache( $post->ID );
5714  
5715      $old_status        = $post->post_status;
5716      $post->post_status = 'publish';
5717      wp_transition_post_status( 'publish', $old_status, $post );
5718  
5719      /** This action is documented in wp-includes/post.php */
5720      do_action( "edit_post_{$post->post_type}", $post->ID, $post );
5721  
5722      /** This action is documented in wp-includes/post.php */
5723      do_action( 'edit_post', $post->ID, $post );
5724  
5725      /** This action is documented in wp-includes/post.php */
5726      do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
5727  
5728      /** This action is documented in wp-includes/post.php */
5729      do_action( 'save_post', $post->ID, $post, true );
5730  
5731      /** This action is documented in wp-includes/post.php */
5732      do_action( 'wp_insert_post', $post->ID, $post, true );
5733  
5734      wp_after_insert_post( $post, true, $post_before );
5735  }
5736  
5737  /**
5738   * Publishes future post and make sure post ID has future post status.
5739   *
5740   * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
5741   * from publishing drafts, etc.
5742   *
5743   * @since 2.5.0
5744   *
5745   * @param int|WP_Post $post Post ID or post object.
5746   */
5747  function check_and_publish_future_post( $post ) {
5748      $post = get_post( $post );
5749  
5750      if ( ! $post ) {
5751          return;
5752      }
5753  
5754      if ( 'future' !== $post->post_status ) {
5755          return;
5756      }
5757  
5758      $time = strtotime( $post->post_date_gmt . ' GMT' );
5759  
5760      // Uh oh, someone jumped the gun!
5761      if ( $time > time() ) {
5762          wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); // Clear anything else in the system.
5763          wp_schedule_single_event( $time, 'publish_future_post', array( $post->ID ) );
5764          return;
5765      }
5766  
5767      // wp_publish_post() returns no meaningful value.
5768      wp_publish_post( $post->ID );
5769  }
5770  
5771  /**
5772   * Uses wp_checkdate to return a valid Gregorian-calendar value for post_date.
5773   * If post_date is not provided, this first checks post_date_gmt if provided,
5774   * then falls back to use the current time.
5775   *
5776   * For back-compat purposes in wp_insert_post, an empty post_date and an invalid
5777   * post_date_gmt will continue to return '1970-01-01 00:00:00' rather than false.
5778   *
5779   * @since 5.7.0
5780   *
5781   * @param string $post_date     The date in mysql format (`Y-m-d H:i:s`).
5782   * @param string $post_date_gmt The GMT date in mysql format (`Y-m-d H:i:s`).
5783   * @return string|false A valid Gregorian-calendar date string, or false on failure.
5784   */
5785  function wp_resolve_post_date( $post_date = '', $post_date_gmt = '' ) {
5786      // If the date is empty, set the date to now.
5787      if ( empty( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
5788          if ( empty( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
5789              $post_date = current_time( 'mysql' );
5790          } else {
5791              $post_date = get_date_from_gmt( $post_date_gmt );
5792          }
5793      }
5794  
5795      // Validate the date.
5796      preg_match( '/^(\d{4})-(\d{1,2})-(\d{1,2})/', $post_date, $matches );
5797  
5798      if ( empty( $matches ) || ! is_array( $matches ) || count( $matches ) < 4 ) {
5799          return false;
5800      }
5801  
5802      $valid_date = wp_checkdate( $matches[2], $matches[3], $matches[1], $post_date );
5803  
5804      if ( ! $valid_date ) {
5805          return false;
5806      }
5807      return $post_date;
5808  }
5809  
5810  /**
5811   * Computes a unique slug for the post, when given the desired slug and some post details.
5812   *
5813   * @since 2.8.0
5814   *
5815   * @global wpdb       $wpdb       WordPress database abstraction object.
5816   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
5817   *
5818   * @param string $slug        The desired slug (post_name).
5819   * @param int    $post_id     Post ID.
5820   * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
5821   * @param string $post_type   Post type.
5822   * @param int    $post_parent Post parent ID.
5823   * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
5824   */
5825  function wp_unique_post_slug( $slug, $post_id, $post_status, $post_type, $post_parent ) {
5826      if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true )
5827          || ( 'inherit' === $post_status && 'revision' === $post_type ) || 'user_request' === $post_type
5828      ) {
5829          return $slug;
5830      }
5831  
5832      /**
5833       * Filters the post slug before it is generated to be unique.
5834       *
5835       * Returning a non-null value will short-circuit the
5836       * unique slug generation, returning the passed value instead.
5837       *
5838       * @since 5.1.0
5839       *
5840       * @param string|null $override_slug Short-circuit return value.
5841       * @param string      $slug          The desired slug (post_name).
5842       * @param int         $post_id       Post ID.
5843       * @param string      $post_status   The post status.
5844       * @param string      $post_type     Post type.
5845       * @param int         $post_parent   Post parent ID.
5846       */
5847      $override_slug = apply_filters( 'pre_wp_unique_post_slug', null, $slug, $post_id, $post_status, $post_type, $post_parent );
5848      if ( null !== $override_slug ) {
5849          return $override_slug;
5850      }
5851  
5852      global $wpdb, $wp_rewrite;
5853  
5854      $original_slug = $slug;
5855  
5856      $feeds = $wp_rewrite->feeds;
5857      if ( ! is_array( $feeds ) ) {
5858          $feeds = array();
5859      }
5860  
5861      if ( 'attachment' === $post_type ) {
5862          // Attachment slugs must be unique across all types.
5863          $check_sql       = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
5864          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_id ) );
5865  
5866          /**
5867           * Filters whether the post slug would make a bad attachment slug.
5868           *
5869           * @since 3.1.0
5870           *
5871           * @param bool   $bad_slug Whether the slug would be bad as an attachment slug.
5872           * @param string $slug     The post slug.
5873           */
5874          $is_bad_attachment_slug = apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug );
5875  
5876          if ( $post_name_check
5877              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5878              || $is_bad_attachment_slug
5879          ) {
5880              $suffix = 2;
5881              do {
5882                  $alt_post_name   = wp_truncate_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5883                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_id ) );
5884                  ++$suffix;
5885              } while ( $post_name_check );
5886              $slug = $alt_post_name;
5887          }
5888      } elseif ( is_post_type_hierarchical( $post_type ) ) {
5889          if ( 'nav_menu_item' === $post_type ) {
5890              return $slug;
5891          }
5892  
5893          /*
5894           * Page slugs must be unique within their own trees. Pages are in a separate
5895           * namespace than posts so page slugs are allowed to overlap post slugs.
5896           */
5897          $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";
5898          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_id, $post_parent ) );
5899  
5900          /**
5901           * Filters whether the post slug would make a bad hierarchical post slug.
5902           *
5903           * @since 3.1.0
5904           *
5905           * @param bool   $bad_slug    Whether the post slug would be bad in a hierarchical post context.
5906           * @param string $slug        The post slug.
5907           * @param string $post_type   Post type.
5908           * @param int    $post_parent Post parent ID.
5909           */
5910          $is_bad_hierarchical_slug = apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent );
5911  
5912          if ( $post_name_check
5913              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5914              || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )
5915              || $is_bad_hierarchical_slug
5916          ) {
5917              $suffix = 2;
5918              do {
5919                  $alt_post_name   = wp_truncate_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5920                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_id, $post_parent ) );
5921                  ++$suffix;
5922              } while ( $post_name_check );
5923              $slug = $alt_post_name;
5924          }
5925      } else {
5926          // Post slugs must be unique across all posts.
5927          $check_sql       = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
5928          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_id ) );
5929  
5930          $post = get_post( $post_id );
5931  
5932          // Prevent new post slugs that could result in URLs that conflict with date archives.
5933          $conflicts_with_date_archive = false;
5934          if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) ) {
5935              $slug_num = (int) $slug;
5936  
5937              if ( $slug_num ) {
5938                  $permastructs   = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
5939                  $postname_index = array_search( '%postname%', $permastructs, true );
5940  
5941                  /*
5942                  * Potential date clashes are as follows:
5943                  *
5944                  * - Any integer in the first permastruct position could be a year.
5945                  * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
5946                  * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
5947                  */
5948                  if ( 0 === $postname_index ||
5949                      ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
5950                      ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
5951                  ) {
5952                      $conflicts_with_date_archive = true;
5953                  }
5954              }
5955          }
5956  
5957          /**
5958           * Filters whether the post slug would be bad as a flat slug.
5959           *
5960           * @since 3.1.0
5961           *
5962           * @param bool   $bad_slug  Whether the post slug would be bad as a flat slug.
5963           * @param string $slug      The post slug.
5964           * @param string $post_type Post type.
5965           */
5966          $is_bad_flat_slug = apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type );
5967  
5968          if ( $post_name_check
5969              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5970              || $conflicts_with_date_archive
5971              || $is_bad_flat_slug
5972          ) {
5973              $suffix = 2;
5974              do {
5975                  $alt_post_name   = wp_truncate_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5976                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_id ) );
5977                  ++$suffix;
5978              } while ( $post_name_check );
5979              $slug = $alt_post_name;
5980          }
5981      }
5982  
5983      /**
5984       * Filters the unique post slug.
5985       *
5986       * @since 3.3.0
5987       *
5988       * @param string $slug          The post slug.
5989       * @param int    $post_id       Post ID.
5990       * @param string $post_status   The post status.
5991       * @param string $post_type     Post type.
5992       * @param int    $post_parent   Post parent ID
5993       * @param string $original_slug The original post slug.
5994       */
5995      return apply_filters( 'wp_unique_post_slug', $slug, $post_id, $post_status, $post_type, $post_parent, $original_slug );
5996  }
5997  
5998  /**
5999   * Adds tags to a post.
6000   *
6001   * @see wp_set_post_tags()
6002   *
6003   * @since 2.3.0
6004   *
6005   * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
6006   * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
6007   *                              separated by commas. Default empty.
6008   * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
6009   */
6010  function wp_add_post_tags( $post_id = 0, $tags = '' ) {
6011      return wp_set_post_tags( $post_id, $tags, true );
6012  }
6013  
6014  /**
6015   * Sets the tags for a post.
6016   *
6017   * @since 2.3.0
6018   *
6019   * @see wp_set_object_terms()
6020   *
6021   * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
6022   * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
6023   *                              separated by commas. Default empty.
6024   * @param bool         $append  Optional. If true, don't delete existing tags, just add on. If false,
6025   *                              replace the tags with the new tags. Default false.
6026   * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
6027   */
6028  function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
6029      return wp_set_post_terms( $post_id, $tags, 'post_tag', $append );
6030  }
6031  
6032  /**
6033   * Sets the terms for a post.
6034   *
6035   * @since 2.8.0
6036   *
6037   * @see wp_set_object_terms()
6038   *
6039   * @param int          $post_id  Optional. The Post ID. Does not default to the ID of the global $post.
6040   * @param string|array $terms    Optional. An array of terms to set for the post, or a string of terms
6041   *                               separated by commas. Hierarchical taxonomies must always pass IDs rather
6042   *                               than names so that children with the same names but different parents
6043   *                               aren't confused. Default empty.
6044   * @param string       $taxonomy Optional. Taxonomy name. Default 'post_tag'.
6045   * @param bool         $append   Optional. If true, don't delete existing terms, just add on. If false,
6046   *                               replace the terms with the new terms. Default false.
6047   * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
6048   */
6049  function wp_set_post_terms( $post_id = 0, $terms = '', $taxonomy = 'post_tag', $append = false ) {
6050      $post_id = (int) $post_id;
6051  
6052      if ( ! $post_id ) {
6053          return false;
6054      }
6055  
6056      if ( empty( $terms ) ) {
6057          $terms = array();
6058      }
6059  
6060      if ( ! is_array( $terms ) ) {
6061          $comma = _x( ',', 'tag delimiter' );
6062          if ( ',' !== $comma ) {
6063              $terms = str_replace( $comma, ',', $terms );
6064          }
6065          $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
6066      }
6067  
6068      /*
6069       * Hierarchical taxonomies must always pass IDs rather than names so that
6070       * children with the same names but different parents aren't confused.
6071       */
6072      if ( is_taxonomy_hierarchical( $taxonomy ) ) {
6073          $terms = array_unique( array_map( 'intval', $terms ) );
6074      }
6075  
6076      return wp_set_object_terms( $post_id, $terms, $taxonomy, $append );
6077  }
6078  
6079  /**
6080   * Sets categories for a post.
6081   *
6082   * If no categories are provided, the default category is used.
6083   *
6084   * @since 2.1.0
6085   *
6086   * @param int       $post_id         Optional. The Post ID. Does not default to the ID
6087   *                                   of the global $post. Default 0.
6088   * @param int[]|int $post_categories Optional. List of category IDs, or the ID of a single category.
6089   *                                   Default empty array.
6090   * @param bool      $append          If true, don't delete existing categories, just add on.
6091   *                                   If false, replace the categories with the new categories.
6092   * @return array|false|WP_Error Array of term taxonomy IDs of affected categories. WP_Error or false on failure.
6093   */
6094  function wp_set_post_categories( $post_id = 0, $post_categories = array(), $append = false ) {
6095      $post_id     = (int) $post_id;
6096      $post_type   = get_post_type( $post_id );
6097      $post_status = get_post_status( $post_id );
6098  
6099      // If $post_categories isn't already an array, make it one.
6100      $post_categories = (array) $post_categories;
6101  
6102      if ( empty( $post_categories ) ) {
6103          /**
6104           * Filters post types (in addition to 'post') that require a default category.
6105           *
6106           * @since 5.5.0
6107           *
6108           * @param string[] $post_types An array of post type names. Default empty array.
6109           */
6110          $default_category_post_types = apply_filters( 'default_category_post_types', array() );
6111  
6112          // Regular posts always require a default category.
6113          $default_category_post_types = array_merge( $default_category_post_types, array( 'post' ) );
6114  
6115          if ( in_array( $post_type, $default_category_post_types, true )
6116              && is_object_in_taxonomy( $post_type, 'category' )
6117              && 'auto-draft' !== $post_status
6118          ) {
6119              $post_categories = array( get_option( 'default_category' ) );
6120              $append          = false;
6121          } else {
6122              $post_categories = array();
6123          }
6124      } elseif ( 1 === count( $post_categories ) && '' === reset( $post_categories ) ) {
6125          return true;
6126      }
6127  
6128      return wp_set_post_terms( $post_id, $post_categories, 'category', $append );
6129  }
6130  
6131  /**
6132   * Fires actions related to the transitioning of a post's status.
6133   *
6134   * When a post is saved, the post status is "transitioned" from one status to another,
6135   * though this does not always mean the status has actually changed before and after
6136   * the save. This function fires a number of action hooks related to that transition:
6137   * the generic {@see 'transition_post_status'} action, as well as the dynamic hooks
6138   * {@see '$old_status_to_$new_status'} and {@see '$new_status_$post->post_type'}. Note
6139   * that the function does not transition the post object in the database.
6140   *
6141   * For instance: When publishing a post for the first time, the post status may transition
6142   * from 'draft' – or some other status – to 'publish'. However, if a post is already
6143   * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
6144   * before and after the transition.
6145   *
6146   * @since 2.3.0
6147   *
6148   * @param string  $new_status Transition to this post status.
6149   * @param string  $old_status Previous post status.
6150   * @param WP_Post $post       Post data.
6151   */
6152  function wp_transition_post_status( $new_status, $old_status, $post ) {
6153      /**
6154       * Fires when a post is transitioned from one status to another.
6155       *
6156       * @since 2.3.0
6157       *
6158       * @param string  $new_status New post status.
6159       * @param string  $old_status Old post status.
6160       * @param WP_Post $post       Post object.
6161       */
6162      do_action( 'transition_post_status', $new_status, $old_status, $post );
6163  
6164      $new_status_object = get_post_status_object( $new_status );
6165      $old_status_valid  = get_post_status_object( $old_status ) || 'new' === $old_status;
6166      $post_type_object  = get_post_type_object( $post->post_type );
6167  
6168      if ( $new_status_object && $old_status_valid ) {
6169          /**
6170           * Fires when a post is transitioned from one status to another.
6171           *
6172           * The dynamic portions of the hook name, `$new_status` and `$old_status`,
6173           * refer to the old and new post statuses, respectively.
6174           *
6175           * Possible hook names include:
6176           *
6177           *  - `draft_to_publish`
6178           *  - `publish_to_trash`
6179           *  - `pending_to_draft`
6180           *
6181           * @since 2.3.0
6182           *
6183           * @param WP_Post $post Post object.
6184           */
6185          do_action( "{$old_status}_to_{$new_status}", $post );
6186      }
6187  
6188      if ( $new_status_object && $post_type_object ) {
6189          /**
6190           * Fires when a post is transitioned from one status to another.
6191           *
6192           * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
6193           * refer to the new post status and post type, respectively.
6194           *
6195           * Possible hook names include:
6196           *
6197           *  - `draft_post`
6198           *  - `future_post`
6199           *  - `pending_post`
6200           *  - `private_post`
6201           *  - `publish_post`
6202           *  - `trash_post`
6203           *  - `draft_page`
6204           *  - `future_page`
6205           *  - `pending_page`
6206           *  - `private_page`
6207           *  - `publish_page`
6208           *  - `trash_page`
6209           *  - `publish_attachment`
6210           *  - `trash_attachment`
6211           *
6212           * Please note: When this action is hooked using a particular post status (like
6213           * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
6214           * first transitioned to that status from something else, as well as upon
6215           * subsequent post updates (old and new status are both the same).
6216           *
6217           * Therefore, if you are looking to only fire a callback when a post is first
6218           * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
6219           *
6220           * @since 2.3.0
6221           * @since 5.9.0 Added `$old_status` parameter.
6222           *
6223           * @param int     $post_id    Post ID.
6224           * @param WP_Post $post       Post object.
6225           * @param string  $old_status Old post status.
6226           */
6227          do_action( "{$new_status}_{$post->post_type}", $post->ID, $post, $old_status );
6228      }
6229  }
6230  
6231  /**
6232   * Fires actions after a post, its terms and meta data has been saved.
6233   *
6234   * @since 5.6.0
6235   *
6236   * @param int|WP_Post  $post        The post ID or object that has been saved.
6237   * @param bool         $update      Whether this is an existing post being updated.
6238   * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
6239   *                                  to the update for updated posts.
6240   */
6241  function wp_after_insert_post( $post, $update, $post_before ) {
6242      $post = get_post( $post );
6243  
6244      if ( ! $post ) {
6245          return;
6246      }
6247  
6248      $post_id = $post->ID;
6249  
6250      /**
6251       * Fires once a post, its terms and meta data has been saved.
6252       *
6253       * @since 5.6.0
6254       *
6255       * @param int          $post_id     Post ID.
6256       * @param WP_Post      $post        Post object.
6257       * @param bool         $update      Whether this is an existing post being updated.
6258       * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
6259       *                                  to the update for updated posts.
6260       */
6261      do_action( 'wp_after_insert_post', $post_id, $post, $update, $post_before );
6262  }
6263  
6264  //
6265  // Comment, trackback, and pingback functions.
6266  //
6267  
6268  /**
6269   * Adds a URL to those already pinged.
6270   *
6271   * @since 1.5.0
6272   * @since 4.7.0 `$post` can be a WP_Post object.
6273   * @since 4.7.0 `$uri` can be an array of URIs.
6274   *
6275   * @global wpdb $wpdb WordPress database abstraction object.
6276   *
6277   * @param int|WP_Post  $post Post ID or post object.
6278   * @param string|array $uri  Ping URI or array of URIs.
6279   * @return int|false How many rows were updated.
6280   */
6281  function add_ping( $post, $uri ) {
6282      global $wpdb;
6283  
6284      $post = get_post( $post );
6285  
6286      if ( ! $post ) {
6287          return false;
6288      }
6289  
6290      $pung = trim( $post->pinged );
6291      $pung = preg_split( '/\s/', $pung );
6292  
6293      if ( is_array( $uri ) ) {
6294          $pung = array_merge( $pung, $uri );
6295      } else {
6296          $pung[] = $uri;
6297      }
6298      $new = implode( "\n", $pung );
6299  
6300      /**
6301       * Filters the new ping URL to add for the given post.
6302       *
6303       * @since 2.0.0
6304       *
6305       * @param string $new New ping URL to add.
6306       */
6307      $new = apply_filters( 'add_ping', $new );
6308  
6309      $return = $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post->ID ) );
6310      clean_post_cache( $post->ID );
6311      return $return;
6312  }
6313  
6314  /**
6315   * Retrieves enclosures already enclosed for a post.
6316   *
6317   * @since 1.5.0
6318   *
6319   * @param int $post_id Post ID.
6320   * @return string[] Array of enclosures for the given post.
6321   */
6322  function get_enclosed( $post_id ) {
6323      $custom_fields = get_post_custom( $post_id );
6324      $pung          = array();
6325      if ( ! is_array( $custom_fields ) ) {
6326          return $pung;
6327      }
6328  
6329      foreach ( $custom_fields as $key => $val ) {
6330          if ( 'enclosure' !== $key || ! is_array( $val ) ) {
6331              continue;
6332          }
6333          foreach ( $val as $enc ) {
6334              $enclosure = explode( "\n", $enc );
6335              $pung[]    = trim( $enclosure[0] );
6336          }
6337      }
6338  
6339      /**
6340       * Filters the list of enclosures already enclosed for the given post.
6341       *
6342       * @since 2.0.0
6343       *
6344       * @param string[] $pung    Array of enclosures for the given post.
6345       * @param int      $post_id Post ID.
6346       */
6347      return apply_filters( 'get_enclosed', $pung, $post_id );
6348  }
6349  
6350  /**
6351   * Retrieves URLs already pinged for a post.
6352   *
6353   * @since 1.5.0
6354   *
6355   * @since 4.7.0 `$post` can be a WP_Post object.
6356   *
6357   * @param int|WP_Post $post Post ID or object.
6358   * @return string[]|false Array of URLs already pinged for the given post, false if the post is not found.
6359   */
6360  function get_pung( $post ) {
6361      $post = get_post( $post );
6362  
6363      if ( ! $post ) {
6364          return false;
6365      }
6366  
6367      $pung = trim( $post->pinged );
6368      $pung = preg_split( '/\s/', $pung );
6369  
6370      /**
6371       * Filters the list of already-pinged URLs for the given post.
6372       *
6373       * @since 2.0.0
6374       *
6375       * @param string[] $pung Array of URLs already pinged for the given post.
6376       */
6377      return apply_filters( 'get_pung', $pung );
6378  }
6379  
6380  /**
6381   * Retrieves URLs that need to be pinged.
6382   *
6383   * @since 1.5.0
6384   * @since 4.7.0 `$post` can be a WP_Post object.
6385   *
6386   * @param int|WP_Post $post Post ID or post object.
6387   * @return string[]|false List of URLs yet to ping.
6388   */
6389  function get_to_ping( $post ) {
6390      $post = get_post( $post );
6391  
6392      if ( ! $post ) {
6393          return false;
6394      }
6395  
6396      $to_ping = sanitize_trackback_urls( $post->to_ping );
6397      $to_ping = preg_split( '/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY );
6398  
6399      /**
6400       * Filters the list of URLs yet to ping for the given post.
6401       *
6402       * @since 2.0.0
6403       *
6404       * @param string[] $to_ping List of URLs yet to ping.
6405       */
6406      return apply_filters( 'get_to_ping', $to_ping );
6407  }
6408  
6409  /**
6410   * Does trackbacks for a list of URLs.
6411   *
6412   * @since 1.0.0
6413   *
6414   * @param string $tb_list Comma separated list of URLs.
6415   * @param int    $post_id Post ID.
6416   */
6417  function trackback_url_list( $tb_list, $post_id ) {
6418      if ( ! empty( $tb_list ) ) {
6419          // Get post data.
6420          $post = get_post( $post_id );
6421          if ( ! $post ) {
6422              return;
6423          }
6424          $postdata = $post->to_array();
6425  
6426          // Form an excerpt.
6427          $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
6428  
6429          if ( strlen( $excerpt ) > 255 ) {
6430              $excerpt = substr( $excerpt, 0, 252 ) . '&hellip;';
6431          }
6432  
6433          $trackback_urls = explode( ',', $tb_list );
6434          foreach ( (array) $trackback_urls as $tb_url ) {
6435              $tb_url = trim( $tb_url );
6436              trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
6437          }
6438      }
6439  }
6440  
6441  //
6442  // Page functions.
6443  //
6444  
6445  /**
6446   * Gets a list of page IDs.
6447   *
6448   * @since 2.0.0
6449   *
6450   * @global wpdb $wpdb WordPress database abstraction object.
6451   *
6452   * @return string[] List of page IDs as strings.
6453   */
6454  function get_all_page_ids() {
6455      global $wpdb;
6456  
6457      $page_ids = wp_cache_get( 'all_page_ids', 'posts' );
6458      if ( ! is_array( $page_ids ) ) {
6459          $page_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'page'" );
6460          wp_cache_add( 'all_page_ids', $page_ids, 'posts' );
6461      }
6462  
6463      return $page_ids;
6464  }
6465  
6466  /**
6467   * Retrieves page data given a page ID or page object.
6468   *
6469   * Use get_post() instead of get_page().
6470   *
6471   * @since 1.5.1
6472   * @deprecated 3.5.0 Use get_post()
6473   *
6474   * @param int|WP_Post $page   Page object or page ID. Passed by reference.
6475   * @param string      $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
6476   *                            correspond to a WP_Post object, an associative array, or a numeric array,
6477   *                            respectively. Default OBJECT.
6478   * @param string      $filter Optional. How the return value should be filtered. Accepts 'raw',
6479   *                            'edit', 'db', 'display'. Default 'raw'.
6480   * @return WP_Post|array|null WP_Post or array on success, null on failure.
6481   *
6482   * @phpstan-param int|decimal-int-string|WP_Post|null $page
6483   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
6484   * @phpstan-param 'raw'|'edit'|'db'|'display' $filter
6485   * @phpstan-return (
6486   *     $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : (
6487   *         $output is 'ARRAY_N' ? non-empty-array<int, mixed>|null : (
6488   *             WP_Post|null
6489   *         )
6490   *     )
6491   * )
6492   */
6493  function get_page( $page, $output = OBJECT, $filter = 'raw' ) {
6494      return get_post( $page, $output, $filter );
6495  }
6496  
6497  /**
6498   * Retrieves a page given its path.
6499   *
6500   * @since 2.1.0
6501   *
6502   * @global wpdb $wpdb WordPress database abstraction object.
6503   *
6504   * @param string       $page_path Page path.
6505   * @param string       $output    Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
6506   *                                correspond to a WP_Post object, an associative array, or a numeric array,
6507   *                                respectively. Default OBJECT.
6508   * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
6509   * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
6510   *
6511   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
6512   * @phpstan-param string|string[]              $post_type
6513   * @phpstan-return (
6514   *     $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : (
6515   *         $output is 'ARRAY_N' ? non-empty-array<int, mixed>|null : (
6516   *             WP_Post|null
6517   *         )
6518   *     )
6519   * )
6520   */
6521  function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
6522      global $wpdb;
6523  
6524      $last_changed = wp_cache_get_last_changed( 'posts' );
6525  
6526      $hash      = md5( $page_path . serialize( $post_type ) );
6527      $cache_key = "get_page_by_path:$hash";
6528      $cached    = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
6529      if ( false !== $cached ) {
6530          // Special case: '0' is a bad `$page_path`.
6531          if ( '0' === $cached || 0 === $cached ) {
6532              return null;
6533          } else {
6534              return get_post( (int) $cached, $output );
6535          }
6536      }
6537  
6538      $page_path     = rawurlencode( urldecode( $page_path ) );
6539      $page_path     = str_replace( '%2F', '/', $page_path );
6540      $page_path     = str_replace( '%20', ' ', $page_path );
6541      $parts         = explode( '/', trim( $page_path, '/' ) );
6542      $parts         = array_map( 'sanitize_title_for_query', $parts );
6543      $escaped_parts = esc_sql( $parts );
6544  
6545      $in_string = "'" . implode( "','", $escaped_parts ) . "'";
6546  
6547      if ( is_array( $post_type ) ) {
6548          $post_types = $post_type;
6549      } else {
6550          $post_types = array( $post_type, 'attachment' );
6551      }
6552  
6553      $post_types          = esc_sql( $post_types );
6554      $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
6555      $sql                 = "
6556          SELECT ID, post_name, post_parent, post_type
6557          FROM $wpdb->posts
6558          WHERE post_name IN ($in_string)
6559          AND post_type IN ($post_type_in_string)
6560          ORDER BY
6561              post_status = 'publish' DESC,
6562              post_status IN ('draft', 'pending', 'auto-draft') ASC, ID ASC
6563      ";
6564  
6565      /** @var array<object{ ID: string, post_name: string, post_parent: string, post_type: string }> $pages */
6566      $pages = $wpdb->get_results( $sql, OBJECT_K ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The escaping has been applied above via esc_sql().
6567  
6568      $revparts = array_reverse( $parts );
6569  
6570      $found_id = 0;
6571      foreach ( (array) $pages as $page ) {
6572          if ( $page->post_name === $revparts[0] ) {
6573              $count = 0;
6574              $p     = $page;
6575  
6576              /*
6577               * Loop through the given path parts from right to left,
6578               * ensuring each matches the post ancestry.
6579               */
6580              while ( 0 !== (int) $p->post_parent && isset( $pages[ $p->post_parent ] ) ) {
6581                  ++$count;
6582                  $parent = $pages[ $p->post_parent ];
6583                  if ( ! isset( $revparts[ $count ] ) || $parent->post_name !== $revparts[ $count ] ) {
6584                      break;
6585                  }
6586                  $p = $parent;
6587              }
6588  
6589              if ( 0 === (int) $p->post_parent
6590                  && count( $revparts ) === $count + 1
6591                  && $p->post_name === $revparts[ $count ]
6592              ) {
6593                  $found_id = $page->ID;
6594  
6595                  /*
6596                   * A string like 'page' also searches attachments: /about/photo/ could be
6597                   * a child page or an attachment page, and this lookup handles both.
6598                   * Keep an attachment as a fallback, but keep looking for the requested
6599                   * type so an attachment cannot hide a page with the same path.
6600                   *
6601                   * An array is the exact list of types to search; no extra types are added.
6602                   * SQL already checks that list, so stop at the first full-path match.
6603                   */
6604                  if ( is_array( $post_type ) || $page->post_type === $post_type ) {
6605                      break;
6606                  }
6607              }
6608          }
6609      }
6610  
6611      // We cache misses as well as hits.
6612      wp_cache_set_salted( $cache_key, $found_id, 'post-queries', $last_changed );
6613  
6614      if ( $found_id ) {
6615          return get_post( (int) $found_id, $output );
6616      }
6617  
6618      return null;
6619  }
6620  
6621  /**
6622   * Identifies descendants of a given page ID in a list of page objects.
6623   *
6624   * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
6625   *
6626   * @since 1.5.1
6627   *
6628   * @param int       $page_id Page ID.
6629   * @param WP_Post[] $pages   List of page objects from which descendants should be identified.
6630   * @return WP_Post[] List of page children.
6631   */
6632  function get_page_children( $page_id, $pages ) {
6633      // Build a hash of ID -> children.
6634      $children = array();
6635      foreach ( (array) $pages as $page ) {
6636          $children[ (int) $page->post_parent ][] = $page;
6637      }
6638  
6639      $page_list = array();
6640  
6641      // Start the search by looking at immediate children.
6642      if ( isset( $children[ $page_id ] ) ) {
6643          // Always start at the end of the stack in order to preserve original `$pages` order.
6644          $to_look = array_reverse( $children[ $page_id ] );
6645  
6646          while ( $to_look ) {
6647              $p           = array_pop( $to_look );
6648              $page_list[] = $p;
6649              if ( isset( $children[ $p->ID ] ) ) {
6650                  foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
6651                      // Append to the `$to_look` stack to descend the tree.
6652                      $to_look[] = $child;
6653                  }
6654              }
6655          }
6656      }
6657  
6658      return $page_list;
6659  }
6660  
6661  /**
6662   * Orders the pages with children under parents in a flat list.
6663   *
6664   * It uses auxiliary structure to hold parent-children relationships and
6665   * runs in O(N) complexity
6666   *
6667   * @since 2.0.0
6668   *
6669   * @param WP_Post[] $pages   Posts array (passed by reference).
6670   * @param int       $page_id Optional. Parent page ID. Default 0.
6671   * @return string[] Array of post names keyed by ID and arranged by hierarchy. Children immediately follow their parents.
6672   */
6673  function get_page_hierarchy( &$pages, $page_id = 0 ) {
6674      if ( empty( $pages ) ) {
6675          return array();
6676      }
6677  
6678      $children = array();
6679      foreach ( (array) $pages as $p ) {
6680          $parent_id                = (int) $p->post_parent;
6681          $children[ $parent_id ][] = $p;
6682      }
6683  
6684      $result = array();
6685      _page_traverse_name( $page_id, $children, $result );
6686  
6687      return $result;
6688  }
6689  
6690  /**
6691   * Traverses and return all the nested children post names of a root page.
6692   *
6693   * $children contains parent-children relations
6694   *
6695   * @since 2.9.0
6696   * @access private
6697   *
6698   * @see _page_traverse_name()
6699   *
6700   * @param int      $page_id  Page ID.
6701   * @param array    $children Parent-children relations (passed by reference).
6702   * @param string[] $result   Array of page names keyed by ID (passed by reference).
6703   */
6704  function _page_traverse_name( $page_id, &$children, &$result ) {
6705      if ( isset( $children[ $page_id ] ) ) {
6706          foreach ( (array) $children[ $page_id ] as $child ) {
6707              $result[ $child->ID ] = $child->post_name;
6708              _page_traverse_name( $child->ID, $children, $result );
6709          }
6710      }
6711  }
6712  
6713  /**
6714   * Builds the URI path for a page.
6715   *
6716   * Sub pages will be in the "directory" under the parent page post name.
6717   *
6718   * @since 1.5.0
6719   * @since 4.6.0 The `$page` parameter was made optional.
6720   *
6721   * @param WP_Post|object|int $page Optional. Page ID or WP_Post object. Default is global $post.
6722   * @return string|false Page URI, false on error.
6723   */
6724  function get_page_uri( $page = 0 ) {
6725      if ( ! $page instanceof WP_Post ) {
6726          $page = get_post( $page );
6727      }
6728  
6729      if ( ! $page ) {
6730          return false;
6731      }
6732  
6733      $uri = $page->post_name;
6734  
6735      foreach ( $page->ancestors as $parent ) {
6736          $parent = get_post( $parent );
6737          if ( $parent && $parent->post_name ) {
6738              $uri = $parent->post_name . '/' . $uri;
6739          }
6740      }
6741  
6742      /**
6743       * Filters the URI for a page.
6744       *
6745       * @since 4.4.0
6746       *
6747       * @param string  $uri  Page URI.
6748       * @param WP_Post $page Page object.
6749       */
6750      return apply_filters( 'get_page_uri', $uri, $page );
6751  }
6752  
6753  /**
6754   * Retrieves an array of pages (or hierarchical post type items).
6755   *
6756   * @since 1.5.0
6757   * @since 6.3.0 Use WP_Query internally.
6758   *
6759   * @param array|string $args {
6760   *     Optional. Array or string of arguments to retrieve pages.
6761   *
6762   *     @type int          $child_of     Page ID to return child and grandchild pages of. Note: The value
6763   *                                      of `$hierarchical` has no bearing on whether `$child_of` returns
6764   *                                      hierarchical results. Default 0, or no restriction.
6765   *     @type string       $sort_order   How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
6766   *     @type string       $sort_column  What columns to sort pages by, comma-separated. Accepts 'post_author',
6767   *                                      'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
6768   *                                      'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
6769   *                                      'post_' can be omitted for any values that start with it.
6770   *                                      Default 'post_title'.
6771   *     @type bool         $hierarchical Whether to return pages hierarchically. If false in conjunction with
6772   *                                      `$child_of` also being false, both arguments will be disregarded.
6773   *                                      Default true.
6774   *     @type int[]        $exclude      Array of page IDs to exclude. Default empty array.
6775   *     @type int[]        $include      Array of page IDs to include. Cannot be used with `$child_of`,
6776   *                                      `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
6777   *                                      Default empty array.
6778   *     @type string       $meta_key     Only include pages with this meta key. Default empty.
6779   *     @type string       $meta_value   Only include pages with this meta value. Requires `$meta_key`.
6780   *                                      Default empty.
6781   *     @type string       $authors      A comma-separated list of author IDs. Default empty.
6782   *     @type int          $parent       Page ID to return direct children of. Default -1, or no restriction.
6783   *     @type string|int[] $exclude_tree Comma-separated string or array of page IDs to exclude.
6784   *                                      Default empty array.
6785   *     @type int          $number       The number of pages to return. Default 0, or all pages.
6786   *     @type int          $offset       The number of pages to skip before returning. Requires `$number`.
6787   *                                      Default 0.
6788   *     @type string       $post_type    The post type to query. Default 'page'.
6789   *     @type string|array $post_status  A comma-separated list or array of post statuses to include.
6790   *                                      Default 'publish'.
6791   * }
6792   * @return WP_Post[]|false Array of pages (or hierarchical post type items). Boolean false if the
6793   *                         specified post type is not hierarchical or the specified status is not
6794   *                         supported by the post type.
6795   */
6796  function get_pages( $args = array() ) {
6797      $defaults = array(
6798          'child_of'     => 0,
6799          'sort_order'   => 'ASC',
6800          'sort_column'  => 'post_title',
6801          'hierarchical' => 1,
6802          'exclude'      => array(),
6803          'include'      => array(),
6804          'meta_key'     => '',
6805          'meta_value'   => '',
6806          'authors'      => '',
6807          'parent'       => -1,
6808          'exclude_tree' => array(),
6809          'number'       => '',
6810          'offset'       => 0,
6811          'post_type'    => 'page',
6812          'post_status'  => 'publish',
6813      );
6814  
6815      $parsed_args = wp_parse_args( $args, $defaults );
6816  
6817      $number       = (int) $parsed_args['number'];
6818      $offset       = (int) $parsed_args['offset'];
6819      $child_of     = (int) $parsed_args['child_of'];
6820      $hierarchical = $parsed_args['hierarchical'];
6821      $exclude      = $parsed_args['exclude'];
6822      $meta_key     = $parsed_args['meta_key'];
6823      $meta_value   = $parsed_args['meta_value'];
6824      $parent       = $parsed_args['parent'];
6825      $post_status  = $parsed_args['post_status'];
6826  
6827      // Make sure the post type is hierarchical.
6828      $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
6829      if ( ! in_array( $parsed_args['post_type'], $hierarchical_post_types, true ) ) {
6830          return false;
6831      }
6832  
6833      if ( $parent > 0 && ! $child_of ) {
6834          $hierarchical = false;
6835      }
6836  
6837      // Make sure we have a valid post status.
6838      if ( ! is_array( $post_status ) ) {
6839          $post_status = explode( ',', $post_status );
6840      }
6841      if ( array_diff( $post_status, get_post_stati() ) ) {
6842          return false;
6843      }
6844  
6845      $query_args = array(
6846          'orderby'                => 'post_title',
6847          'order'                  => 'ASC',
6848          'post__not_in'           => wp_parse_id_list( $exclude ),
6849          'meta_key'               => $meta_key,
6850          'meta_value'             => $meta_value,
6851          'posts_per_page'         => -1,
6852          'offset'                 => $offset,
6853          'post_type'              => $parsed_args['post_type'],
6854          'post_status'            => $post_status,
6855          'update_post_term_cache' => false,
6856          'update_post_meta_cache' => false,
6857          'ignore_sticky_posts'    => true,
6858          'no_found_rows'          => true,
6859      );
6860  
6861      if ( ! empty( $parsed_args['include'] ) ) {
6862          $child_of = 0; // Ignore child_of, parent, exclude, meta_key, and meta_value params if using include.
6863          $parent   = -1;
6864          unset( $query_args['post__not_in'], $query_args['meta_key'], $query_args['meta_value'] );
6865          $hierarchical           = false;
6866          $query_args['post__in'] = wp_parse_id_list( $parsed_args['include'] );
6867      }
6868  
6869      if ( ! empty( $parsed_args['authors'] ) ) {
6870          $post_authors = wp_parse_list( $parsed_args['authors'] );
6871  
6872          if ( ! empty( $post_authors ) ) {
6873              $query_args['author__in'] = array();
6874              foreach ( $post_authors as $post_author ) {
6875                  // Do we have an author id or an author login?
6876                  if ( 0 === (int) $post_author ) {
6877                      $post_author = get_user_by( 'login', $post_author );
6878                      if ( empty( $post_author ) ) {
6879                          continue;
6880                      }
6881                      if ( empty( $post_author->ID ) ) {
6882                          continue;
6883                      }
6884                      $post_author = $post_author->ID;
6885                  }
6886                  $query_args['author__in'][] = (int) $post_author;
6887              }
6888          }
6889      }
6890  
6891      if ( is_array( $parent ) ) {
6892          $post_parent__in = array_map( 'absint', (array) $parent );
6893          if ( ! empty( $post_parent__in ) ) {
6894              $query_args['post_parent__in'] = $post_parent__in;
6895          }
6896      } elseif ( $parent >= 0 ) {
6897          $query_args['post_parent'] = $parent;
6898      }
6899  
6900      /*
6901       * Maintain backward compatibility for `sort_column` key.
6902       * Additionally to `WP_Query`, it has been supporting the `post_modified_gmt` field, so this logic will translate
6903       * it to `post_modified` which should result in the same order given the two dates in the fields match.
6904       */
6905      $orderby = wp_parse_list( $parsed_args['sort_column'] );
6906      $orderby = array_map(
6907          static function ( $orderby_field ) {
6908              $orderby_field = trim( $orderby_field );
6909              if ( 'post_modified_gmt' === $orderby_field || 'modified_gmt' === $orderby_field ) {
6910                  $orderby_field = str_replace( '_gmt', '', $orderby_field );
6911              }
6912              return $orderby_field;
6913          },
6914          $orderby
6915      );
6916      if ( $orderby ) {
6917          $query_args['orderby'] = array_fill_keys( $orderby, $parsed_args['sort_order'] );
6918      }
6919  
6920      $order = $parsed_args['sort_order'];
6921      if ( $order ) {
6922          $query_args['order'] = $order;
6923      }
6924  
6925      if ( ! empty( $number ) ) {
6926          $query_args['posts_per_page'] = $number;
6927      }
6928  
6929      /**
6930       * Filters query arguments passed to WP_Query in get_pages().
6931       *
6932       * @since 6.3.0
6933       *
6934       * @param array $query_args  Array of arguments passed to WP_Query.
6935       * @param array $parsed_args Array of get_pages() arguments.
6936       */
6937      $query_args = apply_filters( 'get_pages_query_args', $query_args, $parsed_args );
6938  
6939      $pages = new WP_Query();
6940      $pages = $pages->query( $query_args );
6941  
6942      if ( $child_of || $hierarchical ) {
6943          $pages = get_page_children( $child_of, $pages );
6944      }
6945  
6946      if ( ! empty( $parsed_args['exclude_tree'] ) ) {
6947          $exclude = wp_parse_id_list( $parsed_args['exclude_tree'] );
6948          foreach ( $exclude as $id ) {
6949              $children = get_page_children( $id, $pages );
6950              foreach ( $children as $child ) {
6951                  $exclude[] = $child->ID;
6952              }
6953          }
6954  
6955          $num_pages = count( $pages );
6956          for ( $i = 0; $i < $num_pages; $i++ ) {
6957              if ( in_array( $pages[ $i ]->ID, $exclude, true ) ) {
6958                  unset( $pages[ $i ] );
6959              }
6960          }
6961      }
6962  
6963      /**
6964       * Filters the retrieved list of pages.
6965       *
6966       * @since 2.1.0
6967       *
6968       * @param WP_Post[] $pages       Array of page objects.
6969       * @param array     $parsed_args Array of get_pages() arguments.
6970       */
6971      return apply_filters( 'get_pages', $pages, $parsed_args );
6972  }
6973  
6974  //
6975  // Attachment functions.
6976  //
6977  
6978  /**
6979   * Determines whether an attachment URI is local and really an attachment.
6980   *
6981   * For more information on this and similar theme functions, check out
6982   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
6983   * Conditional Tags} article in the Theme Developer Handbook.
6984   *
6985   * @since 2.0.0
6986   *
6987   * @param string $url URL to check
6988   * @return bool True on success, false on failure.
6989   */
6990  function is_local_attachment( $url ) {
6991      if ( ! str_contains( $url, home_url() ) ) {
6992          return false;
6993      }
6994      if ( str_contains( $url, home_url( '/?attachment_id=' ) ) ) {
6995          return true;
6996      }
6997  
6998      $id = url_to_postid( $url );
6999      if ( $id ) {
7000          $post = get_post( $id );
7001          if ( 'attachment' === $post->post_type ) {
7002              return true;
7003          }
7004      }
7005      return false;
7006  }
7007  
7008  /**
7009   * Inserts an attachment.
7010   *
7011   * If you set the 'ID' in the $args parameter, it will mean that you are
7012   * updating and attempt to update the attachment. You can also set the
7013   * attachment name or title by setting the key 'post_name' or 'post_title'.
7014   *
7015   * You can set the dates for the attachment manually by setting the 'post_date'
7016   * and 'post_date_gmt' keys' values.
7017   *
7018   * By default, the comments will use the default settings for whether the
7019   * comments are allowed. You can close them manually or keep them open by
7020   * setting the value for the 'comment_status' key.
7021   *
7022   * @since 2.0.0
7023   * @since 4.7.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
7024   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
7025   *
7026   * @see wp_insert_post()
7027   *
7028   * @param string|array $args             Arguments for inserting an attachment.
7029   * @param string|false $file             Optional. Filename. Default false.
7030   * @param int          $parent_post_id   Optional. Parent post ID or 0 for no parent. Default 0.
7031   * @param bool         $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
7032   * @param bool         $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
7033   * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
7034   *
7035   * @phpstan-return (
7036   *     $wp_error is false ? int : int|WP_Error
7037   * )
7038   */
7039  function wp_insert_attachment( $args, $file = false, $parent_post_id = 0, $wp_error = false, $fire_after_hooks = true ) {
7040      $defaults = array(
7041          'file'        => $file,
7042          'post_parent' => 0,
7043      );
7044  
7045      $data = wp_parse_args( $args, $defaults );
7046  
7047      if ( ! empty( $parent_post_id ) ) {
7048          $data['post_parent'] = $parent_post_id;
7049      }
7050  
7051      $data['post_type'] = 'attachment';
7052  
7053      return wp_insert_post( $data, $wp_error, $fire_after_hooks );
7054  }
7055  
7056  /**
7057   * Trashes or deletes an attachment.
7058   *
7059   * When an attachment is permanently deleted, the file will also be removed.
7060   * Deletion removes all post meta fields, taxonomy, comments, etc. associated
7061   * with the attachment (except the main post).
7062   *
7063   * The attachment is moved to the Trash instead of permanently deleted unless Trash
7064   * for media is disabled, item is already in the Trash, or $force_delete is true.
7065   *
7066   * @since 2.0.0
7067   *
7068   * @global wpdb $wpdb WordPress database abstraction object.
7069   *
7070   * @param int  $post_id      Attachment ID.
7071   * @param bool $force_delete Optional. Whether to bypass Trash and force deletion.
7072   *                           Default false.
7073   * @return WP_Post|false|null Post data on success, false or null on failure.
7074   */
7075  function wp_delete_attachment( $post_id, $force_delete = false ) {
7076      global $wpdb;
7077  
7078      $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) );
7079  
7080      if ( ! $post ) {
7081          return $post;
7082      }
7083  
7084      $post = get_post( $post );
7085  
7086      if ( 'attachment' !== $post->post_type ) {
7087          return false;
7088      }
7089  
7090      if ( ! $force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' !== $post->post_status ) {
7091          return wp_trash_post( $post_id );
7092      }
7093  
7094      /**
7095       * Filters whether an attachment deletion should take place.
7096       *
7097       * @since 5.5.0
7098       *
7099       * @param WP_Post|false|null $delete       Whether to go forward with deletion.
7100       * @param WP_Post            $post         Post object.
7101       * @param bool               $force_delete Whether to bypass the Trash.
7102       */
7103      $check = apply_filters( 'pre_delete_attachment', null, $post, $force_delete );
7104      if ( null !== $check ) {
7105          return $check;
7106      }
7107  
7108      delete_post_meta( $post_id, '_wp_trash_meta_status' );
7109      delete_post_meta( $post_id, '_wp_trash_meta_time' );
7110  
7111      $meta         = wp_get_attachment_metadata( $post_id );
7112      $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
7113      $file         = get_attached_file( $post_id );
7114  
7115      if ( is_multisite() && is_string( $file ) && ! empty( $file ) ) {
7116          clean_dirsize_cache( $file );
7117      }
7118  
7119      /**
7120       * Fires before an attachment is deleted, at the start of wp_delete_attachment().
7121       *
7122       * @since 2.0.0
7123       * @since 5.5.0 Added the `$post` parameter.
7124       *
7125       * @param int     $post_id Attachment ID.
7126       * @param WP_Post $post    Post object.
7127       */
7128      do_action( 'delete_attachment', $post_id, $post );
7129  
7130      wp_delete_object_term_relationships( $post_id, array( 'category', 'post_tag' ) );
7131      wp_delete_object_term_relationships( $post_id, get_object_taxonomies( $post->post_type ) );
7132  
7133      // Delete all for any posts.
7134      delete_metadata( 'post', 0, '_thumbnail_id', $post_id, true );
7135  
7136      wp_defer_comment_counting( true );
7137  
7138      $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 ) );
7139      foreach ( $comment_ids as $comment_id ) {
7140          wp_delete_comment( $comment_id, true );
7141      }
7142  
7143      wp_defer_comment_counting( false );
7144  
7145      $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ) );
7146      foreach ( $post_meta_ids as $mid ) {
7147          delete_metadata_by_mid( 'post', $mid );
7148      }
7149  
7150      /** This action is documented in wp-includes/post.php */
7151      do_action( 'delete_post', $post_id, $post );
7152      $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
7153      if ( ! $result ) {
7154          return false;
7155      }
7156      /** This action is documented in wp-includes/post.php */
7157      do_action( 'deleted_post', $post_id, $post );
7158  
7159      wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file );
7160  
7161      clean_post_cache( $post );
7162  
7163      return $post;
7164  }
7165  
7166  /**
7167   * Deletes all files that belong to the given attachment.
7168   *
7169   * @since 4.9.7
7170   *
7171   * @global wpdb $wpdb WordPress database abstraction object.
7172   *
7173   * @param int    $post_id      Attachment ID.
7174   * @param array  $meta         The attachment's meta data.
7175   * @param array  $backup_sizes The meta data for the attachment's backup images.
7176   * @param string $file         Absolute path to the attachment's file.
7177   * @return bool True on success, false on failure.
7178   */
7179  function wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file ) {
7180      global $wpdb;
7181  
7182      $uploadpath = wp_get_upload_dir();
7183      $deleted    = true;
7184  
7185      if ( ! empty( $meta['thumb'] ) ) {
7186          // Don't delete the thumb if another attachment uses it.
7187          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 ) ) ) {
7188              $thumbfile = str_replace( wp_basename( $file ), $meta['thumb'], $file );
7189  
7190              if ( ! empty( $thumbfile ) ) {
7191                  $thumbfile = path_join( $uploadpath['basedir'], $thumbfile );
7192                  $thumbdir  = path_join( $uploadpath['basedir'], dirname( $file ) );
7193  
7194                  if ( ! wp_delete_file_from_directory( $thumbfile, $thumbdir ) ) {
7195                      $deleted = false;
7196                  }
7197              }
7198          }
7199      }
7200  
7201      // Remove intermediate and backup images if there are any.
7202      if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
7203          $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7204  
7205          foreach ( $meta['sizes'] as $size => $sizeinfo ) {
7206              $intermediate_file = str_replace( wp_basename( $file ), $sizeinfo['file'], $file );
7207  
7208              if ( ! empty( $intermediate_file ) ) {
7209                  $intermediate_file = path_join( $uploadpath['basedir'], $intermediate_file );
7210  
7211                  if ( ! wp_delete_file_from_directory( $intermediate_file, $intermediate_dir ) ) {
7212                      $deleted = false;
7213                  }
7214              }
7215          }
7216      }
7217  
7218      if ( ! empty( $meta['original_image'] ) ) {
7219          if ( empty( $intermediate_dir ) ) {
7220              $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7221          }
7222  
7223          $original_image = str_replace( wp_basename( $file ), $meta['original_image'], $file );
7224  
7225          if ( ! empty( $original_image ) ) {
7226              $original_image = path_join( $uploadpath['basedir'], $original_image );
7227  
7228              if ( ! wp_delete_file_from_directory( $original_image, $intermediate_dir ) ) {
7229                  $deleted = false;
7230              }
7231          }
7232      }
7233  
7234      /*
7235       * Delete the source-format companion file. The client-side media flow can
7236       * sideload a source-format original (such as a HEIC file) alongside a
7237       * web-viewable derivative, recording its filename under the 'source_image'
7238       * key. This is kept separate from 'original_image', which continues to
7239       * point at the derivative.
7240       */
7241      if ( ! empty( $meta['source_image'] ) && is_string( $meta['source_image'] ) ) {
7242          if ( empty( $intermediate_dir ) ) {
7243              $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7244          }
7245  
7246          $source_image = str_replace( wp_basename( $file ), $meta['source_image'], $file );
7247  
7248          if ( ! empty( $source_image ) ) {
7249              $source_image = path_join( $uploadpath['basedir'], $source_image );
7250  
7251              if ( ! wp_delete_file_from_directory( $source_image, $intermediate_dir ) ) {
7252                  $deleted = false;
7253              }
7254          }
7255      }
7256  
7257      /*
7258       * Delete the animated-GIF video companions. When the client-side media flow
7259       * converts an opaque animated GIF to a web-safe video, the converted MP4/WebM
7260       * and a static first-frame JPEG poster are sideloaded alongside the GIF and
7261       * recorded under the 'animated_video' and 'animated_video_poster' keys. These
7262       * are kept separate from 'original_image', which continues to point at the GIF.
7263       */
7264      foreach ( array( 'animated_video', 'animated_video_poster' ) as $companion_key ) {
7265          if ( empty( $meta[ $companion_key ] ) || ! is_string( $meta[ $companion_key ] ) ) {
7266              continue;
7267          }
7268  
7269          if ( empty( $intermediate_dir ) ) {
7270              $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
7271          }
7272  
7273          $companion_file = str_replace( wp_basename( $file ), $meta[ $companion_key ], $file );
7274  
7275          if ( ! empty( $companion_file ) ) {
7276              $companion_file = path_join( $uploadpath['basedir'], $companion_file );
7277  
7278              if ( ! wp_delete_file_from_directory( $companion_file, $intermediate_dir ) ) {
7279                  $deleted = false;
7280              }
7281          }
7282      }
7283  
7284      if ( is_array( $backup_sizes ) ) {
7285          $del_dir = path_join( $uploadpath['basedir'], dirname( $meta['file'] ) );
7286  
7287          foreach ( $backup_sizes as $size ) {
7288              $del_file = path_join( dirname( $meta['file'] ), $size['file'] );
7289  
7290              if ( ! empty( $del_file ) ) {
7291                  $del_file = path_join( $uploadpath['basedir'], $del_file );
7292  
7293                  if ( ! wp_delete_file_from_directory( $del_file, $del_dir ) ) {
7294                      $deleted = false;
7295                  }
7296              }
7297          }
7298      }
7299  
7300      if ( ! wp_delete_file_from_directory( $file, $uploadpath['basedir'] ) ) {
7301          $deleted = false;
7302      }
7303  
7304      return $deleted;
7305  }
7306  
7307  /**
7308   * Retrieves attachment metadata for attachment ID.
7309   *
7310   * @since 2.1.0
7311   * @since 6.0.0 The `$filesize` value was added to the returned array.
7312   * @since 7.1.0 `false` is now returned if the metadata is not an array, and when the result is
7313   *              filtered the `sizes` key is always an array when present.
7314   *
7315   * @param int  $attachment_id Attachment post ID. Defaults to global $post.
7316   * @param bool $unfiltered    Optional. If true, filters are not run. Default false.
7317   * @return array|false {
7318   *     Attachment metadata. False on failure.
7319   *
7320   *     @type int    $width      The width of the attachment.
7321   *     @type int    $height     The height of the attachment.
7322   *     @type string $file       The file path relative to `wp-content/uploads`.
7323   *     @type array  $sizes      Keys are size slugs, each value is an array containing
7324   *                              'file', 'width', 'height', and 'mime-type'.
7325   *     @type array  $image_meta Image metadata.
7326   *     @type int    $filesize   File size of the attachment.
7327   * }
7328   *
7329   * @phpstan-return array{
7330   *                     width?: int<1, max>,
7331   *                     height?: int<1, max>,
7332   *                     file?: non-empty-string,
7333   *                     filesize?: int<0, max>,
7334   *                     original_image?: non-empty-string,
7335   *                     source_image?: non-empty-string,
7336   *                     sizes?: array<non-empty-string, array{
7337   *                                                         file: non-empty-string,
7338   *                                                         width: int<1, max>,
7339   *                                                         height: int<1, max>,
7340   *                                                         'mime-type': non-empty-string,
7341   *                                                         filesize?: int<0, max>,
7342   *                                                         ...
7343   *                                                     }>,
7344   *                     image_meta?: array{
7345   *                                      aperture: numeric-string|int,
7346   *                                      credit: string,
7347   *                                      camera: string,
7348   *                                      caption: string,
7349   *                                      created_timestamp: numeric-string|int,
7350   *                                      copyright: string,
7351   *                                      focal_length: numeric-string|int,
7352   *                                      iso: numeric-string|int,
7353   *                                      shutter_speed: numeric-string|int,
7354   *                                      title: string,
7355   *                                      orientation: numeric-string|int,
7356   *                                      keywords: list<string>,
7357   *                                      alt: string,
7358   *                                  },
7359   *                     ...
7360   *                 }|false
7361   */
7362  function wp_get_attachment_metadata( $attachment_id = 0, $unfiltered = false ) {
7363      $attachment_id = (int) $attachment_id;
7364  
7365      if ( ! $attachment_id ) {
7366          $post = get_post();
7367  
7368          if ( ! $post ) {
7369              return false;
7370          }
7371  
7372          $attachment_id = $post->ID;
7373      }
7374  
7375      $data = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
7376  
7377      if ( ! is_array( $data ) || ! $data ) {
7378          return false;
7379      }
7380  
7381      if ( $unfiltered ) {
7382          return $data;
7383      }
7384  
7385      /**
7386       * Filters the attachment meta data.
7387       *
7388       * @since 2.1.0
7389       *
7390       * @param array $data          Array of meta data for the given attachment.
7391       * @param int   $attachment_id Attachment post ID.
7392       */
7393      $data = apply_filters( 'wp_get_attachment_metadata', $data, $attachment_id );
7394  
7395      if ( ! is_array( $data ) ) {
7396          return false;
7397      }
7398  
7399      if ( array_key_exists( 'sizes', $data ) && ! is_array( $data['sizes'] ) ) {
7400          $data['sizes'] = array();
7401      }
7402  
7403      return $data;
7404  }
7405  
7406  /**
7407   * Updates metadata for an attachment.
7408   *
7409   * @since 2.1.0
7410   *
7411   * @param int   $attachment_id Attachment post ID.
7412   * @param array $data          Attachment meta data.
7413   * @return int|bool Whether the metadata was successfully updated.
7414   *                  True on success, the Meta ID if the key didn't exist.
7415   *                  False if $post is invalid, on failure, or if $data is the same as the existing metadata.
7416   */
7417  function wp_update_attachment_metadata( $attachment_id, $data ) {
7418      $attachment_id = (int) $attachment_id;
7419  
7420      $post = get_post( $attachment_id );
7421  
7422      if ( ! $post ) {
7423          return false;
7424      }
7425  
7426      /**
7427       * Filters the updated attachment meta data.
7428       *
7429       * @since 2.1.0
7430       *
7431       * @param array $data          Array of updated attachment meta data.
7432       * @param int   $attachment_id Attachment post ID.
7433       */
7434      $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
7435      if ( $data ) {
7436          return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
7437      } else {
7438          return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
7439      }
7440  }
7441  
7442  /**
7443   * Retrieves the URL for an attachment.
7444   *
7445   * @since 2.1.0
7446   *
7447   * @global string $pagenow The filename of the current screen.
7448   *
7449   * @param int $attachment_id Optional. Attachment post ID. Defaults to global $post.
7450   * @return string|false Attachment URL, otherwise false.
7451   */
7452  function wp_get_attachment_url( $attachment_id = 0 ) {
7453      global $pagenow;
7454  
7455      $attachment_id = (int) $attachment_id;
7456  
7457      $post = get_post( $attachment_id );
7458  
7459      if ( ! $post ) {
7460          return false;
7461      }
7462  
7463      if ( 'attachment' !== $post->post_type ) {
7464          return false;
7465      }
7466  
7467      $url = '';
7468      // Get attached file.
7469      $file = get_post_meta( $post->ID, '_wp_attached_file', true );
7470      if ( $file ) {
7471          // Get upload directory.
7472          $uploads = wp_get_upload_dir();
7473          if ( $uploads && false === $uploads['error'] ) {
7474              // Check that the upload base exists in the file location.
7475              if ( str_starts_with( $file, $uploads['basedir'] ) ) {
7476                  // Replace file location with url location.
7477                  $url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file );
7478              } elseif ( str_contains( $file, 'wp-content/uploads' ) ) {
7479                  // Get the directory name relative to the basedir (back compat for pre-2.7 uploads).
7480                  $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . wp_basename( $file );
7481              } else {
7482                  // It's a newly-uploaded file, therefore $file is relative to the basedir.
7483                  $url = $uploads['baseurl'] . "/$file";
7484              }
7485          }
7486      }
7487  
7488      /*
7489       * If any of the above options failed, Fallback on the GUID as used pre-2.7,
7490       * not recommended to rely upon this.
7491       */
7492      if ( ! $url ) {
7493          $url = get_the_guid( $post->ID );
7494      }
7495  
7496      // On SSL front end, URLs should be HTTPS.
7497      if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $pagenow ) {
7498          $url = set_url_scheme( $url );
7499      }
7500  
7501      /**
7502       * Filters the attachment URL.
7503       *
7504       * @since 2.1.0
7505       *
7506       * @param string $url           URL for the given attachment.
7507       * @param int    $attachment_id Attachment post ID.
7508       */
7509      $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
7510  
7511      if ( ! $url ) {
7512          return false;
7513      }
7514  
7515      return $url;
7516  }
7517  
7518  /**
7519   * Retrieves the caption for an attachment.
7520   *
7521   * @since 4.6.0
7522   *
7523   * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
7524   * @return string|false Attachment caption on success, false on failure.
7525   */
7526  function wp_get_attachment_caption( $post_id = 0 ) {
7527      $post_id = (int) $post_id;
7528      $post    = get_post( $post_id );
7529  
7530      if ( ! $post ) {
7531          return false;
7532      }
7533  
7534      if ( 'attachment' !== $post->post_type ) {
7535          return false;
7536      }
7537  
7538      $caption = $post->post_excerpt;
7539  
7540      /**
7541       * Filters the attachment caption.
7542       *
7543       * @since 4.6.0
7544       *
7545       * @param string $caption Caption for the given attachment.
7546       * @param int    $post_id Attachment ID.
7547       */
7548      return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
7549  }
7550  
7551  /**
7552   * Retrieves URL for an attachment thumbnail.
7553   *
7554   * @since 2.1.0
7555   * @since 6.1.0 Changed to use wp_get_attachment_image_url().
7556   *
7557   * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
7558   * @return string|false Thumbnail URL on success, false on failure.
7559   */
7560  function wp_get_attachment_thumb_url( $post_id = 0 ) {
7561      $post_id = (int) $post_id;
7562  
7563      /*
7564       * This uses image_downsize() which also looks for the (very) old format $image_meta['thumb']
7565       * when the newer format $image_meta['sizes']['thumbnail'] doesn't exist.
7566       */
7567      $thumbnail_url = wp_get_attachment_image_url( $post_id, 'thumbnail' );
7568  
7569      if ( empty( $thumbnail_url ) ) {
7570          return false;
7571      }
7572  
7573      /**
7574       * Filters the attachment thumbnail URL.
7575       *
7576       * @since 2.1.0
7577       *
7578       * @param string $thumbnail_url URL for the attachment thumbnail.
7579       * @param int    $post_id       Attachment ID.
7580       */
7581      return apply_filters( 'wp_get_attachment_thumb_url', $thumbnail_url, $post_id );
7582  }
7583  
7584  /**
7585   * Verifies an attachment is of a given type.
7586   *
7587   * @since 4.2.0
7588   *
7589   * @param string      $type Attachment type. Accepts `image`, `audio`, `video`, or a file extension.
7590   * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
7591   * @return bool True if an accepted type or a matching file extension, false otherwise.
7592   */
7593  function wp_attachment_is( $type, $post = null ) {
7594      $post = get_post( $post );
7595  
7596      if ( ! $post ) {
7597          return false;
7598      }
7599  
7600      $file = get_attached_file( $post->ID );
7601  
7602      if ( ! $file ) {
7603          return false;
7604      }
7605  
7606      if ( str_starts_with( $post->post_mime_type, $type . '/' ) ) {
7607          return true;
7608      }
7609  
7610      $check = wp_check_filetype( $file );
7611  
7612      if ( empty( $check['ext'] ) ) {
7613          return false;
7614      }
7615  
7616      $ext = $check['ext'];
7617  
7618      if ( 'import' !== $post->post_mime_type ) {
7619          return $type === $ext;
7620      }
7621  
7622      switch ( $type ) {
7623          case 'image':
7624              $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'webp', 'avif', 'heic' );
7625              return in_array( $ext, $image_exts, true );
7626  
7627          case 'audio':
7628              return in_array( $ext, wp_get_audio_extensions(), true );
7629  
7630          case 'video':
7631              return in_array( $ext, wp_get_video_extensions(), true );
7632  
7633          default:
7634              return $type === $ext;
7635      }
7636  }
7637  
7638  /**
7639   * Determines whether an attachment is an image.
7640   *
7641   * For more information on this and similar theme functions, check out
7642   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
7643   * Conditional Tags} article in the Theme Developer Handbook.
7644   *
7645   * @since 2.1.0
7646   * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
7647   *              allowed WP_Post object to be passed.
7648   *
7649   * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
7650   * @return bool Whether the attachment is an image.
7651   */
7652  function wp_attachment_is_image( $post = null ) {
7653      return wp_attachment_is( 'image', $post );
7654  }
7655  
7656  /**
7657   * Retrieves the icon for a MIME type or attachment.
7658   *
7659   * @since 2.1.0
7660   * @since 6.5.0 Added the `$preferred_ext` parameter.
7661   *
7662   * @param string|int $mime          MIME type or attachment ID.
7663   * @param string     $preferred_ext File format to prefer in return. Default '.png'.
7664   * @return string|false Icon URL, or false if no icon was found.
7665   */
7666  function wp_mime_type_icon( $mime = 0, $preferred_ext = '.png' ) {
7667      $icon = false;
7668      if ( ! is_numeric( $mime ) ) {
7669          $cached_icon = wp_cache_get( "mime_type_icon_$mime" );
7670          if ( is_string( $cached_icon ) ) {
7671              $icon = $cached_icon;
7672          }
7673      }
7674  
7675      // Check if preferred file format variable is present and is a validly formatted file extension.
7676      if ( ! empty( $preferred_ext ) && is_string( $preferred_ext ) && ! str_starts_with( $preferred_ext, '.' ) ) {
7677          $preferred_ext = '.' . strtolower( $preferred_ext );
7678      }
7679  
7680      $post_id = 0;
7681      if ( empty( $icon ) ) {
7682          $post_mimes = array();
7683          if ( is_numeric( $mime ) ) {
7684              $mime = (int) $mime;
7685              $post = get_post( $mime );
7686              if ( $post ) {
7687                  $post_id = (int) $post->ID;
7688                  $file    = get_attached_file( $post_id );
7689                  $ext     = preg_replace( '/^.+?\.([^.]+)$/', '$1', $file );
7690                  if ( ! empty( $ext ) ) {
7691                      $post_mimes[] = $ext;
7692                      $ext_type     = wp_ext2type( $ext );
7693                      if ( $ext_type ) {
7694                          $post_mimes[] = $ext_type;
7695                      }
7696                  }
7697                  $mime = $post->post_mime_type;
7698              } else {
7699                  $mime = 0;
7700              }
7701          } else {
7702              $post_mimes[] = $mime;
7703          }
7704  
7705          $icon_files = wp_cache_get( 'icon_files' );
7706  
7707          if ( ! is_array( $icon_files ) ) {
7708              /**
7709               * Filters the icon directory path.
7710               *
7711               * @since 2.0.0
7712               *
7713               * @param string $path Icon directory absolute path.
7714               */
7715              $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
7716  
7717              /**
7718               * Filters the icon directory URI.
7719               *
7720               * @since 2.0.0
7721               *
7722               * @param string $uri Icon directory URI.
7723               */
7724              $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
7725  
7726              /**
7727               * Filters the array of icon directory URIs.
7728               *
7729               * @since 2.5.0
7730               *
7731               * @param string[] $uris Array of icon directory URIs keyed by directory absolute path.
7732               */
7733              $dirs       = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
7734              $icon_files = array();
7735              $all_icons  = array();
7736              while ( $dirs ) {
7737                  $keys = array_keys( $dirs );
7738                  $dir  = array_shift( $keys );
7739                  $uri  = array_shift( $dirs );
7740                  $dh   = opendir( $dir );
7741                  if ( $dh ) {
7742                      while ( false !== $file = readdir( $dh ) ) {
7743                          $file = wp_basename( $file );
7744                          if ( str_starts_with( $file, '.' ) ) {
7745                              continue;
7746                          }
7747  
7748                          $ext = strtolower( substr( $file, -4 ) );
7749                          if ( ! in_array( $ext, array( '.svg', '.png', '.gif', '.jpg' ), true ) ) {
7750                              if ( is_dir( "$dir/$file" ) ) {
7751                                  $dirs[ "$dir/$file" ] = "$uri/$file";
7752                              }
7753                              continue;
7754                          }
7755                          $all_icons[ "$dir/$file" ] = "$uri/$file";
7756                          if ( $ext === $preferred_ext ) {
7757                              $icon_files[ "$dir/$file" ] = "$uri/$file";
7758                          }
7759                      }
7760                      closedir( $dh );
7761                  }
7762              }
7763              // If directory only contained icons of a non-preferred format, return those.
7764              if ( empty( $icon_files ) ) {
7765                  $icon_files = $all_icons;
7766              }
7767              wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
7768          }
7769  
7770          $types = array();
7771          // Icon wp_basename - extension = MIME wildcard.
7772          foreach ( $icon_files as $file => $uri ) {
7773              $types[ preg_replace( '/^([^.]*).*$/', '$1', wp_basename( $file ) ) ] =& $icon_files[ $file ];
7774          }
7775  
7776          if ( ! empty( $mime ) ) {
7777              $post_mimes[] = substr( $mime, 0, strpos( $mime, '/' ) );
7778              $post_mimes[] = substr( $mime, strpos( $mime, '/' ) + 1 );
7779              $post_mimes[] = str_replace( '/', '_', $mime );
7780          }
7781  
7782          $matches            = wp_match_mime_types( array_keys( $types ), $post_mimes );
7783          $matches['default'] = array( 'default' );
7784  
7785          foreach ( $matches as $match => $wilds ) {
7786              foreach ( $wilds as $wild ) {
7787                  $type_icon = $types[ $wild ] ?? null;
7788                  if ( ! is_string( $type_icon ) ) {
7789                      continue;
7790                  }
7791  
7792                  $icon = $type_icon;
7793                  if ( ! is_numeric( $mime ) ) {
7794                      wp_cache_add( "mime_type_icon_$mime", $icon );
7795                  }
7796                  break 2;
7797              }
7798          }
7799      }
7800  
7801      /**
7802       * Filters the mime type icon.
7803       *
7804       * @since 2.1.0
7805       *
7806       * @param string|false $icon    URL of the mime type icon, or false if no icon was found.
7807       * @param string|int   $mime    Mime type, or 0 if no post was found for the passed ID.
7808       * @param int          $post_id Attachment ID. Will equal 0 if the function passed
7809       *                              the mime type or no post was found for the passed ID.
7810       */
7811      return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
7812  }
7813  
7814  /**
7815   * Checks for changed slugs for published post objects and save the old slug.
7816   *
7817   * The function is used when a post object of any type is updated,
7818   * by comparing the current and previous post objects.
7819   *
7820   * If the slug was changed and not already part of the old slugs then it will be
7821   * added to the post meta field ('_wp_old_slug') for storing old slugs for that
7822   * post.
7823   *
7824   * The most logically usage of this function is redirecting changed post objects, so
7825   * that those that linked to an changed post will be redirected to the new post.
7826   *
7827   * @since 2.1.0
7828   *
7829   * @param int     $post_id     Post ID.
7830   * @param WP_Post $post        The post object.
7831   * @param WP_Post $post_before The previous post object.
7832   */
7833  function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
7834      // Don't bother if it hasn't changed.
7835      if ( $post->post_name === $post_before->post_name ) {
7836          return;
7837      }
7838  
7839      // We're only concerned with published, non-hierarchical objects.
7840      if ( ! ( 'publish' === $post->post_status || ( 'attachment' === $post->post_type && 'inherit' === $post->post_status ) )
7841          || is_post_type_hierarchical( $post->post_type )
7842      ) {
7843          return;
7844      }
7845  
7846      $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
7847  
7848      // If we haven't added this old slug before, add it now.
7849      if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs, true ) ) {
7850          add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
7851      }
7852  
7853      // If the new slug was used previously, delete it from the list.
7854      if ( in_array( $post->post_name, $old_slugs, true ) ) {
7855          delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
7856      }
7857  }
7858  
7859  /**
7860   * Checks for changed dates for published post objects and save the old date.
7861   *
7862   * The function is used when a post object of any type is updated,
7863   * by comparing the current and previous post objects.
7864   *
7865   * If the date was changed and not already part of the old dates then it will be
7866   * added to the post meta field ('_wp_old_date') for storing old dates for that
7867   * post.
7868   *
7869   * The most logically usage of this function is redirecting changed post objects, so
7870   * that those that linked to an changed post will be redirected to the new post.
7871   *
7872   * @since 4.9.3
7873   *
7874   * @param int     $post_id     Post ID.
7875   * @param WP_Post $post        The post object.
7876   * @param WP_Post $post_before The previous post object.
7877   */
7878  function wp_check_for_changed_dates( $post_id, $post, $post_before ) {
7879      $previous_date = gmdate( 'Y-m-d', strtotime( $post_before->post_date ) );
7880      $new_date      = gmdate( 'Y-m-d', strtotime( $post->post_date ) );
7881  
7882      // Don't bother if it hasn't changed.
7883      if ( $new_date === $previous_date ) {
7884          return;
7885      }
7886  
7887      // We're only concerned with published, non-hierarchical objects.
7888      if ( ! ( 'publish' === $post->post_status || ( 'attachment' === $post->post_type && 'inherit' === $post->post_status ) )
7889          || is_post_type_hierarchical( $post->post_type )
7890      ) {
7891          return;
7892      }
7893  
7894      $old_dates = (array) get_post_meta( $post_id, '_wp_old_date' );
7895  
7896      // If we haven't added this old date before, add it now.
7897      if ( ! empty( $previous_date ) && ! in_array( $previous_date, $old_dates, true ) ) {
7898          add_post_meta( $post_id, '_wp_old_date', $previous_date );
7899      }
7900  
7901      // If the new slug was used previously, delete it from the list.
7902      if ( in_array( $new_date, $old_dates, true ) ) {
7903          delete_post_meta( $post_id, '_wp_old_date', $new_date );
7904      }
7905  }
7906  
7907  /**
7908   * Retrieves the private post SQL based on capability.
7909   *
7910   * This function provides a standardized way to appropriately select on the
7911   * post_status of a post type. The function will return a piece of SQL code
7912   * that can be added to a WHERE clause; this SQL is constructed to allow all
7913   * published posts, and all private posts to which the user has access.
7914   *
7915   * @since 2.2.0
7916   * @since 4.3.0 Added the ability to pass an array to `$post_type`.
7917   *
7918   * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
7919   * @return string SQL code that can be added to a where clause.
7920   */
7921  function get_private_posts_cap_sql( $post_type ) {
7922      return get_posts_by_author_sql( $post_type, false );
7923  }
7924  
7925  /**
7926   * Retrieves the post SQL based on capability, author, and type.
7927   *
7928   * @since 3.0.0
7929   * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
7930   *
7931   * @see get_private_posts_cap_sql()
7932   * @global wpdb $wpdb WordPress database abstraction object.
7933   *
7934   * @param string|string[] $post_type   Single post type or an array of post types.
7935   * @param bool            $full        Optional. Returns a full WHERE statement instead of just
7936   *                                     an 'andalso' term. Default true.
7937   * @param int             $post_author Optional. Query posts having a single author ID. Default null.
7938   * @param bool            $public_only Optional. Only return public posts. Skips cap checks for
7939   *                                     $current_user.  Default false.
7940   * @return string SQL WHERE code that can be added to a query.
7941   */
7942  function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
7943      global $wpdb;
7944  
7945      if ( is_array( $post_type ) ) {
7946          $post_types = $post_type;
7947      } else {
7948          $post_types = array( $post_type );
7949      }
7950  
7951      $post_type_clauses = array();
7952      foreach ( $post_types as $post_type ) {
7953          $post_type_obj = get_post_type_object( $post_type );
7954  
7955          if ( ! $post_type_obj ) {
7956              continue;
7957          }
7958  
7959          /**
7960           * Filters the capability to read private posts for a custom post type
7961           * when generating SQL for getting posts by author.
7962           *
7963           * @since 2.2.0
7964           * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
7965           *
7966           * @param string $cap Capability.
7967           */
7968          $cap = apply_filters_deprecated( 'pub_priv_sql_capability', array( '' ), '3.2.0' );
7969  
7970          if ( ! $cap ) {
7971              $cap = current_user_can( $post_type_obj->cap->read_private_posts );
7972          }
7973  
7974          // Only need to check the cap if $public_only is false.
7975          $post_status_sql = "post_status = 'publish'";
7976  
7977          if ( false === $public_only ) {
7978              if ( $cap ) {
7979                  // Does the user have the capability to view private posts? Guess so.
7980                  $post_status_sql .= " OR post_status = 'private'";
7981              } elseif ( is_user_logged_in() ) {
7982                  // Users can view their own private posts.
7983                  $id = get_current_user_id();
7984                  if ( null === $post_author || ! $full ) {
7985                      $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
7986                  } elseif ( $id === (int) $post_author ) {
7987                      $post_status_sql .= " OR post_status = 'private'";
7988                  } // Else none.
7989              } // Else none.
7990          }
7991  
7992          $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
7993      }
7994  
7995      if ( empty( $post_type_clauses ) ) {
7996          return $full ? 'WHERE 1 = 0' : '1 = 0';
7997      }
7998  
7999      $sql = '( ' . implode( ' OR ', $post_type_clauses ) . ' )';
8000  
8001      if ( null !== $post_author ) {
8002          $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
8003      }
8004  
8005      if ( $full ) {
8006          $sql = 'WHERE ' . $sql;
8007      }
8008  
8009      return $sql;
8010  }
8011  
8012  /**
8013   * Retrieves the most recent time that a post on the site was published.
8014   *
8015   * The server timezone is the default and is the difference between GMT and
8016   * server time. The 'blog' value is the date when the last post was posted.
8017   * The 'gmt' is when the last post was posted in GMT formatted date.
8018   *
8019   * @since 0.71
8020   * @since 4.4.0 The `$post_type` argument was added.
8021   *
8022   * @param string $timezone  Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
8023   *                          'server' uses the server's internal timezone.
8024   *                          'blog' uses the `post_date` field, which proxies to the timezone set for the site.
8025   *                          'gmt' uses the `post_date_gmt` field.
8026   *                          Default 'server'.
8027   * @param string $post_type Optional. The post type to check. Default 'any'.
8028   * @return string The date of the last post, or false on failure.
8029   */
8030  function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
8031      $lastpostdate = _get_last_post_time( $timezone, 'date', $post_type );
8032  
8033      /**
8034       * Filters the most recent time that a post on the site was published.
8035       *
8036       * @since 2.3.0
8037       * @since 5.5.0 Added the `$post_type` parameter.
8038       *
8039       * @param string|false $lastpostdate The most recent time that a post was published,
8040       *                                   in 'Y-m-d H:i:s' format. False on failure.
8041       * @param string       $timezone     Location to use for getting the post published date.
8042       *                                   See get_lastpostdate() for accepted `$timezone` values.
8043       * @param string       $post_type    The post type to check.
8044       */
8045      return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone, $post_type );
8046  }
8047  
8048  /**
8049   * Gets the most recent time that a post on the site was modified.
8050   *
8051   * The server timezone is the default and is the difference between GMT and
8052   * server time. The 'blog' value is just when the last post was modified.
8053   * The 'gmt' is when the last post was modified in GMT time.
8054   *
8055   * @since 1.2.0
8056   * @since 4.4.0 The `$post_type` argument was added.
8057   *
8058   * @param string $timezone  Optional. The timezone for the timestamp. See get_lastpostdate()
8059   *                          for information on accepted values.
8060   *                          Default 'server'.
8061   * @param string $post_type Optional. The post type to check. Default 'any'.
8062   * @return string The timestamp in 'Y-m-d H:i:s' format, or false on failure.
8063   */
8064  function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
8065      /**
8066       * Pre-filter the return value of get_lastpostmodified() before the query is run.
8067       *
8068       * @since 4.4.0
8069       *
8070       * @param string|false $lastpostmodified The most recent time that a post was modified,
8071       *                                       in 'Y-m-d H:i:s' format, or false. Returning anything
8072       *                                       other than false will short-circuit the function.
8073       * @param string       $timezone         Location to use for getting the post modified date.
8074       *                                       See get_lastpostdate() for accepted `$timezone` values.
8075       * @param string       $post_type        The post type to check.
8076       */
8077      $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
8078  
8079      if ( false !== $lastpostmodified ) {
8080          return $lastpostmodified;
8081      }
8082  
8083      $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
8084      $lastpostdate     = get_lastpostdate( $timezone, $post_type );
8085  
8086      if ( $lastpostdate > $lastpostmodified ) {
8087          $lastpostmodified = $lastpostdate;
8088      }
8089  
8090      /**
8091       * Filters the most recent time that a post on the site was modified.
8092       *
8093       * @since 2.3.0
8094       * @since 5.5.0 Added the `$post_type` parameter.
8095       *
8096       * @param string|false $lastpostmodified The most recent time that a post was modified,
8097       *                                       in 'Y-m-d H:i:s' format. False on failure.
8098       * @param string       $timezone         Location to use for getting the post modified date.
8099       *                                       See get_lastpostdate() for accepted `$timezone` values.
8100       * @param string       $post_type        The post type to check.
8101       */
8102      return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone, $post_type );
8103  }
8104  
8105  /**
8106   * Gets the timestamp of the last time any post was modified or published.
8107   *
8108   * @since 3.1.0
8109   * @since 4.4.0 The `$post_type` argument was added.
8110   * @access private
8111   *
8112   * @global wpdb $wpdb WordPress database abstraction object.
8113   *
8114   * @param string $timezone  The timezone for the timestamp. See get_lastpostdate().
8115   *                          for information on accepted values.
8116   * @param string $field     Post field to check. Accepts 'date' or 'modified'.
8117   * @param string $post_type Optional. The post type to check. Default 'any'.
8118   * @return string|false The timestamp in 'Y-m-d H:i:s' format, or false on failure.
8119   */
8120  function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
8121      global $wpdb;
8122  
8123      if ( ! in_array( $field, array( 'date', 'modified' ), true ) ) {
8124          return false;
8125      }
8126  
8127      $timezone = strtolower( $timezone );
8128  
8129      $key = "lastpost{$field}:$timezone";
8130      if ( 'any' !== $post_type ) {
8131          $key .= ':' . sanitize_key( $post_type );
8132      }
8133  
8134      $date = wp_cache_get( $key, 'timeinfo' );
8135      if ( false !== $date ) {
8136          return $date;
8137      }
8138  
8139      if ( 'any' === $post_type ) {
8140          $post_types = get_post_types( array( 'public' => true ) );
8141          array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
8142          $post_types = "'" . implode( "', '", $post_types ) . "'";
8143      } else {
8144          $post_types = "'" . sanitize_key( $post_type ) . "'";
8145      }
8146  
8147      switch ( $timezone ) {
8148          case 'gmt':
8149              $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" );
8150              break;
8151          case 'blog':
8152              $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" );
8153              break;
8154          case 'server':
8155              $add_seconds_server = gmdate( 'Z' );
8156              $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" );
8157              break;
8158      }
8159  
8160      if ( $date ) {
8161          wp_cache_set( $key, $date, 'timeinfo' );
8162  
8163          return $date;
8164      }
8165  
8166      return false;
8167  }
8168  
8169  /**
8170   * Updates posts in cache.
8171   *
8172   * @since 1.5.1
8173   *
8174   * @param WP_Post[] $posts Array of post objects (passed by reference).
8175   */
8176  function update_post_cache( &$posts ) {
8177      if ( ! $posts ) {
8178          return;
8179      }
8180  
8181      $data = array();
8182      foreach ( $posts as $post ) {
8183          if ( empty( $post->filter ) || 'raw' !== $post->filter ) {
8184              $post = sanitize_post( $post, 'raw' );
8185          }
8186          $data[ $post->ID ] = $post;
8187      }
8188      wp_cache_add_multiple( $data, 'posts' );
8189  }
8190  
8191  /**
8192   * Will clean the post in the cache.
8193   *
8194   * Cleaning means delete from the cache of the post. Will call to clean the term
8195   * object cache associated with the post ID.
8196   *
8197   * This function not run if $_wp_suspend_cache_invalidation is not empty. See
8198   * wp_suspend_cache_invalidation().
8199   *
8200   * @since 2.0.0
8201   *
8202   * @global bool $_wp_suspend_cache_invalidation
8203   *
8204   * @param int|WP_Post $post Post ID or post object to remove from the cache.
8205   */
8206  function clean_post_cache( $post ) {
8207      global $_wp_suspend_cache_invalidation;
8208  
8209      if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
8210          return;
8211      }
8212  
8213      $post = get_post( $post );
8214  
8215      if ( ! $post ) {
8216          return;
8217      }
8218  
8219      wp_cache_delete( $post->ID, 'posts' );
8220      wp_cache_delete( 'post_parent:' . (string) $post->ID, 'posts' );
8221      wp_cache_delete( $post->ID, 'post_meta' );
8222  
8223      clean_object_term_cache( $post->ID, $post->post_type );
8224  
8225      wp_cache_delete( 'wp_get_archives', 'general' );
8226  
8227      /**
8228       * Fires immediately after the given post's cache is cleaned.
8229       *
8230       * @since 2.5.0
8231       *
8232       * @param int     $post_id Post ID.
8233       * @param WP_Post $post    Post object.
8234       */
8235      do_action( 'clean_post_cache', $post->ID, $post );
8236  
8237      if ( 'page' === $post->post_type ) {
8238          wp_cache_delete( 'all_page_ids', 'posts' );
8239  
8240          /**
8241           * Fires immediately after the given page's cache is cleaned.
8242           *
8243           * @since 2.5.0
8244           *
8245           * @param int $post_id Post ID.
8246           */
8247          do_action( 'clean_page_cache', $post->ID );
8248      }
8249  
8250      wp_cache_set_posts_last_changed();
8251  }
8252  
8253  /**
8254   * Updates post, term, and metadata caches for a list of post objects.
8255   *
8256   * @since 1.5.0
8257   *
8258   * @param WP_Post[]       $posts             Array of post objects (passed by reference).
8259   * @param string|string[] $post_type         Optional. Single post type, 'any', or an array of post types.
8260   *                                           Default 'post'.
8261   * @param bool            $update_term_cache Optional. Whether to update the term cache. Default true.
8262   * @param bool            $update_meta_cache Optional. Whether to update the meta cache. Default true.
8263   */
8264  function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
8265      // No point in doing all this work if we didn't match any posts.
8266      if ( ! $posts ) {
8267          return;
8268      }
8269  
8270      update_post_cache( $posts );
8271  
8272      $post_ids = array();
8273      foreach ( $posts as $post ) {
8274          $post_ids[] = $post->ID;
8275      }
8276  
8277      if ( ! $post_type ) {
8278          $post_type = 'any';
8279      }
8280  
8281      if ( $update_term_cache ) {
8282          if ( is_array( $post_type ) ) {
8283              $ptypes = $post_type;
8284          } elseif ( 'any' === $post_type ) {
8285              $ptypes = array();
8286              // Just use the post_types in the supplied posts.
8287              foreach ( $posts as $post ) {
8288                  $ptypes[] = $post->post_type;
8289              }
8290              $ptypes = array_unique( $ptypes );
8291          } else {
8292              $ptypes = array( $post_type );
8293          }
8294  
8295          if ( ! empty( $ptypes ) ) {
8296              update_object_term_cache( $post_ids, $ptypes );
8297          }
8298      }
8299  
8300      if ( $update_meta_cache ) {
8301          update_postmeta_cache( $post_ids );
8302      }
8303  }
8304  
8305  /**
8306   * Updates post author user 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_author_caches( $posts ) {
8313      /*
8314       * cache_users() is a pluggable function so is not available prior
8315       * to the `plugins_loaded` hook firing. This is to ensure against
8316       * fatal errors when the function is not available.
8317       */
8318      if ( ! function_exists( 'cache_users' ) ) {
8319          return;
8320      }
8321  
8322      $author_ids = wp_list_pluck( $posts, 'post_author' );
8323      $author_ids = array_map( 'absint', $author_ids );
8324      $author_ids = array_unique( array_filter( $author_ids ) );
8325  
8326      cache_users( $author_ids );
8327  }
8328  
8329  /**
8330   * Updates parent post caches for a list of post objects.
8331   *
8332   * @since 6.1.0
8333   *
8334   * @param WP_Post[] $posts Array of post objects.
8335   */
8336  function update_post_parent_caches( $posts ) {
8337      $parent_ids = wp_list_pluck( $posts, 'post_parent' );
8338      $parent_ids = array_map( 'absint', $parent_ids );
8339      $parent_ids = array_unique( array_filter( $parent_ids ) );
8340  
8341      if ( ! empty( $parent_ids ) ) {
8342          _prime_post_caches( $parent_ids, false );
8343      }
8344  }
8345  
8346  /**
8347   * Updates metadata cache for a list of post IDs.
8348   *
8349   * Performs SQL query to retrieve the metadata for the post IDs and updates the
8350   * metadata cache for the posts. Therefore, the functions, which call this
8351   * function, do not need to perform SQL queries on their own.
8352   *
8353   * @since 2.1.0
8354   *
8355   * @param int[] $post_ids Array of post IDs.
8356   * @return array|false An array of metadata on success, false if there is nothing to update.
8357   */
8358  function update_postmeta_cache( $post_ids ) {
8359      return update_meta_cache( 'post', $post_ids );
8360  }
8361  
8362  /**
8363   * Will clean the attachment in the cache.
8364   *
8365   * Cleaning means delete from the cache. Optionally will clean the term
8366   * object cache associated with the attachment ID.
8367   *
8368   * This function will not run if $_wp_suspend_cache_invalidation is not empty.
8369   *
8370   * @since 3.0.0
8371   *
8372   * @global bool $_wp_suspend_cache_invalidation
8373   *
8374   * @param int  $id          The attachment ID in the cache to clean.
8375   * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
8376   */
8377  function clean_attachment_cache( $id, $clean_terms = false ) {
8378      global $_wp_suspend_cache_invalidation;
8379  
8380      if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
8381          return;
8382      }
8383  
8384      $id = (int) $id;
8385  
8386      wp_cache_delete( $id, 'posts' );
8387      wp_cache_delete( $id, 'post_meta' );
8388  
8389      if ( $clean_terms ) {
8390          clean_object_term_cache( $id, 'attachment' );
8391      }
8392  
8393      /**
8394       * Fires after the given attachment's cache is cleaned.
8395       *
8396       * @since 3.0.0
8397       *
8398       * @param int $id Attachment ID.
8399       */
8400      do_action( 'clean_attachment_cache', $id );
8401  }
8402  
8403  //
8404  // Hooks.
8405  //
8406  
8407  /**
8408   * Hook for managing future post transitions to published.
8409   *
8410   * @since 2.3.0
8411   * @access private
8412   *
8413   * @see wp_clear_scheduled_hook()
8414   * @global wpdb $wpdb WordPress database abstraction object.
8415   *
8416   * @param string  $new_status New post status.
8417   * @param string  $old_status Previous post status.
8418   * @param WP_Post $post       Post object.
8419   */
8420  function _transition_post_status( $new_status, $old_status, $post ) {
8421      global $wpdb;
8422  
8423      if ( 'publish' !== $old_status && 'publish' === $new_status ) {
8424          // Reset GUID if transitioning to publish and it is empty.
8425          if ( '' === get_the_guid( $post->ID ) ) {
8426              $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
8427          }
8428  
8429          /**
8430           * Fires when a post's status is transitioned from private to published.
8431           *
8432           * @since 1.5.0
8433           * @deprecated 2.3.0 Use {@see 'private_to_publish'} instead.
8434           *
8435           * @param int $post_id Post ID.
8436           */
8437          do_action_deprecated( 'private_to_published', array( $post->ID ), '2.3.0', 'private_to_publish' );
8438      }
8439  
8440      // If published posts changed clear the lastpostmodified cache.
8441      if ( 'publish' === $new_status || 'publish' === $old_status ) {
8442          foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
8443              wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
8444              wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
8445              wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
8446          }
8447      }
8448  
8449      if ( $new_status !== $old_status ) {
8450          wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
8451          wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
8452      }
8453  
8454      // Always clears the hook in case the post status bounced from future to draft.
8455      wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
8456  }
8457  
8458  /**
8459   * Hook used to schedule publication for a post marked for the future.
8460   *
8461   * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
8462   *
8463   * @since 2.3.0
8464   * @access private
8465   *
8466   * @param int     $deprecated Not used. Can be set to null. Never implemented. Not marked
8467   *                            as deprecated with _deprecated_argument() as it conflicts with
8468   *                            wp_transition_post_status() and the default filter for _future_post_hook().
8469   * @param WP_Post $post       Post object.
8470   */
8471  function _future_post_hook( $deprecated, $post ) {
8472      wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
8473      wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT' ), 'publish_future_post', array( $post->ID ) );
8474  }
8475  
8476  /**
8477   * Hook to schedule pings and enclosures when a post is published.
8478   *
8479   * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
8480   *
8481   * @since 2.3.0
8482   * @access private
8483   *
8484   * @param int $post_id The ID of the post being published.
8485   */
8486  function _publish_post_hook( $post_id ) {
8487      if ( defined( 'XMLRPC_REQUEST' ) ) {
8488          /**
8489           * Fires when _publish_post_hook() is called during an XML-RPC request.
8490           *
8491           * @since 2.1.0
8492           *
8493           * @param int $post_id Post ID.
8494           */
8495          do_action( 'xmlrpc_publish_post', $post_id );
8496      }
8497  
8498      if ( defined( 'WP_IMPORTING' ) ) {
8499          return;
8500      }
8501  
8502      if ( get_option( 'default_pingback_flag' ) ) {
8503          add_post_meta( $post_id, '_pingme', '1', true );
8504      }
8505      add_post_meta( $post_id, '_encloseme', '1', true );
8506  
8507      $to_ping = get_to_ping( $post_id );
8508      if ( ! empty( $to_ping ) ) {
8509          add_post_meta( $post_id, '_trackbackme', '1' );
8510      }
8511  
8512      if ( ! wp_next_scheduled( 'do_pings' ) ) {
8513          wp_schedule_single_event( time(), 'do_pings' );
8514      }
8515  }
8516  
8517  /**
8518   * Returns the ID of the post's parent.
8519   *
8520   * @since 3.1.0
8521   * @since 5.9.0 The `$post` parameter was made optional.
8522   *
8523   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
8524   * @return int|false Post parent ID (which can be 0 if there is no parent),
8525   *                   or false if the post does not exist.
8526   */
8527  function wp_get_post_parent_id( $post = null ) {
8528      $post = get_post( $post );
8529  
8530      if ( ! $post || is_wp_error( $post ) ) {
8531          return false;
8532      }
8533  
8534      return (int) $post->post_parent;
8535  }
8536  
8537  /**
8538   * Checks the given subset of the post hierarchy for hierarchy loops.
8539   *
8540   * Prevents loops from forming and breaks those that it finds. Attached
8541   * to the {@see 'wp_insert_post_parent'} filter.
8542   *
8543   * @since 3.1.0
8544   *
8545   * @see wp_find_hierarchy_loop()
8546   *
8547   * @param int $post_parent ID of the parent for the post we're checking.
8548   * @param int $post_id     ID of the post we're checking.
8549   * @return int The new post_parent for the post, 0 otherwise.
8550   */
8551  function wp_check_post_hierarchy_for_loops( $post_parent, $post_id ) {
8552      // Nothing fancy here - bail.
8553      if ( ! $post_parent ) {
8554          return 0;
8555      }
8556  
8557      // New post can't cause a loop.
8558      if ( ! $post_id ) {
8559          return $post_parent;
8560      }
8561  
8562      // Can't be its own parent.
8563      if ( $post_parent === $post_id ) {
8564          return 0;
8565      }
8566  
8567      // Now look for larger loops.
8568      $loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_id, $post_parent );
8569      if ( ! $loop ) {
8570          return $post_parent; // No loop.
8571      }
8572  
8573      // Setting $post_parent to the given value causes a loop.
8574      if ( isset( $loop[ $post_id ] ) ) {
8575          return 0;
8576      }
8577  
8578      // There's a loop, but it doesn't contain $post_id. Break the loop.
8579      foreach ( array_keys( $loop ) as $loop_member ) {
8580          wp_update_post(
8581              array(
8582                  'ID'          => $loop_member,
8583                  'post_parent' => 0,
8584              )
8585          );
8586      }
8587  
8588      return $post_parent;
8589  }
8590  
8591  /**
8592   * Sets the post thumbnail (featured image) for the given post.
8593   *
8594   * @since 3.1.0
8595   *
8596   * @param int|WP_Post $post         Post ID or post object where thumbnail should be attached.
8597   * @param int         $thumbnail_id Thumbnail to attach.
8598   * @return int|bool Post meta ID if the key didn't exist (ie. this is the first time that
8599   *                  a thumbnail has been saved for the post), true on successful update,
8600   *                  false on failure or if the value passed is the same as the one that
8601   *                  is already in the database.
8602   */
8603  function set_post_thumbnail( $post, $thumbnail_id ) {
8604      $post         = get_post( $post );
8605      $thumbnail_id = absint( $thumbnail_id );
8606      if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
8607          if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) {
8608              return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
8609          } else {
8610              return delete_post_meta( $post->ID, '_thumbnail_id' );
8611          }
8612      }
8613      return false;
8614  }
8615  
8616  /**
8617   * Removes the thumbnail (featured image) from the given post.
8618   *
8619   * @since 3.3.0
8620   *
8621   * @param int|WP_Post $post Post ID or post object from which the thumbnail should be removed.
8622   * @return bool True on success, false on failure.
8623   */
8624  function delete_post_thumbnail( $post ) {
8625      $post = get_post( $post );
8626      if ( $post ) {
8627          return delete_post_meta( $post->ID, '_thumbnail_id' );
8628      }
8629      return false;
8630  }
8631  
8632  /**
8633   * Deletes auto-drafts for new posts that are > 7 days old.
8634   *
8635   * @since 3.4.0
8636   *
8637   * @global wpdb $wpdb WordPress database abstraction object.
8638   */
8639  function wp_delete_auto_drafts() {
8640      global $wpdb;
8641  
8642      // Cleanup old auto-drafts more than 7 days old.
8643      $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
8644      foreach ( (array) $old_posts as $delete ) {
8645          // Force delete.
8646          wp_delete_post( $delete, true );
8647      }
8648  }
8649  
8650  /**
8651   * Queues posts for lazy-loading of term meta.
8652   *
8653   * @since 4.5.0
8654   *
8655   * @param WP_Post[] $posts Array of WP_Post objects.
8656   */
8657  function wp_queue_posts_for_term_meta_lazyload( $posts ) {
8658      $post_type_taxonomies = array();
8659      $prime_post_terms     = array();
8660      foreach ( $posts as $post ) {
8661          if ( ! ( $post instanceof WP_Post ) ) {
8662              continue;
8663          }
8664  
8665          if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
8666              $post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
8667          }
8668  
8669          foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
8670              $prime_post_terms[ $taxonomy ][] = $post->ID;
8671          }
8672      }
8673  
8674      $term_ids = array();
8675      if ( $prime_post_terms ) {
8676          foreach ( $prime_post_terms as $taxonomy => $post_ids ) {
8677              $cached_term_ids = wp_cache_get_multiple( $post_ids, "{$taxonomy}_relationships" );
8678              if ( is_array( $cached_term_ids ) ) {
8679                  $cached_term_ids = array_filter( $cached_term_ids );
8680                  foreach ( $cached_term_ids as $_term_ids ) {
8681                      // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
8682                      foreach ( $_term_ids as $term_id ) {
8683                          if ( is_numeric( $term_id ) ) {
8684                              $term_ids[] = (int) $term_id;
8685                          } elseif ( isset( $term_id->term_id ) ) {
8686                              $term_ids[] = (int) $term_id->term_id;
8687                          }
8688                      }
8689                  }
8690              }
8691          }
8692          $term_ids = array_unique( $term_ids );
8693      }
8694  
8695      wp_lazyload_term_meta( $term_ids );
8696  }
8697  
8698  /**
8699   * Updates the custom taxonomies' term counts when a post's status is changed.
8700   *
8701   * For example, default posts term counts (for custom taxonomies) don't include
8702   * private / draft posts.
8703   *
8704   * @since 3.3.0
8705   * @access private
8706   *
8707   * @param string  $new_status New post status.
8708   * @param string  $old_status Old post status.
8709   * @param WP_Post $post       Post object.
8710   */
8711  function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
8712      if ( $new_status === $old_status ) {
8713          return;
8714      }
8715  
8716      // Update counts for the post's terms.
8717      foreach ( (array) get_object_taxonomies( $post->post_type, 'objects' ) as $taxonomy ) {
8718          /** This filter is documented in wp-includes/taxonomy.php */
8719          $counted_statuses = apply_filters( 'update_post_term_count_statuses', array( 'publish' ), $taxonomy );
8720  
8721          /*
8722           * Do not recalculate term count if both the old and new status are not included in term counts.
8723           * This accounts for a transition such as draft -> pending.
8724           */
8725          if ( ! in_array( $old_status, $counted_statuses, true ) && ! in_array( $new_status, $counted_statuses, true ) ) {
8726              continue;
8727          }
8728  
8729          /*
8730           * Do not recalculate term count if both the old and new status are included in term counts.
8731           *
8732           * This accounts for transitioning between statuses which are both included in term counts. This can only occur
8733           * if the `update_post_term_count_statuses` filter is in use to count more than just the 'publish' status.
8734           */
8735          if ( in_array( $old_status, $counted_statuses, true ) && in_array( $new_status, $counted_statuses, true ) ) {
8736              continue;
8737          }
8738  
8739          $tt_ids = wp_get_object_terms( $post->ID, $taxonomy->name, array( 'fields' => 'tt_ids' ) );
8740          wp_update_term_count( $tt_ids, $taxonomy->name );
8741      }
8742  }
8743  
8744  /**
8745   * Adds any posts from the given IDs to the cache that do not already exist in cache.
8746   *
8747   * @since 3.4.0
8748   * @since 6.1.0 This function is no longer marked as "private".
8749   *
8750   * @see update_post_cache()
8751   * @see update_postmeta_cache()
8752   * @see update_object_term_cache()
8753   *
8754   * @global wpdb $wpdb WordPress database abstraction object.
8755   *
8756   * @param int[] $ids               ID list.
8757   * @param bool  $update_term_cache Optional. Whether to update the term cache. Default true.
8758   * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
8759   */
8760  function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
8761      global $wpdb;
8762  
8763      $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
8764      if ( ! empty( $non_cached_ids ) ) {
8765          $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
8766  
8767          if ( $fresh_posts ) {
8768              // Despite the name, update_post_cache() expects an array rather than a single post.
8769              update_post_cache( $fresh_posts );
8770          }
8771      }
8772  
8773      if ( $update_meta_cache ) {
8774          update_postmeta_cache( $ids );
8775      }
8776  
8777      if ( $update_term_cache ) {
8778          $post_types = array_map( 'get_post_type', $ids );
8779          $post_types = array_unique( $post_types );
8780          update_object_term_cache( $ids, $post_types );
8781      }
8782  }
8783  
8784  /**
8785   * Prime the cache containing the parent ID of various post objects.
8786   *
8787   * @since 6.4.0
8788   *
8789   * @global wpdb $wpdb WordPress database abstraction object.
8790   *
8791   * @param int[] $ids ID list.
8792   */
8793  function _prime_post_parent_id_caches( array $ids ) {
8794      global $wpdb;
8795  
8796      $ids = array_filter( $ids, '_validate_cache_id' );
8797      $ids = array_unique( array_map( 'intval', $ids ), SORT_NUMERIC );
8798  
8799      if ( empty( $ids ) ) {
8800          return;
8801      }
8802  
8803      $cache_keys = array();
8804      foreach ( $ids as $id ) {
8805          $cache_keys[ $id ] = 'post_parent:' . (string) $id;
8806      }
8807  
8808      $cached_data = wp_cache_get_multiple( array_values( $cache_keys ), 'posts' );
8809  
8810      $non_cached_ids = array();
8811      foreach ( $cache_keys as $id => $cache_key ) {
8812          if ( false === $cached_data[ $cache_key ] ) {
8813              $non_cached_ids[] = $id;
8814          }
8815      }
8816  
8817      if ( ! empty( $non_cached_ids ) ) {
8818          $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 ) ) );
8819  
8820          if ( $fresh_posts ) {
8821              $post_parent_data = array();
8822              foreach ( $fresh_posts as $fresh_post ) {
8823                  $post_parent_data[ 'post_parent:' . (string) $fresh_post->ID ] = (int) $fresh_post->post_parent;
8824              }
8825  
8826              wp_cache_add_multiple( $post_parent_data, 'posts' );
8827          }
8828      }
8829  }
8830  
8831  /**
8832   * Adds a suffix if any trashed posts have a given slug.
8833   *
8834   * Store its desired (i.e. current) slug so it can try to reclaim it
8835   * if the post is untrashed.
8836   *
8837   * For internal use.
8838   *
8839   * @since 4.5.0
8840   * @access private
8841   *
8842   * @param string $post_name Post slug.
8843   * @param int    $post_id   Optional. Post ID that should be ignored. Default 0.
8844   */
8845  function wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_id = 0 ) {
8846      $trashed_posts_with_desired_slug = get_posts(
8847          array(
8848              'name'         => $post_name,
8849              'post_status'  => 'trash',
8850              'post_type'    => 'any',
8851              'nopaging'     => true,
8852              'post__not_in' => array( $post_id ),
8853          )
8854      );
8855  
8856      if ( ! empty( $trashed_posts_with_desired_slug ) ) {
8857          foreach ( $trashed_posts_with_desired_slug as $_post ) {
8858              wp_add_trashed_suffix_to_post_name_for_post( $_post );
8859          }
8860      }
8861  }
8862  
8863  /**
8864   * Adds a trashed suffix for a given post.
8865   *
8866   * Store its desired (i.e. current) slug so it can try to reclaim it
8867   * if the post is untrashed.
8868   *
8869   * For internal use.
8870   *
8871   * @since 4.5.0
8872   * @access private
8873   *
8874   * @global wpdb $wpdb WordPress database abstraction object.
8875   *
8876   * @param WP_Post $post The post.
8877   * @return string New slug for the post.
8878   */
8879  function wp_add_trashed_suffix_to_post_name_for_post( $post ) {
8880      global $wpdb;
8881  
8882      $post = get_post( $post );
8883  
8884      if ( str_ends_with( $post->post_name, '__trashed' ) ) {
8885          return $post->post_name;
8886      }
8887      add_post_meta( $post->ID, '_wp_desired_post_slug', $post->post_name );
8888      $post_name = wp_truncate_slug( $post->post_name, 191 ) . '__trashed';
8889      $wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), array( 'ID' => $post->ID ) );
8890      clean_post_cache( $post->ID );
8891      return $post_name;
8892  }
8893  
8894  /**
8895   * Sets the last changed time for the 'posts' cache group.
8896   *
8897   * @since 5.0.0
8898   */
8899  function wp_cache_set_posts_last_changed() {
8900      wp_cache_set_last_changed( 'posts' );
8901  }
8902  
8903  /**
8904   * Gets all available post MIME types for a given post type.
8905   *
8906   * @since 2.5.0
8907   *
8908   * @global wpdb $wpdb WordPress database abstraction object.
8909   *
8910   * @param string $type
8911   * @return string[] An array of MIME types.
8912   */
8913  function get_available_post_mime_types( $type = 'attachment' ) {
8914      global $wpdb;
8915  
8916      /**
8917       * Filters the list of available post MIME types for the given post type.
8918       *
8919       * @since 6.4.0
8920       *
8921       * @param string[]|null $mime_types An array of MIME types. Default null.
8922       * @param string        $type       The post type name. Usually 'attachment' but can be any post type.
8923       */
8924      $mime_types = apply_filters( 'pre_get_available_post_mime_types', null, $type );
8925  
8926      if ( ! is_array( $mime_types ) ) {
8927          $mime_types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s AND post_mime_type != ''", $type ) );
8928      }
8929  
8930      // Remove nulls from returned $mime_types.
8931      return array_values( array_filter( $mime_types ) );
8932  }
8933  
8934  /**
8935   * Retrieves the path to an uploaded image file.
8936   *
8937   * Similar to `get_attached_file()` however some images may have been processed after uploading
8938   * to make them suitable for web use. In this case the attached "full" size file is usually replaced
8939   * with a scaled down version of the original image. This function always returns the path
8940   * to the originally uploaded image file.
8941   *
8942   * @since 5.3.0
8943   * @since 5.4.0 Added the `$unfiltered` parameter.
8944   *
8945   * @param int  $attachment_id Attachment ID.
8946   * @param bool $unfiltered    Optional. Passed through to `get_attached_file()`. Default false.
8947   * @return string|false Path to the original image file or false if the attachment is not an image.
8948   */
8949  function wp_get_original_image_path( $attachment_id, $unfiltered = false ) {
8950      if ( ! wp_attachment_is_image( $attachment_id ) ) {
8951          return false;
8952      }
8953  
8954      $image_meta = wp_get_attachment_metadata( $attachment_id );
8955      $image_file = get_attached_file( $attachment_id, $unfiltered );
8956  
8957      if ( empty( $image_meta['original_image'] ) ) {
8958          $original_image = $image_file;
8959      } else {
8960          $original_image = path_join( dirname( $image_file ), $image_meta['original_image'] );
8961      }
8962  
8963      /**
8964       * Filters the path to the original image.
8965       *
8966       * @since 5.3.0
8967       *
8968       * @param string $original_image Path to original image file.
8969       * @param int    $attachment_id  Attachment ID.
8970       */
8971      return apply_filters( 'wp_get_original_image_path', $original_image, $attachment_id );
8972  }
8973  
8974  /**
8975   * Retrieves the URL to an original attachment image.
8976   *
8977   * Similar to `wp_get_attachment_url()` however some images may have been
8978   * processed after uploading. In this case this function returns the URL
8979   * to the originally uploaded image file.
8980   *
8981   * @since 5.3.0
8982   *
8983   * @param int $attachment_id Attachment post ID.
8984   * @return string|false Attachment image URL, false on error or if the attachment is not an image.
8985   */
8986  function wp_get_original_image_url( $attachment_id ) {
8987      if ( ! wp_attachment_is_image( $attachment_id ) ) {
8988          return false;
8989      }
8990  
8991      $image_url = wp_get_attachment_url( $attachment_id );
8992  
8993      if ( ! $image_url ) {
8994          return false;
8995      }
8996  
8997      $image_meta = wp_get_attachment_metadata( $attachment_id );
8998  
8999      if ( empty( $image_meta['original_image'] ) ) {
9000          $original_image_url = $image_url;
9001      } else {
9002          $original_image_url = path_join( dirname( $image_url ), $image_meta['original_image'] );
9003      }
9004  
9005      /**
9006       * Filters the URL to the original attachment image.
9007       *
9008       * @since 5.3.0
9009       *
9010       * @param string $original_image_url URL to original image.
9011       * @param int    $attachment_id      Attachment ID.
9012       */
9013      return apply_filters( 'wp_get_original_image_url', $original_image_url, $attachment_id );
9014  }
9015  
9016  /**
9017   * Retrieves the edit root of an attachment: the attachment its chain of edits started from.
9018   *
9019   * Editing an image through the `wp/v2/media/<id>/edit` REST endpoint does not change the
9020   * image that was edited. It saves the result as a brand new attachment, so a site can end
9021   * up with a chain of attachments: an upload, a crop of it, a crop of that crop, and so on.
9022   *
9023   * Every attachment created that way stores the ID of the attachment at the top of its chain,
9024   * so this function can find the edit root in one lookup no matter how long the chain is.
9025   *
9026   * Attachments that were uploaded rather than created by editing have no chain of their own,
9027   * and this returns 0 for them.
9028   *
9029   * @since 7.2.0
9030   *
9031   * @param int $attachment_id Attachment ID.
9032   * @return int ID of the attachment the chain of edits started from, or 0 when none is recorded.
9033   */
9034  function wp_get_edit_root_attachment_id( $attachment_id ) {
9035      $edit_root_id = (int) get_post_meta( $attachment_id, '_wp_attachment_edit_root_id', true );
9036  
9037      // An attachment recorded as its own edit root is a broken record rather than a chain.
9038      if ( $edit_root_id <= 0 || $edit_root_id === (int) $attachment_id ) {
9039          return 0;
9040      }
9041  
9042      return $edit_root_id;
9043  }
9044  
9045  /**
9046   * Clears the recorded edit root ID from any attachment pointing at a deleted one.
9047   *
9048   * Without this, attachments created by editing the deleted image would keep pointing at an
9049   * ID that no longer exists, and could later point at an unrelated attachment if WordPress
9050   * reuses that ID.
9051   *
9052   * This only runs when an attachment is deleted for good. On sites where media goes to the
9053   * trash first, attachments keep pointing at the trashed edit root until the trash is emptied.
9054   *
9055   * @since 7.2.0
9056   *
9057   * @access private
9058   *
9059   * @param int $post_id Attachment ID being deleted.
9060   */
9061  function _wp_delete_edit_root_attachment_id( $post_id ) {
9062      $post_id = (int) $post_id;
9063  
9064      if ( $post_id <= 0 ) {
9065          return;
9066      }
9067  
9068      /*
9069       * Deletes the meta from every attachment recording this ID as its edit root. The meta key
9070       * is indexed, so this only scans the rows for attachments created by editing an image,
9071       * and it avoids searching the serialized attachment metadata for the ID.
9072       */
9073      delete_metadata( 'post', 0, '_wp_attachment_edit_root_id', $post_id, true );
9074  }
9075  
9076  /**
9077   * Filters callback which sets the status of an untrashed post to its previous status.
9078   *
9079   * This can be used as a callback on the `wp_untrash_post_status` filter.
9080   *
9081   * @since 5.6.0
9082   *
9083   * @param string $new_status      The new status of the post being restored.
9084   * @param int    $post_id         The ID of the post being restored.
9085   * @param string $previous_status The status of the post at the point where it was trashed.
9086   * @return string The new status of the post.
9087   */
9088  function wp_untrash_post_set_previous_status( $new_status, $post_id, $previous_status ) {
9089      return $previous_status;
9090  }
9091  
9092  /**
9093   * Returns whether the post can be edited in the block editor.
9094   *
9095   * @since 5.0.0
9096   * @since 6.1.0 Moved to wp-includes from wp-admin.
9097   *
9098   * @param int|WP_Post $post Post ID or WP_Post object.
9099   * @return bool Whether the post can be edited in the block editor.
9100   */
9101  function use_block_editor_for_post( $post ) {
9102      $post = get_post( $post );
9103  
9104      if ( ! $post ) {
9105          return false;
9106      }
9107  
9108      // We're in the meta box loader, so don't use the block editor.
9109      if ( is_admin() && isset( $_GET['meta-box-loader'] ) ) {
9110          check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
9111          return false;
9112      }
9113  
9114      $use_block_editor = use_block_editor_for_post_type( $post->post_type );
9115  
9116      /**
9117       * Filters whether a post is able to be edited in the block editor.
9118       *
9119       * @since 5.0.0
9120       *
9121       * @param bool    $use_block_editor Whether the post can be edited or not.
9122       * @param WP_Post $post             The post being checked.
9123       */
9124      return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
9125  }
9126  
9127  /**
9128   * Returns whether a post type is compatible with the block editor.
9129   *
9130   * The block editor depends on the REST API, and if the post type is not shown in the
9131   * REST API, then it won't work with the block editor.
9132   *
9133   * @since 5.0.0
9134   * @since 6.1.0 Moved to wp-includes from wp-admin.
9135   *
9136   * @param string $post_type The post type.
9137   * @return bool Whether the post type can be edited with the block editor.
9138   */
9139  function use_block_editor_for_post_type( $post_type ) {
9140      if ( ! post_type_exists( $post_type ) ) {
9141          return false;
9142      }
9143  
9144      if ( ! post_type_supports( $post_type, 'editor' ) ) {
9145          return false;
9146      }
9147  
9148      $post_type_object = get_post_type_object( $post_type );
9149      if ( $post_type_object && ! $post_type_object->show_in_rest ) {
9150          return false;
9151      }
9152  
9153      /**
9154       * Filters whether a post is able to be edited in the block editor.
9155       *
9156       * @since 5.0.0
9157       *
9158       * @param bool   $use_block_editor  Whether the post type can be edited or not. Default true.
9159       * @param string $post_type         The post type being checked.
9160       */
9161      return apply_filters( 'use_block_editor_for_post_type', true, $post_type );
9162  }
9163  
9164  /**
9165   * Registers any additional post meta fields.
9166   *
9167   * @since 6.3.0 Adds `wp_pattern_sync_status` meta field to the wp_block post type so an unsynced option can be added.
9168   *
9169   * @link https://github.com/WordPress/gutenberg/pull/51144
9170   */
9171  function wp_create_initial_post_meta() {
9172      register_post_meta(
9173          'wp_block',
9174          'wp_pattern_sync_status',
9175          array(
9176              'sanitize_callback' => 'sanitize_text_field',
9177              'single'            => true,
9178              'type'              => 'string',
9179              'show_in_rest'      => array(
9180                  'schema' => array(
9181                      'type' => 'string',
9182                      'enum' => array( 'partial', 'unsynced' ),
9183                  ),
9184              ),
9185          )
9186      );
9187  }


Generated : Wed Dec 2 08:20:02 2026 Cross-referenced by PHPXref