[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Fri Oct 31 08:20:06 2025 Cross-referenced by PHPXref