[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Fri Jun 26 08:20:11 2026 Cross-referenced by PHPXref