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


Generated : Sun Jul 26 08:20:18 2026 Cross-referenced by PHPXref