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


Generated : Mon Apr 27 08:20:11 2026 Cross-referenced by PHPXref