[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Thu Jul 16 08:20:16 2026 Cross-referenced by PHPXref