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


Generated : Sat Jun 14 08:20:01 2025 Cross-referenced by PHPXref