[ 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 New Media File' ),
  79                  'edit_item'      => __( 'Edit Media' ),
  80                  'view_item'      => ( '1' === get_option( 'wp_attachment_pages_enabled' ) ) ? __( 'View Attachment Page' ) : __( 'View Media File' ),
  81                  'attributes'     => __( 'Attachment Attributes' ),
  82              ),
  83              'public'                => true,
  84              'show_ui'               => true,
  85              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
  86              '_edit_link'            => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  87              'capability_type'       => 'post',
  88              'capabilities'          => array(
  89                  'create_posts' => 'upload_files',
  90              ),
  91              'map_meta_cap'          => true,
  92              'menu_icon'             => 'dashicons-admin-media',
  93              'hierarchical'          => false,
  94              'rewrite'               => false,
  95              'query_var'             => false,
  96              'show_in_nav_menus'     => false,
  97              'delete_with_user'      => true,
  98              'supports'              => array( 'title', 'author', 'comments' ),
  99              'show_in_rest'          => true,
 100              'rest_base'             => 'media',
 101              'rest_controller_class' => 'WP_REST_Attachments_Controller',
 102          )
 103      );
 104      add_post_type_support( 'attachment:audio', 'thumbnail' );
 105      add_post_type_support( 'attachment:video', 'thumbnail' );
 106  
 107      register_post_type(
 108          'revision',
 109          array(
 110              'labels'           => array(
 111                  'name'          => __( 'Revisions' ),
 112                  'singular_name' => __( 'Revision' ),
 113              ),
 114              'public'           => false,
 115              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 116              '_edit_link'       => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
 117              'capability_type'  => 'post',
 118              'map_meta_cap'     => true,
 119              'hierarchical'     => false,
 120              'rewrite'          => false,
 121              'query_var'        => false,
 122              'can_export'       => false,
 123              'delete_with_user' => true,
 124              'supports'         => array( 'author' ),
 125          )
 126      );
 127  
 128      register_post_type(
 129          'nav_menu_item',
 130          array(
 131              'labels'                => array(
 132                  'name'          => __( 'Navigation Menu Items' ),
 133                  'singular_name' => __( 'Navigation Menu Item' ),
 134              ),
 135              'public'                => false,
 136              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 137              'hierarchical'          => false,
 138              'rewrite'               => false,
 139              'delete_with_user'      => false,
 140              'query_var'             => false,
 141              'map_meta_cap'          => true,
 142              'capability_type'       => array( 'edit_theme_options', 'edit_theme_options' ),
 143              'capabilities'          => array(
 144                  // Meta Capabilities.
 145                  'edit_post'              => 'edit_post',
 146                  'read_post'              => 'read_post',
 147                  'delete_post'            => 'delete_post',
 148                  // Primitive Capabilities.
 149                  'edit_posts'             => 'edit_theme_options',
 150                  'edit_others_posts'      => 'edit_theme_options',
 151                  'delete_posts'           => 'edit_theme_options',
 152                  'publish_posts'          => 'edit_theme_options',
 153                  'read_private_posts'     => 'edit_theme_options',
 154                  'read'                   => 'read',
 155                  'delete_private_posts'   => 'edit_theme_options',
 156                  'delete_published_posts' => 'edit_theme_options',
 157                  'delete_others_posts'    => 'edit_theme_options',
 158                  'edit_private_posts'     => 'edit_theme_options',
 159                  'edit_published_posts'   => 'edit_theme_options',
 160              ),
 161              'show_in_rest'          => true,
 162              'rest_base'             => 'menu-items',
 163              'rest_controller_class' => 'WP_REST_Menu_Items_Controller',
 164          )
 165      );
 166  
 167      register_post_type(
 168          'custom_css',
 169          array(
 170              'labels'           => array(
 171                  'name'          => __( 'Custom CSS' ),
 172                  'singular_name' => __( 'Custom CSS' ),
 173              ),
 174              'public'           => false,
 175              'hierarchical'     => false,
 176              'rewrite'          => false,
 177              'query_var'        => false,
 178              'delete_with_user' => false,
 179              'can_export'       => true,
 180              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 181              'supports'         => array( 'title', 'revisions' ),
 182              'capabilities'     => array(
 183                  'delete_posts'           => 'edit_theme_options',
 184                  'delete_post'            => 'edit_theme_options',
 185                  'delete_published_posts' => 'edit_theme_options',
 186                  'delete_private_posts'   => 'edit_theme_options',
 187                  'delete_others_posts'    => 'edit_theme_options',
 188                  'edit_post'              => 'edit_css',
 189                  'edit_posts'             => 'edit_css',
 190                  'edit_others_posts'      => 'edit_css',
 191                  'edit_published_posts'   => 'edit_css',
 192                  'read_post'              => 'read',
 193                  'read_private_posts'     => 'read',
 194                  'publish_posts'          => 'edit_theme_options',
 195              ),
 196          )
 197      );
 198  
 199      register_post_type(
 200          'customize_changeset',
 201          array(
 202              'labels'           => array(
 203                  'name'               => _x( 'Changesets', 'post type general name' ),
 204                  'singular_name'      => _x( 'Changeset', 'post type singular name' ),
 205                  'add_new'            => __( 'Add New Changeset' ),
 206                  'add_new_item'       => __( 'Add New Changeset' ),
 207                  'new_item'           => __( 'New Changeset' ),
 208                  'edit_item'          => __( 'Edit Changeset' ),
 209                  'view_item'          => __( 'View Changeset' ),
 210                  'all_items'          => __( 'All Changesets' ),
 211                  'search_items'       => __( 'Search Changesets' ),
 212                  'not_found'          => __( 'No changesets found.' ),
 213                  'not_found_in_trash' => __( 'No changesets found in Trash.' ),
 214              ),
 215              'public'           => false,
 216              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 217              'map_meta_cap'     => true,
 218              'hierarchical'     => false,
 219              'rewrite'          => false,
 220              'query_var'        => false,
 221              'can_export'       => false,
 222              'delete_with_user' => false,
 223              'supports'         => array( 'title', 'author' ),
 224              'capability_type'  => 'customize_changeset',
 225              'capabilities'     => array(
 226                  'create_posts'           => 'customize',
 227                  'delete_others_posts'    => 'customize',
 228                  'delete_post'            => 'customize',
 229                  'delete_posts'           => 'customize',
 230                  'delete_private_posts'   => 'customize',
 231                  'delete_published_posts' => 'customize',
 232                  'edit_others_posts'      => 'customize',
 233                  'edit_post'              => 'customize',
 234                  'edit_posts'             => 'customize',
 235                  'edit_private_posts'     => 'customize',
 236                  'edit_published_posts'   => 'do_not_allow',
 237                  'publish_posts'          => 'customize',
 238                  'read'                   => 'read',
 239                  'read_post'              => 'customize',
 240                  'read_private_posts'     => 'customize',
 241              ),
 242          )
 243      );
 244  
 245      register_post_type(
 246          'oembed_cache',
 247          array(
 248              'labels'           => array(
 249                  'name'          => __( 'oEmbed Responses' ),
 250                  'singular_name' => __( 'oEmbed Response' ),
 251              ),
 252              'public'           => false,
 253              'hierarchical'     => false,
 254              'rewrite'          => false,
 255              'query_var'        => false,
 256              'delete_with_user' => false,
 257              'can_export'       => false,
 258              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 259              'supports'         => array(),
 260          )
 261      );
 262  
 263      register_post_type(
 264          'user_request',
 265          array(
 266              'labels'           => array(
 267                  'name'          => __( 'User Requests' ),
 268                  'singular_name' => __( 'User Request' ),
 269              ),
 270              'public'           => false,
 271              '_builtin'         => true, /* internal use only. don't use this when registering your own post type. */
 272              'hierarchical'     => false,
 273              'rewrite'          => false,
 274              'query_var'        => false,
 275              'can_export'       => false,
 276              'delete_with_user' => false,
 277              'supports'         => array(),
 278          )
 279      );
 280  
 281      register_post_type(
 282          'wp_block',
 283          array(
 284              'labels'                => array(
 285                  'name'                     => _x( 'Patterns', 'post type general name' ),
 286                  'singular_name'            => _x( 'Pattern', 'post type singular name' ),
 287                  'add_new'                  => __( 'Add New Pattern' ),
 288                  'add_new_item'             => __( 'Add New Pattern' ),
 289                  'new_item'                 => __( 'New Pattern' ),
 290                  'edit_item'                => __( 'Edit Block Pattern' ),
 291                  'view_item'                => __( 'View Pattern' ),
 292                  'view_items'               => __( 'View Patterns' ),
 293                  'all_items'                => __( 'All Patterns' ),
 294                  'search_items'             => __( 'Search Patterns' ),
 295                  'not_found'                => __( 'No patterns found.' ),
 296                  'not_found_in_trash'       => __( 'No patterns found in Trash.' ),
 297                  'filter_items_list'        => __( 'Filter patterns list' ),
 298                  'items_list_navigation'    => __( 'Patterns list navigation' ),
 299                  'items_list'               => __( 'Patterns list' ),
 300                  'item_published'           => __( 'Pattern published.' ),
 301                  'item_published_privately' => __( 'Pattern published privately.' ),
 302                  'item_reverted_to_draft'   => __( 'Pattern reverted to draft.' ),
 303                  'item_scheduled'           => __( 'Pattern scheduled.' ),
 304                  'item_updated'             => __( 'Pattern updated.' ),
 305              ),
 306              'public'                => false,
 307              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 308              'show_ui'               => true,
 309              'show_in_menu'          => false,
 310              'rewrite'               => false,
 311              'show_in_rest'          => true,
 312              'rest_base'             => 'blocks',
 313              'rest_controller_class' => 'WP_REST_Blocks_Controller',
 314              'capability_type'       => 'block',
 315              'capabilities'          => array(
 316                  // You need to be able to edit posts, in order to read blocks in their raw form.
 317                  'read'                   => 'edit_posts',
 318                  // You need to be able to publish posts, in order to create blocks.
 319                  'create_posts'           => 'publish_posts',
 320                  'edit_posts'             => 'edit_posts',
 321                  'edit_published_posts'   => 'edit_published_posts',
 322                  'delete_published_posts' => 'delete_published_posts',
 323                  // Enables trashing draft posts as well.
 324                  'delete_posts'           => 'delete_posts',
 325                  'edit_others_posts'      => 'edit_others_posts',
 326                  'delete_others_posts'    => 'delete_others_posts',
 327              ),
 328              'map_meta_cap'          => true,
 329              'supports'              => array(
 330                  'title',
 331                  'excerpt',
 332                  'editor',
 333                  'revisions',
 334                  'custom-fields',
 335              ),
 336          )
 337      );
 338  
 339      $template_edit_link = 'site-editor.php?' . build_query(
 340          array(
 341              'postType' => '%s',
 342              'postId'   => '%s',
 343              'canvas'   => 'edit',
 344          )
 345      );
 346  
 347      register_post_type(
 348          'wp_template',
 349          array(
 350              'labels'                          => array(
 351                  'name'                  => _x( 'Templates', 'post type general name' ),
 352                  'singular_name'         => _x( 'Template', 'post type singular name' ),
 353                  'add_new'               => __( 'Add New Template' ),
 354                  'add_new_item'          => __( 'Add New Template' ),
 355                  'new_item'              => __( 'New Template' ),
 356                  'edit_item'             => __( 'Edit Template' ),
 357                  'view_item'             => __( 'View Template' ),
 358                  'all_items'             => __( 'Templates' ),
 359                  'search_items'          => __( 'Search Templates' ),
 360                  'parent_item_colon'     => __( 'Parent Template:' ),
 361                  'not_found'             => __( 'No templates found.' ),
 362                  'not_found_in_trash'    => __( 'No templates found in Trash.' ),
 363                  'archives'              => __( 'Template archives' ),
 364                  'insert_into_item'      => __( 'Insert into template' ),
 365                  'uploaded_to_this_item' => __( 'Uploaded to this template' ),
 366                  'filter_items_list'     => __( 'Filter templates list' ),
 367                  'items_list_navigation' => __( 'Templates list navigation' ),
 368                  'items_list'            => __( 'Templates list' ),
 369                  'item_updated'          => __( 'Template updated.' ),
 370              ),
 371              'description'                     => __( 'Templates to include in your theme.' ),
 372              'public'                          => false,
 373              '_builtin'                        => true, /* internal use only. don't use this when registering your own post type. */
 374              '_edit_link'                      => $template_edit_link, /* internal use only. don't use this when registering your own post type. */
 375              'has_archive'                     => false,
 376              'show_ui'                         => false,
 377              'show_in_menu'                    => false,
 378              'show_in_rest'                    => true,
 379              'rewrite'                         => false,
 380              'rest_base'                       => 'templates',
 381              'rest_controller_class'           => 'WP_REST_Templates_Controller',
 382              'autosave_rest_controller_class'  => 'WP_REST_Template_Autosaves_Controller',
 383              'revisions_rest_controller_class' => 'WP_REST_Template_Revisions_Controller',
 384              'late_route_registration'         => true,
 385              'capability_type'                 => array( 'template', 'templates' ),
 386              'capabilities'                    => array(
 387                  'create_posts'           => 'edit_theme_options',
 388                  'delete_posts'           => 'edit_theme_options',
 389                  'delete_others_posts'    => 'edit_theme_options',
 390                  'delete_private_posts'   => 'edit_theme_options',
 391                  'delete_published_posts' => 'edit_theme_options',
 392                  'edit_posts'             => 'edit_theme_options',
 393                  'edit_others_posts'      => 'edit_theme_options',
 394                  'edit_private_posts'     => 'edit_theme_options',
 395                  'edit_published_posts'   => 'edit_theme_options',
 396                  'publish_posts'          => 'edit_theme_options',
 397                  'read'                   => 'edit_theme_options',
 398                  'read_private_posts'     => 'edit_theme_options',
 399              ),
 400              'map_meta_cap'                    => true,
 401              'supports'                        => array(
 402                  'title',
 403                  'slug',
 404                  'excerpt',
 405                  'editor',
 406                  'revisions',
 407                  'author',
 408              ),
 409          )
 410      );
 411  
 412      register_post_type(
 413          'wp_template_part',
 414          array(
 415              'labels'                          => array(
 416                  'name'                  => _x( 'Template Parts', 'post type general name' ),
 417                  'singular_name'         => _x( 'Template Part', 'post type singular name' ),
 418                  'add_new'               => __( 'Add New Template Part' ),
 419                  'add_new_item'          => __( 'Add New Template Part' ),
 420                  'new_item'              => __( 'New Template Part' ),
 421                  'edit_item'             => __( 'Edit Template Part' ),
 422                  'view_item'             => __( 'View Template Part' ),
 423                  'all_items'             => __( 'Template Parts' ),
 424                  'search_items'          => __( 'Search Template Parts' ),
 425                  'parent_item_colon'     => __( 'Parent Template Part:' ),
 426                  'not_found'             => __( 'No template parts found.' ),
 427                  'not_found_in_trash'    => __( 'No template parts found in Trash.' ),
 428                  'archives'              => __( 'Template part archives' ),
 429                  'insert_into_item'      => __( 'Insert into template part' ),
 430                  'uploaded_to_this_item' => __( 'Uploaded to this template part' ),
 431                  'filter_items_list'     => __( 'Filter template parts list' ),
 432                  'items_list_navigation' => __( 'Template parts list navigation' ),
 433                  'items_list'            => __( 'Template parts list' ),
 434                  'item_updated'          => __( 'Template part updated.' ),
 435              ),
 436              'description'                     => __( 'Template parts to include in your templates.' ),
 437              'public'                          => false,
 438              '_builtin'                        => true, /* internal use only. don't use this when registering your own post type. */
 439              '_edit_link'                      => $template_edit_link, /* internal use only. don't use this when registering your own post type. */
 440              'has_archive'                     => false,
 441              'show_ui'                         => false,
 442              'show_in_menu'                    => false,
 443              'show_in_rest'                    => true,
 444              'rewrite'                         => false,
 445              'rest_base'                       => 'template-parts',
 446              'rest_controller_class'           => 'WP_REST_Templates_Controller',
 447              'autosave_rest_controller_class'  => 'WP_REST_Template_Autosaves_Controller',
 448              'revisions_rest_controller_class' => 'WP_REST_Template_Revisions_Controller',
 449              'late_route_registration'         => true,
 450              'map_meta_cap'                    => true,
 451              'capabilities'                    => array(
 452                  'create_posts'           => 'edit_theme_options',
 453                  'delete_posts'           => 'edit_theme_options',
 454                  'delete_others_posts'    => 'edit_theme_options',
 455                  'delete_private_posts'   => 'edit_theme_options',
 456                  'delete_published_posts' => 'edit_theme_options',
 457                  'edit_posts'             => 'edit_theme_options',
 458                  'edit_others_posts'      => 'edit_theme_options',
 459                  'edit_private_posts'     => 'edit_theme_options',
 460                  'edit_published_posts'   => 'edit_theme_options',
 461                  'publish_posts'          => 'edit_theme_options',
 462                  'read'                   => 'edit_theme_options',
 463                  'read_private_posts'     => 'edit_theme_options',
 464              ),
 465              'supports'                        => array(
 466                  'title',
 467                  'slug',
 468                  'excerpt',
 469                  'editor',
 470                  'revisions',
 471                  'author',
 472              ),
 473          )
 474      );
 475  
 476      register_post_type(
 477          'wp_global_styles',
 478          array(
 479              'label'                           => _x( 'Global Styles', 'post type general name' ),
 480              'description'                     => __( 'Global styles to include in themes.' ),
 481              'public'                          => false,
 482              '_builtin'                        => true, /* internal use only. don't use this when registering your own post type. */
 483              '_edit_link'                      => '/site-editor.php?canvas=edit', /* internal use only. don't use this when registering your own post type. */
 484              'show_ui'                         => false,
 485              'show_in_rest'                    => true,
 486              'rewrite'                         => false,
 487              'rest_base'                       => 'global-styles',
 488              'rest_controller_class'           => 'WP_REST_Global_Styles_Controller',
 489              'revisions_rest_controller_class' => 'WP_REST_Global_Styles_Revisions_Controller',
 490              'late_route_registration'         => true,
 491              'capabilities'                    => array(
 492                  'read'                   => 'edit_theme_options',
 493                  'create_posts'           => 'edit_theme_options',
 494                  'edit_posts'             => 'edit_theme_options',
 495                  'edit_published_posts'   => 'edit_theme_options',
 496                  'delete_published_posts' => 'edit_theme_options',
 497                  'edit_others_posts'      => 'edit_theme_options',
 498                  'delete_others_posts'    => 'edit_theme_options',
 499              ),
 500              'map_meta_cap'                    => true,
 501              'supports'                        => array(
 502                  'title',
 503                  'editor',
 504                  'revisions',
 505              ),
 506          )
 507      );
 508      // Disable autosave endpoints for global styles.
 509      remove_post_type_support( 'wp_global_styles', 'autosave' );
 510  
 511      $navigation_post_edit_link = 'site-editor.php?' . build_query(
 512          array(
 513              'postId'   => '%s',
 514              'postType' => 'wp_navigation',
 515              'canvas'   => 'edit',
 516          )
 517      );
 518  
 519      register_post_type(
 520          'wp_navigation',
 521          array(
 522              'labels'                => array(
 523                  'name'                  => _x( 'Navigation Menus', 'post type general name' ),
 524                  'singular_name'         => _x( 'Navigation Menu', 'post type singular name' ),
 525                  'add_new'               => __( 'Add New Navigation Menu' ),
 526                  'add_new_item'          => __( 'Add New Navigation Menu' ),
 527                  'new_item'              => __( 'New Navigation Menu' ),
 528                  'edit_item'             => __( 'Edit Navigation Menu' ),
 529                  'view_item'             => __( 'View Navigation Menu' ),
 530                  'all_items'             => __( 'Navigation Menus' ),
 531                  'search_items'          => __( 'Search Navigation Menus' ),
 532                  'parent_item_colon'     => __( 'Parent Navigation Menu:' ),
 533                  'not_found'             => __( 'No Navigation Menu found.' ),
 534                  'not_found_in_trash'    => __( 'No Navigation Menu found in Trash.' ),
 535                  'archives'              => __( 'Navigation Menu archives' ),
 536                  'insert_into_item'      => __( 'Insert into Navigation Menu' ),
 537                  'uploaded_to_this_item' => __( 'Uploaded to this Navigation Menu' ),
 538                  'filter_items_list'     => __( 'Filter Navigation Menu list' ),
 539                  'items_list_navigation' => __( 'Navigation Menus list navigation' ),
 540                  'items_list'            => __( 'Navigation Menus list' ),
 541              ),
 542              'description'           => __( 'Navigation menus that can be inserted into your site.' ),
 543              'public'                => false,
 544              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 545              '_edit_link'            => $navigation_post_edit_link, /* internal use only. don't use this when registering your own post type. */
 546              'has_archive'           => false,
 547              'show_ui'               => true,
 548              'show_in_menu'          => false,
 549              'show_in_admin_bar'     => false,
 550              'show_in_rest'          => true,
 551              'rewrite'               => false,
 552              'map_meta_cap'          => true,
 553              'capabilities'          => array(
 554                  'edit_others_posts'      => 'edit_theme_options',
 555                  'delete_posts'           => 'edit_theme_options',
 556                  'publish_posts'          => 'edit_theme_options',
 557                  'create_posts'           => 'edit_theme_options',
 558                  'read_private_posts'     => 'edit_theme_options',
 559                  'delete_private_posts'   => 'edit_theme_options',
 560                  'delete_published_posts' => 'edit_theme_options',
 561                  'delete_others_posts'    => 'edit_theme_options',
 562                  'edit_private_posts'     => 'edit_theme_options',
 563                  'edit_published_posts'   => 'edit_theme_options',
 564                  'edit_posts'             => 'edit_theme_options',
 565              ),
 566              'rest_base'             => 'navigation',
 567              'rest_controller_class' => 'WP_REST_Posts_Controller',
 568              'supports'              => array(
 569                  'title',
 570                  'editor',
 571                  'revisions',
 572              ),
 573          )
 574      );
 575  
 576      register_post_type(
 577          'wp_font_family',
 578          array(
 579              'labels'                => array(
 580                  'name'          => __( 'Font Families' ),
 581                  'singular_name' => __( 'Font Family' ),
 582              ),
 583              'public'                => false,
 584              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 585              'hierarchical'          => false,
 586              'capabilities'          => array(
 587                  'read'                   => 'edit_theme_options',
 588                  'read_private_posts'     => 'edit_theme_options',
 589                  'create_posts'           => 'edit_theme_options',
 590                  'publish_posts'          => 'edit_theme_options',
 591                  'edit_posts'             => 'edit_theme_options',
 592                  'edit_others_posts'      => 'edit_theme_options',
 593                  'edit_published_posts'   => 'edit_theme_options',
 594                  'delete_posts'           => 'edit_theme_options',
 595                  'delete_others_posts'    => 'edit_theme_options',
 596                  'delete_published_posts' => 'edit_theme_options',
 597              ),
 598              'map_meta_cap'          => true,
 599              'query_var'             => false,
 600              'rewrite'               => false,
 601              'show_in_rest'          => true,
 602              'rest_base'             => 'font-families',
 603              'rest_controller_class' => 'WP_REST_Font_Families_Controller',
 604              'supports'              => array( 'title' ),
 605          )
 606      );
 607  
 608      register_post_type(
 609          'wp_font_face',
 610          array(
 611              'labels'                => array(
 612                  'name'          => __( 'Font Faces' ),
 613                  'singular_name' => __( 'Font Face' ),
 614              ),
 615              'public'                => false,
 616              '_builtin'              => true, /* internal use only. don't use this when registering your own post type. */
 617              'hierarchical'          => false,
 618              'capabilities'          => array(
 619                  'read'                   => 'edit_theme_options',
 620                  'read_private_posts'     => 'edit_theme_options',
 621                  'create_posts'           => 'edit_theme_options',
 622                  'publish_posts'          => 'edit_theme_options',
 623                  'edit_posts'             => 'edit_theme_options',
 624                  'edit_others_posts'      => 'edit_theme_options',
 625                  'edit_published_posts'   => 'edit_theme_options',
 626                  'delete_posts'           => 'edit_theme_options',
 627                  'delete_others_posts'    => 'edit_theme_options',
 628                  'delete_published_posts' => 'edit_theme_options',
 629              ),
 630              'map_meta_cap'          => true,
 631              'query_var'             => false,
 632              'rewrite'               => false,
 633              'show_in_rest'          => true,
 634              'rest_base'             => 'font-families/(?P<font_family_id>[\d]+)/font-faces',
 635              'rest_controller_class' => 'WP_REST_Font_Faces_Controller',
 636              'supports'              => array( 'title' ),
 637          )
 638      );
 639  
 640      register_post_status(
 641          'publish',
 642          array(
 643              'label'       => _x( 'Published', 'post status' ),
 644              'public'      => true,
 645              '_builtin'    => true, /* internal use only. */
 646              /* translators: %s: Number of published posts. */
 647              'label_count' => _n_noop(
 648                  'Published <span class="count">(%s)</span>',
 649                  'Published <span class="count">(%s)</span>'
 650              ),
 651          )
 652      );
 653  
 654      register_post_status(
 655          'future',
 656          array(
 657              'label'       => _x( 'Scheduled', 'post status' ),
 658              'protected'   => true,
 659              '_builtin'    => true, /* internal use only. */
 660              /* translators: %s: Number of scheduled posts. */
 661              'label_count' => _n_noop(
 662                  'Scheduled <span class="count">(%s)</span>',
 663                  'Scheduled <span class="count">(%s)</span>'
 664              ),
 665          )
 666      );
 667  
 668      register_post_status(
 669          'draft',
 670          array(
 671              'label'         => _x( 'Draft', 'post status' ),
 672              'protected'     => true,
 673              '_builtin'      => true, /* internal use only. */
 674              /* translators: %s: Number of draft posts. */
 675              'label_count'   => _n_noop(
 676                  'Draft <span class="count">(%s)</span>',
 677                  'Drafts <span class="count">(%s)</span>'
 678              ),
 679              'date_floating' => true,
 680          )
 681      );
 682  
 683      register_post_status(
 684          'pending',
 685          array(
 686              'label'         => _x( 'Pending', 'post status' ),
 687              'protected'     => true,
 688              '_builtin'      => true, /* internal use only. */
 689              /* translators: %s: Number of pending posts. */
 690              'label_count'   => _n_noop(
 691                  'Pending <span class="count">(%s)</span>',
 692                  'Pending <span class="count">(%s)</span>'
 693              ),
 694              'date_floating' => true,
 695          )
 696      );
 697  
 698      register_post_status(
 699          'private',
 700          array(
 701              'label'       => _x( 'Private', 'post status' ),
 702              'private'     => true,
 703              '_builtin'    => true, /* internal use only. */
 704              /* translators: %s: Number of private posts. */
 705              'label_count' => _n_noop(
 706                  'Private <span class="count">(%s)</span>',
 707                  'Private <span class="count">(%s)</span>'
 708              ),
 709          )
 710      );
 711  
 712      register_post_status(
 713          'trash',
 714          array(
 715              'label'                     => _x( 'Trash', 'post status' ),
 716              'internal'                  => true,
 717              '_builtin'                  => true, /* internal use only. */
 718              /* translators: %s: Number of trashed posts. */
 719              'label_count'               => _n_noop(
 720                  'Trash <span class="count">(%s)</span>',
 721                  'Trash <span class="count">(%s)</span>'
 722              ),
 723              'show_in_admin_status_list' => true,
 724          )
 725      );
 726  
 727      register_post_status(
 728          'auto-draft',
 729          array(
 730              'label'         => 'auto-draft',
 731              'internal'      => true,
 732              '_builtin'      => true, /* internal use only. */
 733              'date_floating' => true,
 734          )
 735      );
 736  
 737      register_post_status(
 738          'inherit',
 739          array(
 740              'label'               => 'inherit',
 741              'internal'            => true,
 742              '_builtin'            => true, /* internal use only. */
 743              'exclude_from_search' => false,
 744          )
 745      );
 746  
 747      register_post_status(
 748          'request-pending',
 749          array(
 750              'label'               => _x( 'Pending', 'request status' ),
 751              'internal'            => true,
 752              '_builtin'            => true, /* internal use only. */
 753              /* translators: %s: Number of pending requests. */
 754              'label_count'         => _n_noop(
 755                  'Pending <span class="count">(%s)</span>',
 756                  'Pending <span class="count">(%s)</span>'
 757              ),
 758              'exclude_from_search' => false,
 759          )
 760      );
 761  
 762      register_post_status(
 763          'request-confirmed',
 764          array(
 765              'label'               => _x( 'Confirmed', 'request status' ),
 766              'internal'            => true,
 767              '_builtin'            => true, /* internal use only. */
 768              /* translators: %s: Number of confirmed requests. */
 769              'label_count'         => _n_noop(
 770                  'Confirmed <span class="count">(%s)</span>',
 771                  'Confirmed <span class="count">(%s)</span>'
 772              ),
 773              'exclude_from_search' => false,
 774          )
 775      );
 776  
 777      register_post_status(
 778          'request-failed',
 779          array(
 780              'label'               => _x( 'Failed', 'request status' ),
 781              'internal'            => true,
 782              '_builtin'            => true, /* internal use only. */
 783              /* translators: %s: Number of failed requests. */
 784              'label_count'         => _n_noop(
 785                  'Failed <span class="count">(%s)</span>',
 786                  'Failed <span class="count">(%s)</span>'
 787              ),
 788              'exclude_from_search' => false,
 789          )
 790      );
 791  
 792      register_post_status(
 793          'request-completed',
 794          array(
 795              'label'               => _x( 'Completed', 'request status' ),
 796              'internal'            => true,
 797              '_builtin'            => true, /* internal use only. */
 798              /* translators: %s: Number of completed requests. */
 799              'label_count'         => _n_noop(
 800                  'Completed <span class="count">(%s)</span>',
 801                  'Completed <span class="count">(%s)</span>'
 802              ),
 803              'exclude_from_search' => false,
 804          )
 805      );
 806  }
 807  
 808  /**
 809   * Retrieves attached file path based on attachment ID.
 810   *
 811   * By default the path will go through the {@see 'get_attached_file'} filter, but
 812   * passing `true` to the `$unfiltered` argument will return the file path unfiltered.
 813   *
 814   * The function works by retrieving the `_wp_attached_file` post meta value.
 815   * This is a convenience function to prevent looking up the meta name and provide
 816   * a mechanism for sending the attached filename through a filter.
 817   *
 818   * @since 2.0.0
 819   *
 820   * @param int  $attachment_id Attachment ID.
 821   * @param bool $unfiltered    Optional. Whether to skip the {@see 'get_attached_file'} filter.
 822   *                            Default false.
 823   * @return string|false The file path to where the attached file should be, false otherwise.
 824   */
 825  function get_attached_file( $attachment_id, $unfiltered = false ) {
 826      $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
 827  
 828      // If the file is relative, prepend upload dir.
 829      if ( $file && ! str_starts_with( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) ) {
 830          $uploads = wp_get_upload_dir();
 831          if ( false === $uploads['error'] ) {
 832              $file = $uploads['basedir'] . "/$file";
 833          }
 834      }
 835  
 836      if ( $unfiltered ) {
 837          return $file;
 838      }
 839  
 840      /**
 841       * Filters the attached file based on the given ID.
 842       *
 843       * @since 2.1.0
 844       *
 845       * @param string|false $file          The file path to where the attached file should be, false otherwise.
 846       * @param int          $attachment_id Attachment ID.
 847       */
 848      return apply_filters( 'get_attached_file', $file, $attachment_id );
 849  }
 850  
 851  /**
 852   * Updates attachment file path based on attachment ID.
 853   *
 854   * Used to update the file path of the attachment, which uses post meta name
 855   * '_wp_attached_file' to store the path of the attachment.
 856   *
 857   * @since 2.1.0
 858   *
 859   * @param int    $attachment_id Attachment ID.
 860   * @param string $file          File path for the attachment.
 861   * @return bool True on success, false on failure.
 862   */
 863  function update_attached_file( $attachment_id, $file ) {
 864      if ( ! get_post( $attachment_id ) ) {
 865          return false;
 866      }
 867  
 868      /**
 869       * Filters the path to the attached file to update.
 870       *
 871       * @since 2.1.0
 872       *
 873       * @param string $file          Path to the attached file to update.
 874       * @param int    $attachment_id Attachment ID.
 875       */
 876      $file = apply_filters( 'update_attached_file', $file, $attachment_id );
 877  
 878      $file = _wp_relative_upload_path( $file );
 879      if ( $file ) {
 880          return update_post_meta( $attachment_id, '_wp_attached_file', $file );
 881      } else {
 882          return delete_post_meta( $attachment_id, '_wp_attached_file' );
 883      }
 884  }
 885  
 886  /**
 887   * Returns relative path to an uploaded file.
 888   *
 889   * The path is relative to the current upload dir.
 890   *
 891   * @since 2.9.0
 892   * @access private
 893   *
 894   * @param string $path Full path to the file.
 895   * @return string Relative path on success, unchanged path on failure.
 896   */
 897  function _wp_relative_upload_path( $path ) {
 898      $new_path = $path;
 899  
 900      $uploads = wp_get_upload_dir();
 901      if ( str_starts_with( $new_path, $uploads['basedir'] ) ) {
 902              $new_path = str_replace( $uploads['basedir'], '', $new_path );
 903              $new_path = ltrim( $new_path, '/' );
 904      }
 905  
 906      /**
 907       * Filters the relative path to an uploaded file.
 908       *
 909       * @since 2.9.0
 910       *
 911       * @param string $new_path Relative path to the file.
 912       * @param string $path     Full path to the file.
 913       */
 914      return apply_filters( '_wp_relative_upload_path', $new_path, $path );
 915  }
 916  
 917  /**
 918   * Retrieves all children of the post parent ID.
 919   *
 920   * Normally, without any enhancements, the children would apply to pages. In the
 921   * context of the inner workings of WordPress, pages, posts, and attachments
 922   * share the same table, so therefore the functionality could apply to any one
 923   * of them. It is then noted that while this function does not work on posts, it
 924   * does not mean that it won't work on posts. It is recommended that you know
 925   * what context you wish to retrieve the children of.
 926   *
 927   * Attachments may also be made the child of a post, so if that is an accurate
 928   * statement (which needs to be verified), it would then be possible to get
 929   * all of the attachments for a post. Attachments have since changed since
 930   * version 2.5, so this is most likely inaccurate, but serves generally as an
 931   * example of what is possible.
 932   *
 933   * The arguments listed as defaults are for this function and also of the
 934   * get_posts() function. The arguments are combined with the get_children defaults
 935   * and are then passed to the get_posts() function, which accepts additional arguments.
 936   * You can replace the defaults in this function, listed below and the additional
 937   * arguments listed in the get_posts() function.
 938   *
 939   * The 'post_parent' is the most important argument and important attention
 940   * needs to be paid to the $args parameter. If you pass either an object or an
 941   * integer (number), then just the 'post_parent' is grabbed and everything else
 942   * is lost. If you don't specify any arguments, then it is assumed that you are
 943   * in The Loop and the post parent will be grabbed for from the current post.
 944   *
 945   * The 'post_parent' argument is the ID to get the children. The 'numberposts'
 946   * is the amount of posts to retrieve that has a default of '-1', which is
 947   * used to get all of the posts. Giving a number higher than 0 will only
 948   * retrieve that amount of posts.
 949   *
 950   * The 'post_type' and 'post_status' arguments can be used to choose what
 951   * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
 952   * post types are 'post', 'pages', and 'attachments'. The 'post_status'
 953   * argument will accept any post status within the write administration panels.
 954   *
 955   * @since 2.0.0
 956   *
 957   * @see get_posts()
 958   * @todo Check validity of description.
 959   *
 960   * @global WP_Post $post Global post object.
 961   *
 962   * @param mixed  $args   Optional. User defined arguments for replacing the defaults. Default empty.
 963   * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 964   *                       correspond to a WP_Post object, an associative array, or a numeric array,
 965   *                       respectively. Default OBJECT.
 966   * @return WP_Post[]|array[]|int[] Array of post objects, arrays, or IDs, depending on `$output`.
 967   */
 968  function get_children( $args = '', $output = OBJECT ) {
 969      $kids = array();
 970      if ( empty( $args ) ) {
 971          if ( isset( $GLOBALS['post'] ) ) {
 972              $args = array( 'post_parent' => (int) $GLOBALS['post']->post_parent );
 973          } else {
 974              return $kids;
 975          }
 976      } elseif ( is_object( $args ) ) {
 977          $args = array( 'post_parent' => (int) $args->post_parent );
 978      } elseif ( is_numeric( $args ) ) {
 979          $args = array( 'post_parent' => (int) $args );
 980      }
 981  
 982      $defaults = array(
 983          'numberposts' => -1,
 984          'post_type'   => 'any',
 985          'post_status' => 'any',
 986          'post_parent' => 0,
 987      );
 988  
 989      $parsed_args = wp_parse_args( $args, $defaults );
 990  
 991      $children = get_posts( $parsed_args );
 992  
 993      if ( ! $children ) {
 994          return $kids;
 995      }
 996  
 997      if ( ! empty( $parsed_args['fields'] ) ) {
 998          return $children;
 999      }
1000  
1001      update_post_cache( $children );
1002  
1003      foreach ( $children as $key => $child ) {
1004          $kids[ $child->ID ] = $children[ $key ];
1005      }
1006  
1007      if ( OBJECT === $output ) {
1008          return $kids;
1009      } elseif ( ARRAY_A === $output ) {
1010          $weeuns = array();
1011          foreach ( (array) $kids as $kid ) {
1012              $weeuns[ $kid->ID ] = get_object_vars( $kids[ $kid->ID ] );
1013          }
1014          return $weeuns;
1015      } elseif ( ARRAY_N === $output ) {
1016          $babes = array();
1017          foreach ( (array) $kids as $kid ) {
1018              $babes[ $kid->ID ] = array_values( get_object_vars( $kids[ $kid->ID ] ) );
1019          }
1020          return $babes;
1021      } else {
1022          return $kids;
1023      }
1024  }
1025  
1026  /**
1027   * Gets extended entry info (<!--more-->).
1028   *
1029   * There should not be any space after the second dash and before the word
1030   * 'more'. There can be text or space(s) after the word 'more', but won't be
1031   * referenced.
1032   *
1033   * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
1034   * the `<!--more-->`. The 'extended' key has the content after the
1035   * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
1036   *
1037   * @since 1.0.0
1038   *
1039   * @param string $post Post content.
1040   * @return string[] {
1041   *     Extended entry info.
1042   *
1043   *     @type string $main      Content before the more tag.
1044   *     @type string $extended  Content after the more tag.
1045   *     @type string $more_text Custom read more text, or empty string.
1046   * }
1047   */
1048  function get_extended( $post ) {
1049      // Match the new style more links.
1050      if ( preg_match( '/<!--more(.*?)?-->/', $post, $matches ) ) {
1051          list($main, $extended) = explode( $matches[0], $post, 2 );
1052          $more_text             = $matches[1];
1053      } else {
1054          $main      = $post;
1055          $extended  = '';
1056          $more_text = '';
1057      }
1058  
1059      // Leading and trailing whitespace.
1060      $main      = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $main );
1061      $extended  = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $extended );
1062      $more_text = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $more_text );
1063  
1064      return array(
1065          'main'      => $main,
1066          'extended'  => $extended,
1067          'more_text' => $more_text,
1068      );
1069  }
1070  
1071  /**
1072   * Retrieves post data given a post ID or post object.
1073   *
1074   * See sanitize_post() for optional $filter values. Also, the parameter
1075   * `$post`, must be given as a variable, since it is passed by reference.
1076   *
1077   * @since 1.5.1
1078   *
1079   * @global WP_Post $post Global post object.
1080   *
1081   * @param int|WP_Post|null $post   Optional. Post ID or post object. `null`, `false`, `0` and other PHP falsey values
1082   *                                 return the current global post inside the loop. A numerically valid post ID that
1083   *                                 points to a non-existent post returns `null`. Defaults to global $post.
1084   * @param string           $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
1085   *                                 correspond to a WP_Post object, an associative array, or a numeric array,
1086   *                                 respectively. Default OBJECT.
1087   * @param string           $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
1088   *                                 or 'display'. Default 'raw'.
1089   * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
1090   *                            When $output is OBJECT, a `WP_Post` instance is returned.
1091   */
1092  function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
1093      if ( empty( $post ) && isset( $GLOBALS['post'] ) ) {
1094          $post = $GLOBALS['post'];
1095      }
1096  
1097      if ( $post instanceof WP_Post ) {
1098          $_post = $post;
1099      } elseif ( is_object( $post ) ) {
1100          if ( empty( $post->filter ) ) {
1101              $_post = sanitize_post( $post, 'raw' );
1102              $_post = new WP_Post( $_post );
1103          } elseif ( 'raw' === $post->filter ) {
1104              $_post = new WP_Post( $post );
1105          } else {
1106              $_post = WP_Post::get_instance( $post->ID );
1107          }
1108      } else {
1109          $_post = WP_Post::get_instance( $post );
1110      }
1111  
1112      if ( ! $_post ) {
1113          return null;
1114      }
1115  
1116      $_post = $_post->filter( $filter );
1117  
1118      if ( ARRAY_A === $output ) {
1119          return $_post->to_array();
1120      } elseif ( ARRAY_N === $output ) {
1121          return array_values( $_post->to_array() );
1122      }
1123  
1124      return $_post;
1125  }
1126  
1127  /**
1128   * Retrieves the IDs of the ancestors of a post.
1129   *
1130   * @since 2.5.0
1131   *
1132   * @param int|WP_Post $post Post ID or post object.
1133   * @return int[] Array of ancestor IDs or empty array if there are none.
1134   */
1135  function get_post_ancestors( $post ) {
1136      $post = get_post( $post );
1137  
1138      if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID ) {
1139          return array();
1140      }
1141  
1142      $ancestors = array();
1143  
1144      $id          = $post->post_parent;
1145      $ancestors[] = $id;
1146  
1147      while ( $ancestor = get_post( $id ) ) {
1148          // Loop detection: If the ancestor has been seen before, break.
1149          if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors, true ) ) {
1150              break;
1151          }
1152  
1153          $id          = $ancestor->post_parent;
1154          $ancestors[] = $id;
1155      }
1156  
1157      return $ancestors;
1158  }
1159  
1160  /**
1161   * Retrieves data from a post field based on Post ID.
1162   *
1163   * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
1164   * etc and based off of the post object property or key names.
1165   *
1166   * The context values are based off of the taxonomy filter functions and
1167   * supported values are found within those functions.
1168   *
1169   * @since 2.3.0
1170   * @since 4.5.0 The `$post` parameter was made optional.
1171   *
1172   * @see sanitize_post_field()
1173   *
1174   * @param string      $field   Post field name.
1175   * @param int|WP_Post $post    Optional. Post ID or post object. Defaults to global $post.
1176   * @param string      $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
1177   *                             or 'display'. Default 'display'.
1178   * @return string The value of the post field on success, empty string on failure.
1179   */
1180  function get_post_field( $field, $post = null, $context = 'display' ) {
1181      $post = get_post( $post );
1182  
1183      if ( ! $post ) {
1184          return '';
1185      }
1186  
1187      if ( ! isset( $post->$field ) ) {
1188          return '';
1189      }
1190  
1191      return sanitize_post_field( $field, $post->$field, $post->ID, $context );
1192  }
1193  
1194  /**
1195   * Retrieves the mime type of an attachment based on the ID.
1196   *
1197   * This function can be used with any post type, but it makes more sense with
1198   * attachments.
1199   *
1200   * @since 2.0.0
1201   *
1202   * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
1203   * @return string|false The mime type on success, false on failure.
1204   */
1205  function get_post_mime_type( $post = null ) {
1206      $post = get_post( $post );
1207  
1208      if ( is_object( $post ) ) {
1209          return $post->post_mime_type;
1210      }
1211  
1212      return false;
1213  }
1214  
1215  /**
1216   * Retrieves the post status based on the post ID.
1217   *
1218   * If the post ID is of an attachment, then the parent post status will be given
1219   * instead.
1220   *
1221   * @since 2.0.0
1222   *
1223   * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
1224   * @return string|false Post status on success, false on failure.
1225   */
1226  function get_post_status( $post = null ) {
1227      // Normalize the post object if necessary, skip normalization if called from get_sample_permalink().
1228      if ( ! $post instanceof WP_Post || ! isset( $post->filter ) || 'sample' !== $post->filter ) {
1229          $post = get_post( $post );
1230      }
1231  
1232      if ( ! is_object( $post ) ) {
1233          return false;
1234      }
1235  
1236      $post_status = $post->post_status;
1237  
1238      if (
1239          'attachment' === $post->post_type &&
1240          'inherit' === $post_status
1241      ) {
1242          if (
1243              0 === $post->post_parent ||
1244              ! get_post( $post->post_parent ) ||
1245              $post->ID === $post->post_parent
1246          ) {
1247              // Unattached attachments with inherit status are assumed to be published.
1248              $post_status = 'publish';
1249          } elseif ( 'trash' === get_post_status( $post->post_parent ) ) {
1250              // Get parent status prior to trashing.
1251              $post_status = get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
1252  
1253              if ( ! $post_status ) {
1254                  // Assume publish as above.
1255                  $post_status = 'publish';
1256              }
1257          } else {
1258              $post_status = get_post_status( $post->post_parent );
1259          }
1260      } elseif (
1261          'attachment' === $post->post_type &&
1262          ! in_array( $post_status, array( 'private', 'trash', 'auto-draft' ), true )
1263      ) {
1264          /*
1265           * Ensure uninherited attachments have a permitted status either 'private', 'trash', 'auto-draft'.
1266           * This is to match the logic in wp_insert_post().
1267           *
1268           * Note: 'inherit' is excluded from this check as it is resolved to the parent post's
1269           * status in the logic block above.
1270           */
1271          $post_status = 'publish';
1272      }
1273  
1274      /**
1275       * Filters the post status.
1276       *
1277       * @since 4.4.0
1278       * @since 5.7.0 The attachment post type is now passed through this filter.
1279       *
1280       * @param string  $post_status The post status.
1281       * @param WP_Post $post        The post object.
1282       */
1283      return apply_filters( 'get_post_status', $post_status, $post );
1284  }
1285  
1286  /**
1287   * Retrieves all of the WordPress supported post statuses.
1288   *
1289   * Posts have a limited set of valid status values, this provides the
1290   * post_status values and descriptions.
1291   *
1292   * @since 2.5.0
1293   *
1294   * @return string[] Array of post status labels keyed by their status.
1295   */
1296  function get_post_statuses() {
1297      $status = array(
1298          'draft'   => __( 'Draft' ),
1299          'pending' => __( 'Pending Review' ),
1300          'private' => __( 'Private' ),
1301          'publish' => __( 'Published' ),
1302      );
1303  
1304      return $status;
1305  }
1306  
1307  /**
1308   * Retrieves all of the WordPress support page statuses.
1309   *
1310   * Pages have a limited set of valid status values, this provides the
1311   * post_status values and descriptions.
1312   *
1313   * @since 2.5.0
1314   *
1315   * @return string[] Array of page status labels keyed by their status.
1316   */
1317  function get_page_statuses() {
1318      $status = array(
1319          'draft'   => __( 'Draft' ),
1320          'private' => __( 'Private' ),
1321          'publish' => __( 'Published' ),
1322      );
1323  
1324      return $status;
1325  }
1326  
1327  /**
1328   * Returns statuses for privacy requests.
1329   *
1330   * @since 4.9.6
1331   * @access private
1332   *
1333   * @return string[] Array of privacy request status labels keyed by their status.
1334   */
1335  function _wp_privacy_statuses() {
1336      return array(
1337          'request-pending'   => _x( 'Pending', 'request status' ),      // Pending confirmation from user.
1338          'request-confirmed' => _x( 'Confirmed', 'request status' ),    // User has confirmed the action.
1339          'request-failed'    => _x( 'Failed', 'request status' ),       // User failed to confirm the action.
1340          'request-completed' => _x( 'Completed', 'request status' ),    // Admin has handled the request.
1341      );
1342  }
1343  
1344  /**
1345   * Registers a post status. Do not use before init.
1346   *
1347   * A simple function for creating or modifying a post status based on the
1348   * parameters given. The function will accept an array (second optional
1349   * parameter), along with a string for the post status name.
1350   *
1351   * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
1352   *
1353   * @since 3.0.0
1354   *
1355   * @global stdClass[] $wp_post_statuses Inserts new post status object into the list
1356   *
1357   * @param string       $post_status Name of the post status.
1358   * @param array|string $args {
1359   *     Optional. Array or string of post status arguments.
1360   *
1361   *     @type bool|string $label                     A descriptive name for the post status marked
1362   *                                                  for translation. Defaults to value of $post_status.
1363   *     @type array|false $label_count               Nooped plural text from _n_noop() to provide the singular
1364   *                                                  and plural forms of the label for counts. Default false
1365   *                                                  which means the `$label` argument will be used for both
1366   *                                                  the singular and plural forms of this label.
1367   *     @type bool        $exclude_from_search       Whether to exclude posts with this post status
1368   *                                                  from search results. Default is value of $internal.
1369   *     @type bool        $_builtin                  Whether the status is built-in. Core-use only.
1370   *                                                  Default false.
1371   *     @type bool        $public                    Whether posts of this status should be shown
1372   *                                                  in the front end of the site. Default false.
1373   *     @type bool        $internal                  Whether the status is for internal use only.
1374   *                                                  Default false.
1375   *     @type bool        $protected                 Whether posts with this status should be protected.
1376   *                                                  Default false.
1377   *     @type bool        $private                   Whether posts with this status should be private.
1378   *                                                  Default false.
1379   *     @type bool        $publicly_queryable        Whether posts with this status should be publicly-
1380   *                                                  queryable. Default is value of $public.
1381   *     @type bool        $show_in_admin_all_list    Whether to include posts in the edit listing for
1382   *                                                  their post type. Default is the opposite value
1383   *                                                  of $internal.
1384   *     @type bool        $show_in_admin_status_list Show in the list of statuses with post counts at
1385   *                                                  the top of the edit listings,
1386   *                                                  e.g. All (12) | Published (9) | My Custom Status (2)
1387   *                                                  Default is the opposite value of $internal.
1388   *     @type bool        $date_floating             Whether the post has a floating creation date.
1389   *                                                  Default to false.
1390   * }
1391   * @return object
1392   */
1393  function register_post_status( $post_status, $args = array() ) {
1394      global $wp_post_statuses;
1395  
1396      if ( ! is_array( $wp_post_statuses ) ) {
1397          $wp_post_statuses = array();
1398      }
1399  
1400      // Args prefixed with an underscore are reserved for internal use.
1401      $defaults = array(
1402          'label'                     => false,
1403          'label_count'               => false,
1404          'exclude_from_search'       => null,
1405          '_builtin'                  => false,
1406          'public'                    => null,
1407          'internal'                  => null,
1408          'protected'                 => null,
1409          'private'                   => null,
1410          'publicly_queryable'        => null,
1411          'show_in_admin_status_list' => null,
1412          'show_in_admin_all_list'    => null,
1413          'date_floating'             => null,
1414      );
1415      $args     = wp_parse_args( $args, $defaults );
1416      $args     = (object) $args;
1417  
1418      $post_status = sanitize_key( $post_status );
1419      $args->name  = $post_status;
1420  
1421      // Set various defaults.
1422      if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private ) {
1423          $args->internal = true;
1424      }
1425  
1426      if ( null === $args->public ) {
1427          $args->public = false;
1428      }
1429  
1430      if ( null === $args->private ) {
1431          $args->private = false;
1432      }
1433  
1434      if ( null === $args->protected ) {
1435          $args->protected = false;
1436      }
1437  
1438      if ( null === $args->internal ) {
1439          $args->internal = false;
1440      }
1441  
1442      if ( null === $args->publicly_queryable ) {
1443          $args->publicly_queryable = $args->public;
1444      }
1445  
1446      if ( null === $args->exclude_from_search ) {
1447          $args->exclude_from_search = $args->internal;
1448      }
1449  
1450      if ( null === $args->show_in_admin_all_list ) {
1451          $args->show_in_admin_all_list = ! $args->internal;
1452      }
1453  
1454      if ( null === $args->show_in_admin_status_list ) {
1455          $args->show_in_admin_status_list = ! $args->internal;
1456      }
1457  
1458      if ( null === $args->date_floating ) {
1459          $args->date_floating = false;
1460      }
1461  
1462      if ( false === $args->label ) {
1463          $args->label = $post_status;
1464      }
1465  
1466      if ( false === $args->label_count ) {
1467          // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralSingular,WordPress.WP.I18n.NonSingularStringLiteralPlural
1468          $args->label_count = _n_noop( $args->label, $args->label );
1469      }
1470  
1471      $wp_post_statuses[ $post_status ] = $args;
1472  
1473      return $args;
1474  }
1475  
1476  /**
1477   * Retrieves a post status object by name.
1478   *
1479   * @since 3.0.0
1480   *
1481   * @global stdClass[] $wp_post_statuses List of post statuses.
1482   *
1483   * @see register_post_status()
1484   *
1485   * @param string $post_status The name of a registered post status.
1486   * @return stdClass|null A post status object.
1487   */
1488  function get_post_status_object( $post_status ) {
1489      global $wp_post_statuses;
1490  
1491      if ( empty( $wp_post_statuses[ $post_status ] ) ) {
1492          return null;
1493      }
1494  
1495      return $wp_post_statuses[ $post_status ];
1496  }
1497  
1498  /**
1499   * Gets a list of post statuses.
1500   *
1501   * @since 3.0.0
1502   *
1503   * @global stdClass[] $wp_post_statuses List of post statuses.
1504   *
1505   * @see register_post_status()
1506   *
1507   * @param array|string $args     Optional. Array or string of post status arguments to compare against
1508   *                               properties of the global `$wp_post_statuses objects`. Default empty array.
1509   * @param string       $output   Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
1510   * @param string       $operator Optional. The logical operation to perform. 'or' means only one element
1511   *                               from the array needs to match; 'and' means all elements must match.
1512   *                               Default 'and'.
1513   * @return string[]|stdClass[] A list of post status names or objects.
1514   */
1515  function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
1516      global $wp_post_statuses;
1517  
1518      $field = ( 'names' === $output ) ? 'name' : false;
1519  
1520      return wp_filter_object_list( $wp_post_statuses, $args, $operator, $field );
1521  }
1522  
1523  /**
1524   * Determines whether the post type is hierarchical.
1525   *
1526   * A false return value might also mean that the post type does not exist.
1527   *
1528   * @since 3.0.0
1529   *
1530   * @see get_post_type_object()
1531   *
1532   * @param string $post_type Post type name
1533   * @return bool Whether post type is hierarchical.
1534   */
1535  function is_post_type_hierarchical( $post_type ) {
1536      if ( ! post_type_exists( $post_type ) ) {
1537          return false;
1538      }
1539  
1540      $post_type = get_post_type_object( $post_type );
1541      return $post_type->hierarchical;
1542  }
1543  
1544  /**
1545   * Determines whether a post type is registered.
1546   *
1547   * For more information on this and similar theme functions, check out
1548   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1549   * Conditional Tags} article in the Theme Developer Handbook.
1550   *
1551   * @since 3.0.0
1552   *
1553   * @see get_post_type_object()
1554   *
1555   * @param string $post_type Post type name.
1556   * @return bool Whether post type is registered.
1557   */
1558  function post_type_exists( $post_type ) {
1559      return (bool) get_post_type_object( $post_type );
1560  }
1561  
1562  /**
1563   * Retrieves the post type of the current post or of a given post.
1564   *
1565   * @since 2.1.0
1566   *
1567   * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
1568   * @return string|false          Post type on success, false on failure.
1569   */
1570  function get_post_type( $post = null ) {
1571      $post = get_post( $post );
1572      if ( $post ) {
1573          return $post->post_type;
1574      }
1575  
1576      return false;
1577  }
1578  
1579  /**
1580   * Retrieves a post type object by name.
1581   *
1582   * @since 3.0.0
1583   * @since 4.6.0 Object returned is now an instance of `WP_Post_Type`.
1584   *
1585   * @global array $wp_post_types List of post types.
1586   *
1587   * @see register_post_type()
1588   *
1589   * @param string $post_type The name of a registered post type.
1590   * @return WP_Post_Type|null WP_Post_Type object if it exists, null otherwise.
1591   */
1592  function get_post_type_object( $post_type ) {
1593      global $wp_post_types;
1594  
1595      if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
1596          return null;
1597      }
1598  
1599      return $wp_post_types[ $post_type ];
1600  }
1601  
1602  /**
1603   * Gets a list of all registered post type objects.
1604   *
1605   * @since 2.9.0
1606   *
1607   * @global array $wp_post_types List of post types.
1608   *
1609   * @see register_post_type() for accepted arguments.
1610   *
1611   * @param array|string $args     Optional. An array of key => value arguments to match against
1612   *                               the post type objects. Default empty array.
1613   * @param string       $output   Optional. The type of output to return. Either 'names'
1614   *                               or 'objects'. Default 'names'.
1615   * @param string       $operator Optional. The logical operation to perform. 'or' means only one
1616   *                               element from the array needs to match; 'and' means all elements
1617   *                               must match; 'not' means no elements may match. Default 'and'.
1618   * @return string[]|WP_Post_Type[] An array of post type names or objects.
1619   */
1620  function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
1621      global $wp_post_types;
1622  
1623      $field = ( 'names' === $output ) ? 'name' : false;
1624  
1625      return wp_filter_object_list( $wp_post_types, $args, $operator, $field );
1626  }
1627  
1628  /**
1629   * Registers a post type.
1630   *
1631   * Note: Post type registrations should not be hooked before the
1632   * {@see 'init'} action. Also, any taxonomy connections should be
1633   * registered via the `$taxonomies` argument to ensure consistency
1634   * when hooks such as {@see 'parse_query'} or {@see 'pre_get_posts'}
1635   * are used.
1636   *
1637   * Post types can support any number of built-in core features such
1638   * as meta boxes, custom fields, post thumbnails, post statuses,
1639   * comments, and more. See the `$supports` argument for a complete
1640   * list of supported features.
1641   *
1642   * @since 2.9.0
1643   * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
1644   * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing
1645   *              screen and post editing screen.
1646   * @since 4.6.0 Post type object returned is now an instance of `WP_Post_Type`.
1647   * @since 4.7.0 Introduced `show_in_rest`, `rest_base` and `rest_controller_class`
1648   *              arguments to register the post type in REST API.
1649   * @since 5.0.0 The `template` and `template_lock` arguments were added.
1650   * @since 5.3.0 The `supports` argument will now accept an array of arguments for a feature.
1651   * @since 5.9.0 The `rest_namespace` argument was added.
1652   *
1653   * @global array $wp_post_types List of post types.
1654   *
1655   * @param string       $post_type Post type key. Must not exceed 20 characters and may only contain
1656   *                                lowercase alphanumeric characters, dashes, and underscores. See sanitize_key().
1657   * @param array|string $args {
1658   *     Array or string of arguments for registering a post type.
1659   *
1660   *     @type string       $label                           Name of the post type shown in the menu. Usually plural.
1661   *                                                         Default is value of $labels['name'].
1662   *     @type string[]     $labels                          An array of labels for this post type. If not set, post
1663   *                                                         labels are inherited for non-hierarchical types and page
1664   *                                                         labels for hierarchical ones. See get_post_type_labels() for a full
1665   *                                                         list of supported labels.
1666   *     @type string       $description                     A short descriptive summary of what the post type is.
1667   *                                                         Default empty.
1668   *     @type bool         $public                          Whether a post type is intended for use publicly either via
1669   *                                                         the admin interface or by front-end users. While the default
1670   *                                                         settings of $exclude_from_search, $publicly_queryable, $show_ui,
1671   *                                                         and $show_in_nav_menus are inherited from $public, each does not
1672   *                                                         rely on this relationship and controls a very specific intention.
1673   *                                                         Default false.
1674   *     @type bool         $hierarchical                    Whether the post type is hierarchical (e.g. page). Default false.
1675   *     @type bool         $exclude_from_search             Whether to exclude posts with this post type from front end search
1676   *                                                         results. Default is the opposite value of $public.
1677   *     @type bool         $publicly_queryable              Whether queries can be performed on the front end for the post type
1678   *                                                         as part of parse_request(). Endpoints would include:
1679   *                                                          * ?post_type={post_type_key}
1680   *                                                          * ?{post_type_key}={single_post_slug}
1681   *                                                          * ?{post_type_query_var}={single_post_slug}
1682   *                                                         If not set, the default is inherited from $public.
1683   *     @type bool         $show_ui                         Whether to generate and allow a UI for managing this post type in the
1684   *                                                         admin. Default is value of $public.
1685   *     @type bool|string  $show_in_menu                    Where to show the post type in the admin menu. To work, $show_ui
1686   *                                                         must be true. If true, the post type is shown in its own top level
1687   *                                                         menu. If false, no menu is shown. If a string of an existing top
1688   *                                                         level menu ('tools.php' or 'edit.php?post_type=page', for example), the
1689   *                                                         post type will be placed as a sub-menu of that.
1690   *                                                         Default is value of $show_ui.
1691   *     @type bool         $show_in_nav_menus               Makes this post type available for selection in navigation menus.
1692   *                                                         Default is value of $public.
1693   *     @type bool         $show_in_admin_bar               Makes this post type available via the admin bar. Default is value
1694   *                                                         of $show_in_menu.
1695   *     @type bool         $show_in_rest                    Whether to include the post type in the REST API. Set this to true
1696   *                                                         for the post type to be available in the block editor.
1697   *     @type string       $rest_base                       To change the base URL of REST API route. Default is $post_type.
1698   *     @type string       $rest_namespace                  To change the namespace URL of REST API route. Default is wp/v2.
1699   *     @type string       $rest_controller_class           REST API controller class name. Default is 'WP_REST_Posts_Controller'.
1700   *     @type string|bool  $autosave_rest_controller_class  REST API controller class name. Default is 'WP_REST_Autosaves_Controller'.
1701   *     @type string|bool  $revisions_rest_controller_class REST API controller class name. Default is 'WP_REST_Revisions_Controller'.
1702   *     @type bool         $late_route_registration         A flag to direct the REST API controllers for autosave / revisions
1703   *                                                         should be registered before/after the post type controller.
1704   *     @type int          $menu_position                   The position in the menu order the post type should appear. To work,
1705   *                                                         $show_in_menu must be true. Default null (at the bottom).
1706   *     @type string       $menu_icon                       The URL to the icon to be used for this menu. Pass a base64-encoded
1707   *                                                         SVG using a data URI, which will be colored to match the color scheme
1708   *                                                         -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
1709   *                                                         of a Dashicons helper class to use a font icon, e.g.
1710   *                                                        'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
1711   *                                                         so an icon can be added via CSS. Defaults to use the posts icon.
1712   *     @type string|array $capability_type                 The string to use to build the read, edit, and delete capabilities.
1713   *                                                         May be passed as an array to allow for alternative plurals when using
1714   *                                                         this argument as a base to construct the capabilities, e.g.
1715   *                                                         array('story', 'stories'). Default 'post'.
1716   *     @type string[]     $capabilities                    Array of capabilities for this post type. $capability_type is used
1717   *                                                         as a base to construct capabilities by default.
1718   *                                                         See get_post_type_capabilities().
1719   *     @type bool         $map_meta_cap                    Whether to use the internal default meta capability handling.
1720   *                                                         Default false.
1721   *     @type array|false  $supports                        Core feature(s) the post type supports. Serves as an alias for calling
1722   *                                                         add_post_type_support() directly. Core features include 'title',
1723   *                                                         'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt',
1724   *                                                         'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'.
1725   *                                                         Additionally, the 'revisions' feature dictates whether the post type
1726   *                                                         will store revisions, the 'autosave' feature dictates whether the post type
1727   *                                                         will be autosaved, and the 'comments' feature dictates whether the
1728   *                                                         comments count will show on the edit screen. For backward compatibility reasons,
1729   *                                                         adding 'editor' support implies 'autosave' support too. A feature can also be
1730   *                                                         specified as an array of arguments to provide additional information
1731   *                                                         about supporting that feature.
1732   *                                                         Example: `array( 'my_feature', array( 'field' => 'value' ) )`.
1733   *                                                         If false, no features will be added.
1734   *                                                         Default is an array containing 'title' and 'editor'.
1735   *     @type callable     $register_meta_box_cb            Provide a callback function that sets up the meta boxes for the
1736   *                                                         edit form. Do remove_meta_box() and add_meta_box() calls in the
1737   *                                                         callback. Default null.
1738   *     @type string[]     $taxonomies                      An array of taxonomy identifiers that will be registered for the
1739   *                                                         post type. Taxonomies can be registered later with register_taxonomy()
1740   *                                                         or register_taxonomy_for_object_type().
1741   *                                                         Default empty array.
1742   *     @type bool|string  $has_archive                     Whether there should be post type archives, or if a string, the
1743   *                                                         archive slug to use. Will generate the proper rewrite rules if
1744   *                                                         $rewrite is enabled. Default false.
1745   *     @type bool|array   $rewrite                         {
1746   *         Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
1747   *         Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
1748   *         passed with any of these keys:
1749   *
1750   *         @type string $slug       Customize the permastruct slug. Defaults to $post_type key.
1751   *         @type bool   $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
1752   *                                  Default true.
1753   *         @type bool   $feeds      Whether the feed permastruct should be built for this post type.
1754   *                                  Default is value of $has_archive.
1755   *         @type bool   $pages      Whether the permastruct should provide for pagination. Default true.
1756   *         @type int    $ep_mask    Endpoint mask to assign. If not specified and permalink_epmask is set,
1757   *                                  inherits from $permalink_epmask. If not specified and permalink_epmask
1758   *                                  is not set, defaults to EP_PERMALINK.
1759   *     }
1760   *     @type string|bool  $query_var                      Sets the query_var key for this post type. Defaults to $post_type
1761   *                                                        key. If false, a post type cannot be loaded at
1762   *                                                        ?{query_var}={post_slug}. If specified as a string, the query
1763   *                                                        ?{query_var_string}={post_slug} will be valid.
1764   *     @type bool         $can_export                     Whether to allow this post type to be exported. Default true.
1765   *     @type bool         $delete_with_user               Whether to delete posts of this type when deleting a user.
1766   *                                                          * If true, posts of this type belonging to the user will be moved
1767   *                                                            to Trash when the user is deleted.
1768   *                                                          * If false, posts of this type belonging to the user will *not*
1769   *                                                            be trashed or deleted.
1770   *                                                          * If not set (the default), posts are trashed if post type supports
1771   *                                                            the 'author' feature. Otherwise posts are not trashed or deleted.
1772   *                                                        Default null.
1773   *     @type array        $template                       Array of blocks to use as the default initial state for an editor
1774   *                                                        session. Each item should be an array containing block name and
1775   *                                                        optional attributes. Default empty array.
1776   *     @type string|false $template_lock                  Whether the block template should be locked if $template is set.
1777   *                                                        * If set to 'all', the user is unable to insert new blocks,
1778   *                                                          move existing blocks and delete blocks.
1779   *                                                       * If set to 'insert', the user is able to move existing blocks
1780   *                                                         but is unable to insert new blocks and delete blocks.
1781   *                                                         Default false.
1782   *     @type bool         $_builtin                     FOR INTERNAL USE ONLY! True if this post type is a native or
1783   *                                                      "built-in" post_type. Default false.
1784   *     @type string       $_edit_link                   FOR INTERNAL USE ONLY! URL segment to use for edit link of
1785   *                                                      this post type. Default 'post.php?post=%d'.
1786   * }
1787   * @return WP_Post_Type|WP_Error The registered post type object on success,
1788   *                               WP_Error object on failure.
1789   */
1790  function register_post_type( $post_type, $args = array() ) {
1791      global $wp_post_types;
1792  
1793      if ( ! is_array( $wp_post_types ) ) {
1794          $wp_post_types = array();
1795      }
1796  
1797      // Sanitize post type name.
1798      $post_type = sanitize_key( $post_type );
1799  
1800      if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1801          _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2.0' );
1802          return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1803      }
1804  
1805      $post_type_object = new WP_Post_Type( $post_type, $args );
1806      $post_type_object->add_supports();
1807      $post_type_object->add_rewrite_rules();
1808      $post_type_object->register_meta_boxes();
1809  
1810      $wp_post_types[ $post_type ] = $post_type_object;
1811  
1812      $post_type_object->add_hooks();
1813      $post_type_object->register_taxonomies();
1814  
1815      /**
1816       * Fires after a post type is registered.
1817       *
1818       * @since 3.3.0
1819       * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
1820       *
1821       * @param string       $post_type        Post type.
1822       * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1823       */
1824      do_action( 'registered_post_type', $post_type, $post_type_object );
1825  
1826      /**
1827       * Fires after a specific post type is registered.
1828       *
1829       * The dynamic portion of the filter name, `$post_type`, refers to the post type key.
1830       *
1831       * Possible hook names include:
1832       *
1833       *  - `registered_post_type_post`
1834       *  - `registered_post_type_page`
1835       *
1836       * @since 6.0.0
1837       *
1838       * @param string       $post_type        Post type.
1839       * @param WP_Post_Type $post_type_object Arguments used to register the post type.
1840       */
1841      do_action( "registered_post_type_{$post_type}", $post_type, $post_type_object );
1842  
1843      return $post_type_object;
1844  }
1845  
1846  /**
1847   * Unregisters a post type.
1848   *
1849   * Cannot be used to unregister built-in post types.
1850   *
1851   * @since 4.5.0
1852   *
1853   * @global array $wp_post_types List of post types.
1854   *
1855   * @param string $post_type Post type to unregister.
1856   * @return true|WP_Error True on success, WP_Error on failure or if the post type doesn't exist.
1857   */
1858  function unregister_post_type( $post_type ) {
1859      global $wp_post_types;
1860  
1861      if ( ! post_type_exists( $post_type ) ) {
1862          return new WP_Error( 'invalid_post_type', __( 'Invalid post type.' ) );
1863      }
1864  
1865      $post_type_object = get_post_type_object( $post_type );
1866  
1867      // Do not allow unregistering internal post types.
1868      if ( $post_type_object->_builtin ) {
1869          return new WP_Error( 'invalid_post_type', __( 'Unregistering a built-in post type is not allowed' ) );
1870      }
1871  
1872      $post_type_object->remove_supports();
1873      $post_type_object->remove_rewrite_rules();
1874      $post_type_object->unregister_meta_boxes();
1875      $post_type_object->remove_hooks();
1876      $post_type_object->unregister_taxonomies();
1877  
1878      unset( $wp_post_types[ $post_type ] );
1879  
1880      /**
1881       * Fires after a post type was unregistered.
1882       *
1883       * @since 4.5.0
1884       *
1885       * @param string $post_type Post type key.
1886       */
1887      do_action( 'unregistered_post_type', $post_type );
1888  
1889      return true;
1890  }
1891  
1892  /**
1893   * Builds an object with all post type capabilities out of a post type object
1894   *
1895   * Post type capabilities use the 'capability_type' argument as a base, if the
1896   * capability is not set in the 'capabilities' argument array or if the
1897   * 'capabilities' argument is not supplied.
1898   *
1899   * The capability_type argument can optionally be registered as an array, with
1900   * the first value being singular and the second plural, e.g. array('story, 'stories')
1901   * Otherwise, an 's' will be added to the value for the plural form. After
1902   * registration, capability_type will always be a string of the singular value.
1903   *
1904   * By default, eight keys are accepted as part of the capabilities array:
1905   *
1906   * - edit_post, read_post, and delete_post are meta capabilities, which are then
1907   *   generally mapped to corresponding primitive capabilities depending on the
1908   *   context, which would be the post being edited/read/deleted and the user or
1909   *   role being checked. Thus these capabilities would generally not be granted
1910   *   directly to users or roles.
1911   *
1912   * - edit_posts - Controls whether objects of this post type can be edited.
1913   * - edit_others_posts - Controls whether objects of this type owned by other users
1914   *   can be edited. If the post type does not support an author, then this will
1915   *   behave like edit_posts.
1916   * - delete_posts - Controls whether objects of this post type can be deleted.
1917   * - publish_posts - Controls publishing objects of this post type.
1918   * - read_private_posts - Controls whether private objects can be read.
1919   *
1920   * These five primitive capabilities are checked in core in various locations.
1921   * There are also six other primitive capabilities which are not referenced
1922   * directly in core, except in map_meta_cap(), which takes the three aforementioned
1923   * meta capabilities and translates them into one or more primitive capabilities
1924   * that must then be checked against the user or role, depending on the context.
1925   *
1926   * - read - Controls whether objects of this post type can be read.
1927   * - delete_private_posts - Controls whether private objects can be deleted.
1928   * - delete_published_posts - Controls whether published objects can be deleted.
1929   * - delete_others_posts - Controls whether objects owned by other users can be
1930   *   can be deleted. If the post type does not support an author, then this will
1931   *   behave like delete_posts.
1932   * - edit_private_posts - Controls whether private objects can be edited.
1933   * - edit_published_posts - Controls whether published objects can be edited.
1934   *
1935   * These additional capabilities are only used in map_meta_cap(). Thus, they are
1936   * only assigned by default if the post type is registered with the 'map_meta_cap'
1937   * argument set to true (default is false).
1938   *
1939   * @since 3.0.0
1940   * @since 5.4.0 'delete_posts' is included in default capabilities.
1941   *
1942   * @see register_post_type()
1943   * @see map_meta_cap()
1944   *
1945   * @param object $args Post type registration arguments.
1946   * @return object Object with all the capabilities as member variables.
1947   */
1948  function get_post_type_capabilities( $args ) {
1949      if ( ! is_array( $args->capability_type ) ) {
1950          $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1951      }
1952  
1953      // Singular base for meta capabilities, plural base for primitive capabilities.
1954      list( $singular_base, $plural_base ) = $args->capability_type;
1955  
1956      $default_capabilities = array(
1957          // Meta capabilities.
1958          'edit_post'          => 'edit_' . $singular_base,
1959          'read_post'          => 'read_' . $singular_base,
1960          'delete_post'        => 'delete_' . $singular_base,
1961          // Primitive capabilities used outside of map_meta_cap():
1962          'edit_posts'         => 'edit_' . $plural_base,
1963          'edit_others_posts'  => 'edit_others_' . $plural_base,
1964          'delete_posts'       => 'delete_' . $plural_base,
1965          'publish_posts'      => 'publish_' . $plural_base,
1966          'read_private_posts' => 'read_private_' . $plural_base,
1967      );
1968  
1969      // Primitive capabilities used within map_meta_cap():
1970      if ( $args->map_meta_cap ) {
1971          $default_capabilities_for_mapping = array(
1972              'read'                   => 'read',
1973              'delete_private_posts'   => 'delete_private_' . $plural_base,
1974              'delete_published_posts' => 'delete_published_' . $plural_base,
1975              'delete_others_posts'    => 'delete_others_' . $plural_base,
1976              'edit_private_posts'     => 'edit_private_' . $plural_base,
1977              'edit_published_posts'   => 'edit_published_' . $plural_base,
1978          );
1979          $default_capabilities             = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1980      }
1981  
1982      $capabilities = array_merge( $default_capabilities, $args->capabilities );
1983  
1984      // Post creation capability simply maps to edit_posts by default:
1985      if ( ! isset( $capabilities['create_posts'] ) ) {
1986          $capabilities['create_posts'] = $capabilities['edit_posts'];
1987      }
1988  
1989      // Remember meta capabilities for future reference.
1990      if ( $args->map_meta_cap ) {
1991          _post_type_meta_capabilities( $capabilities );
1992      }
1993  
1994      return (object) $capabilities;
1995  }
1996  
1997  /**
1998   * Stores or returns a list of post type meta caps for map_meta_cap().
1999   *
2000   * @since 3.1.0
2001   * @access private
2002   *
2003   * @global array $post_type_meta_caps Used to store meta capabilities.
2004   *
2005   * @param string[] $capabilities Post type meta capabilities.
2006   */
2007  function _post_type_meta_capabilities( $capabilities = null ) {
2008      global $post_type_meta_caps;
2009  
2010      foreach ( $capabilities as $core => $custom ) {
2011          if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ), true ) ) {
2012              $post_type_meta_caps[ $custom ] = $core;
2013          }
2014      }
2015  }
2016  
2017  /**
2018   * Builds an object with all post type labels out of a post type object.
2019   *
2020   * Accepted keys of the label array in the post type object:
2021   *
2022   * - `name` - General name for the post type, usually plural. The same and overridden
2023   *          by `$post_type_object->label`. Default is 'Posts' / 'Pages'.
2024   * - `singular_name` - Name for one object of this post type. Default is 'Post' / 'Page'.
2025   * - `add_new` - Label for adding a new item. Default is 'Add New Post' / 'Add New Page'.
2026   * - `add_new_item` - Label for adding a new singular item. Default is 'Add New Post' / 'Add New Page'.
2027   * - `edit_item` - Label for editing a singular item. Default is 'Edit Post' / 'Edit Page'.
2028   * - `new_item` - Label for the new item page title. Default is 'New Post' / 'New Page'.
2029   * - `view_item` - Label for viewing a singular item. Default is 'View Post' / 'View Page'.
2030   * - `view_items` - Label for viewing post type archives. Default is 'View Posts' / 'View Pages'.
2031   * - `search_items` - Label for searching plural items. Default is 'Search Posts' / 'Search Pages'.
2032   * - `not_found` - Label used when no items are found. Default is 'No posts found' / 'No pages found'.
2033   * - `not_found_in_trash` - Label used when no items are in the Trash. Default is 'No posts found in Trash' /
2034   *                        'No pages found in Trash'.
2035   * - `parent_item_colon` - Label used to prefix parents of hierarchical items. Not used on non-hierarchical
2036   *                       post types. Default is 'Parent Page:'.
2037   * - `all_items` - Label to signify all items in a submenu link. Default is 'All Posts' / 'All Pages'.
2038   * - `archives` - Label for archives in nav menus. Default is 'Post Archives' / 'Page Archives'.
2039   * - `attributes` - Label for the attributes meta box. Default is 'Post Attributes' / 'Page Attributes'.
2040   * - `insert_into_item` - Label for the media frame button. Default is 'Insert into post' / 'Insert into page'.
2041   * - `uploaded_to_this_item` - Label for the media frame filter. Default is 'Uploaded to this post' /
2042   *                           'Uploaded to this page'.
2043   * - `featured_image` - Label for the featured image meta box title. Default is 'Featured image'.
2044   * - `set_featured_image` - Label for setting the featured image. Default is 'Set featured image'.
2045   * - `remove_featured_image` - Label for removing the featured image. Default is 'Remove featured image'.
2046   * - `use_featured_image` - Label in the media frame for using a featured image. Default is 'Use as featured image'.
2047   * - `menu_name` - Label for the menu name. Default is the same as `name`.
2048   * - `filter_items_list` - Label for the table views hidden heading. Default is 'Filter posts list' /
2049   *                       'Filter pages list'.
2050   * - `filter_by_date` - Label for the date filter in list tables. Default is 'Filter by date'.
2051   * - `items_list_navigation` - Label for the table pagination hidden heading. Default is 'Posts list navigation' /
2052   *                           'Pages list navigation'.
2053   * - `items_list` - Label for the table hidden heading. Default is 'Posts list' / 'Pages list'.
2054   * - `item_published` - Label used when an item is published. Default is 'Post published.' / 'Page published.'
2055   * - `item_published_privately` - Label used when an item is published with private visibility.
2056   *                              Default is 'Post published privately.' / 'Page published privately.'
2057   * - `item_reverted_to_draft` - Label used when an item is switched to a draft.
2058   *                            Default is 'Post reverted to draft.' / 'Page reverted to draft.'
2059   * - `item_trashed` - Label used when an item is moved to Trash. Default is 'Post trashed.' / 'Page trashed.'
2060   * - `item_scheduled` - Label used when an item is scheduled for publishing. Default is 'Post scheduled.' /
2061   *                    'Page scheduled.'
2062   * - `item_updated` - Label used when an item is updated. Default is 'Post updated.' / 'Page updated.'
2063   * - `item_link` - Title for a navigation link block variation. Default is 'Post Link' / 'Page Link'.
2064   * - `item_link_description` - Description for a navigation link block variation. Default is 'A link to a post.' /
2065   *                             'A link to a page.'
2066   *
2067   * Above, the first default value is for non-hierarchical post types (like posts)
2068   * and the second one is for hierarchical post types (like pages).
2069   *
2070   * Note: To set labels used in post type admin notices, see the {@see 'post_updated_messages'} filter.
2071   *
2072   * @since 3.0.0
2073   * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
2074   *              and `use_featured_image` labels.
2075   * @since 4.4.0 Added the `archives`, `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
2076   *              `items_list_navigation`, and `items_list` labels.
2077   * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
2078   * @since 4.7.0 Added the `view_items` and `attributes` labels.
2079   * @since 5.0.0 Added the `item_published`, `item_published_privately`, `item_reverted_to_draft`,
2080   *              `item_scheduled`, and `item_updated` labels.
2081   * @since 5.7.0 Added the `filter_by_date` label.
2082   * @since 5.8.0 Added the `item_link` and `item_link_description` labels.
2083   * @since 6.3.0 Added the `item_trashed` label.
2084   * @since 6.4.0 Changed default values for the `add_new` label to include the type of content.
2085   *              This matches `add_new_item` and provides more context for better accessibility.
2086   * @since 6.6.0 Added the `template_name` label.
2087   *
2088   * @access private
2089   *
2090   * @param object|WP_Post_Type $post_type_object Post type object.
2091   * @return object Object with all the labels as member variables.
2092   */
2093  function get_post_type_labels( $post_type_object ) {
2094      $nohier_vs_hier_defaults = WP_Post_Type::get_default_labels();
2095  
2096      $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
2097  
2098      $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
2099  
2100      if ( ! isset( $post_type_object->labels->template_name ) && isset( $post_type_object->labels->singular_name ) ) {
2101              /* translators: %s: Post type name. */
2102              $labels->template_name = sprintf( __( 'Single item: %s' ), $post_type_object->labels->singular_name );
2103      }
2104  
2105      $post_type = $post_type_object->name;
2106  
2107      $default_labels = clone $labels;
2108  
2109      /**
2110       * Filters the labels of a specific post type.
2111       *
2112       * The dynamic portion of the hook name, `$post_type`, refers to
2113       * the post type slug.
2114       *
2115       * Possible hook names include:
2116       *
2117       *  - `post_type_labels_post`
2118       *  - `post_type_labels_page`
2119       *  - `post_type_labels_attachment`
2120       *
2121       * @since 3.5.0
2122       *
2123       * @see get_post_type_labels() for the full list of labels.
2124       *
2125       * @param object $labels Object with labels for the post type as member variables.
2126       */
2127      $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
2128  
2129      // Ensure that the filtered labels contain all required default values.
2130      $labels = (object) array_merge( (array) $default_labels, (array) $labels );
2131  
2132      return $labels;
2133  }
2134  
2135  /**
2136   * Builds an object with custom-something object (post type, taxonomy) labels
2137   * out of a custom-something object
2138   *
2139   * @since 3.0.0
2140   * @access private
2141   *
2142   * @param object $data_object             A custom-something object.
2143   * @param array  $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
2144   * @return object Object containing labels for the given custom-something object.
2145   */
2146  function _get_custom_object_labels( $data_object, $nohier_vs_hier_defaults ) {
2147      $data_object->labels = (array) $data_object->labels;
2148  
2149      if ( isset( $data_object->label ) && empty( $data_object->labels['name'] ) ) {
2150          $data_object->labels['name'] = $data_object->label;
2151      }
2152  
2153      if ( ! isset( $data_object->labels['singular_name'] ) && isset( $data_object->labels['name'] ) ) {
2154          $data_object->labels['singular_name'] = $data_object->labels['name'];
2155      }
2156  
2157      if ( ! isset( $data_object->labels['name_admin_bar'] ) ) {
2158          $data_object->labels['name_admin_bar'] =
2159              isset( $data_object->labels['singular_name'] )
2160              ? $data_object->labels['singular_name']
2161              : $data_object->name;
2162      }
2163  
2164      if ( ! isset( $data_object->labels['menu_name'] ) && isset( $data_object->labels['name'] ) ) {
2165          $data_object->labels['menu_name'] = $data_object->labels['name'];
2166      }
2167  
2168      if ( ! isset( $data_object->labels['all_items'] ) && isset( $data_object->labels['menu_name'] ) ) {
2169          $data_object->labels['all_items'] = $data_object->labels['menu_name'];
2170      }
2171  
2172      if ( ! isset( $data_object->labels['archives'] ) && isset( $data_object->labels['all_items'] ) ) {
2173          $data_object->labels['archives'] = $data_object->labels['all_items'];
2174      }
2175  
2176      $defaults = array();
2177      foreach ( $nohier_vs_hier_defaults as $key => $value ) {
2178          $defaults[ $key ] = $data_object->hierarchical ? $value[1] : $value[0];
2179      }
2180  
2181      $labels              = array_merge( $defaults, $data_object->labels );
2182      $data_object->labels = (object) $data_object->labels;
2183  
2184      return (object) $labels;
2185  }
2186  
2187  /**
2188   * Adds submenus for post types.
2189   *
2190   * @access private
2191   * @since 3.1.0
2192   */
2193  function _add_post_type_submenus() {
2194      foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
2195          $ptype_obj = get_post_type_object( $ptype );
2196          // Sub-menus only.
2197          if ( ! $ptype_obj->show_in_menu || true === $ptype_obj->show_in_menu ) {
2198              continue;
2199          }
2200          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" );
2201      }
2202  }
2203  
2204  /**
2205   * Registers support of certain features for a post type.
2206   *
2207   * All core features are directly associated with a functional area of the edit
2208   * screen, such as the editor or a meta box. Features include: 'title', 'editor',
2209   * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
2210   * 'thumbnail', 'custom-fields', and 'post-formats'.
2211   *
2212   * Additionally, the 'revisions' feature dictates whether the post type will
2213   * store revisions, the 'autosave' feature dictates whether the post type
2214   * will be autosaved, and the 'comments' feature dictates whether the comments
2215   * count will show on the edit screen.
2216   *
2217   * A third, optional parameter can also be passed along with a feature to provide
2218   * additional information about supporting that feature.
2219   *
2220   * Example usage:
2221   *
2222   *     add_post_type_support( 'my_post_type', 'comments' );
2223   *     add_post_type_support( 'my_post_type', array(
2224   *         'author', 'excerpt',
2225   *     ) );
2226   *     add_post_type_support( 'my_post_type', 'my_feature', array(
2227   *         'field' => 'value',
2228   *     ) );
2229   *
2230   * @since 3.0.0
2231   * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
2232   *              by adding it to the function signature.
2233   *
2234   * @global array $_wp_post_type_features
2235   *
2236   * @param string       $post_type The post type for which to add the feature.
2237   * @param string|array $feature   The feature being added, accepts an array of
2238   *                                feature strings or a single string.
2239   * @param mixed        ...$args   Optional extra arguments to pass along with certain features.
2240   */
2241  function add_post_type_support( $post_type, $feature, ...$args ) {
2242      global $_wp_post_type_features;
2243  
2244      $features = (array) $feature;
2245      foreach ( $features as $feature ) {
2246          if ( $args ) {
2247              $_wp_post_type_features[ $post_type ][ $feature ] = $args;
2248          } else {
2249              $_wp_post_type_features[ $post_type ][ $feature ] = true;
2250          }
2251      }
2252  }
2253  
2254  /**
2255   * Removes support for a feature from a post type.
2256   *
2257   * @since 3.0.0
2258   *
2259   * @global array $_wp_post_type_features
2260   *
2261   * @param string $post_type The post type for which to remove the feature.
2262   * @param string $feature   The feature being removed.
2263   */
2264  function remove_post_type_support( $post_type, $feature ) {
2265      global $_wp_post_type_features;
2266  
2267      unset( $_wp_post_type_features[ $post_type ][ $feature ] );
2268  }
2269  
2270  /**
2271   * Gets all the post type features
2272   *
2273   * @since 3.4.0
2274   *
2275   * @global array $_wp_post_type_features
2276   *
2277   * @param string $post_type The post type.
2278   * @return array Post type supports list.
2279   */
2280  function get_all_post_type_supports( $post_type ) {
2281      global $_wp_post_type_features;
2282  
2283      if ( isset( $_wp_post_type_features[ $post_type ] ) ) {
2284          return $_wp_post_type_features[ $post_type ];
2285      }
2286  
2287      return array();
2288  }
2289  
2290  /**
2291   * Checks a post type's support for a given feature.
2292   *
2293   * @since 3.0.0
2294   *
2295   * @global array $_wp_post_type_features
2296   *
2297   * @param string $post_type The post type being checked.
2298   * @param string $feature   The feature being checked.
2299   * @return bool Whether the post type supports the given feature.
2300   */
2301  function post_type_supports( $post_type, $feature ) {
2302      global $_wp_post_type_features;
2303  
2304      return ( isset( $_wp_post_type_features[ $post_type ][ $feature ] ) );
2305  }
2306  
2307  /**
2308   * Retrieves a list of post type names that support a specific feature.
2309   *
2310   * @since 4.5.0
2311   *
2312   * @global array $_wp_post_type_features Post type features
2313   *
2314   * @param array|string $feature  Single feature or an array of features the post types should support.
2315   * @param string       $operator Optional. The logical operation to perform. 'or' means
2316   *                               only one element from the array needs to match; 'and'
2317   *                               means all elements must match; 'not' means no elements may
2318   *                               match. Default 'and'.
2319   * @return string[] A list of post type names.
2320   */
2321  function get_post_types_by_support( $feature, $operator = 'and' ) {
2322      global $_wp_post_type_features;
2323  
2324      $features = array_fill_keys( (array) $feature, true );
2325  
2326      return array_keys( wp_filter_object_list( $_wp_post_type_features, $features, $operator ) );
2327  }
2328  
2329  /**
2330   * Updates the post type for the post ID.
2331   *
2332   * The page or post cache will be cleaned for the post ID.
2333   *
2334   * @since 2.5.0
2335   *
2336   * @global wpdb $wpdb WordPress database abstraction object.
2337   *
2338   * @param int    $post_id   Optional. Post ID to change post type. Default 0.
2339   * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
2340   *                          name a few. Default 'post'.
2341   * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
2342   */
2343  function set_post_type( $post_id = 0, $post_type = 'post' ) {
2344      global $wpdb;
2345  
2346      $post_type = sanitize_post_field( 'post_type', $post_type, $post_id, 'db' );
2347      $return    = $wpdb->update( $wpdb->posts, array( 'post_type' => $post_type ), array( 'ID' => $post_id ) );
2348  
2349      clean_post_cache( $post_id );
2350  
2351      return $return;
2352  }
2353  
2354  /**
2355   * Determines whether a post type is considered "viewable".
2356   *
2357   * For built-in post types such as posts and pages, the 'public' value will be evaluated.
2358   * For all others, the 'publicly_queryable' value will be used.
2359   *
2360   * @since 4.4.0
2361   * @since 4.5.0 Added the ability to pass a post type name in addition to object.
2362   * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
2363   * @since 5.9.0 Added `is_post_type_viewable` hook to filter the result.
2364   *
2365   * @param string|WP_Post_Type $post_type Post type name or object.
2366   * @return bool Whether the post type should be considered viewable.
2367   */
2368  function is_post_type_viewable( $post_type ) {
2369      if ( is_scalar( $post_type ) ) {
2370          $post_type = get_post_type_object( $post_type );
2371  
2372          if ( ! $post_type ) {
2373              return false;
2374          }
2375      }
2376  
2377      if ( ! is_object( $post_type ) ) {
2378          return false;
2379      }
2380  
2381      $is_viewable = $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
2382  
2383      /**
2384       * Filters whether a post type is considered "viewable".
2385       *
2386       * The returned filtered value must be a boolean type to ensure
2387       * `is_post_type_viewable()` only returns a boolean. This strictness
2388       * is by design to maintain backwards-compatibility and guard against
2389       * potential type errors in PHP 8.1+. Non-boolean values (even falsey
2390       * and truthy values) will result in the function returning false.
2391       *
2392       * @since 5.9.0
2393       *
2394       * @param bool         $is_viewable Whether the post type is "viewable" (strict type).
2395       * @param WP_Post_Type $post_type   Post type object.
2396       */
2397      return true === apply_filters( 'is_post_type_viewable', $is_viewable, $post_type );
2398  }
2399  
2400  /**
2401   * Determines whether a post status is considered "viewable".
2402   *
2403   * For built-in post statuses such as publish and private, the 'public' value will be evaluated.
2404   * For all others, the 'publicly_queryable' value will be used.
2405   *
2406   * @since 5.7.0
2407   * @since 5.9.0 Added `is_post_status_viewable` hook to filter the result.
2408   *
2409   * @param string|stdClass $post_status Post status name or object.
2410   * @return bool Whether the post status should be considered viewable.
2411   */
2412  function is_post_status_viewable( $post_status ) {
2413      if ( is_scalar( $post_status ) ) {
2414          $post_status = get_post_status_object( $post_status );
2415  
2416          if ( ! $post_status ) {
2417              return false;
2418          }
2419      }
2420  
2421      if (
2422          ! is_object( $post_status ) ||
2423          $post_status->internal ||
2424          $post_status->protected
2425      ) {
2426          return false;
2427      }
2428  
2429      $is_viewable = $post_status->publicly_queryable || ( $post_status->_builtin && $post_status->public );
2430  
2431      /**
2432       * Filters whether a post status is considered "viewable".
2433       *
2434       * The returned filtered value must be a boolean type to ensure
2435       * `is_post_status_viewable()` only returns a boolean. This strictness
2436       * is by design to maintain backwards-compatibility and guard against
2437       * potential type errors in PHP 8.1+. Non-boolean values (even falsey
2438       * and truthy values) will result in the function returning false.
2439       *
2440       * @since 5.9.0
2441       *
2442       * @param bool     $is_viewable Whether the post status is "viewable" (strict type).
2443       * @param stdClass $post_status Post status object.
2444       */
2445      return true === apply_filters( 'is_post_status_viewable', $is_viewable, $post_status );
2446  }
2447  
2448  /**
2449   * Determines whether a post is publicly viewable.
2450   *
2451   * Posts are considered publicly viewable if both the post status and post type
2452   * are viewable.
2453   *
2454   * @since 5.7.0
2455   *
2456   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2457   * @return bool Whether the post is publicly viewable.
2458   */
2459  function is_post_publicly_viewable( $post = null ) {
2460      $post = get_post( $post );
2461  
2462      if ( ! $post ) {
2463          return false;
2464      }
2465  
2466      $post_type   = get_post_type( $post );
2467      $post_status = get_post_status( $post );
2468  
2469      return is_post_type_viewable( $post_type ) && is_post_status_viewable( $post_status );
2470  }
2471  
2472  /**
2473   * Retrieves an array of the latest posts, or posts matching the given criteria.
2474   *
2475   * For more information on the accepted arguments, see the
2476   * {@link https://developer.wordpress.org/reference/classes/wp_query/
2477   * WP_Query} documentation in the Developer Handbook.
2478   *
2479   * The `$ignore_sticky_posts` and `$no_found_rows` arguments are ignored by
2480   * this function and both are set to `true`.
2481   *
2482   * The defaults are as follows:
2483   *
2484   * @since 1.2.0
2485   *
2486   * @see WP_Query
2487   * @see WP_Query::parse_query()
2488   *
2489   * @param array $args {
2490   *     Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all available arguments.
2491   *
2492   *     @type int        $numberposts      Total number of posts to retrieve. Is an alias of `$posts_per_page`
2493   *                                        in WP_Query. Accepts -1 for all. Default 5.
2494   *     @type int|string $category         Category ID or comma-separated list of IDs (this or any children).
2495   *                                        Is an alias of `$cat` in WP_Query. Default 0.
2496   *     @type int[]      $include          An array of post IDs to retrieve, sticky posts will be included.
2497   *                                        Is an alias of `$post__in` in WP_Query. Default empty array.
2498   *     @type int[]      $exclude          An array of post IDs not to retrieve. Default empty array.
2499   *     @type bool       $suppress_filters Whether to suppress filters. Default true.
2500   * }
2501   * @return WP_Post[]|int[] Array of post objects or post IDs.
2502   */
2503  function get_posts( $args = null ) {
2504      $defaults = array(
2505          'numberposts'      => 5,
2506          'category'         => 0,
2507          'orderby'          => 'date',
2508          'order'            => 'DESC',
2509          'include'          => array(),
2510          'exclude'          => array(),
2511          'meta_key'         => '',
2512          'meta_value'       => '',
2513          'post_type'        => 'post',
2514          'suppress_filters' => true,
2515      );
2516  
2517      $parsed_args = wp_parse_args( $args, $defaults );
2518      if ( empty( $parsed_args['post_status'] ) ) {
2519          $parsed_args['post_status'] = ( 'attachment' === $parsed_args['post_type'] ) ? 'inherit' : 'publish';
2520      }
2521      if ( ! empty( $parsed_args['numberposts'] ) && empty( $parsed_args['posts_per_page'] ) ) {
2522          $parsed_args['posts_per_page'] = $parsed_args['numberposts'];
2523      }
2524      if ( ! empty( $parsed_args['category'] ) ) {
2525          $parsed_args['cat'] = $parsed_args['category'];
2526      }
2527      if ( ! empty( $parsed_args['include'] ) ) {
2528          $incposts                      = wp_parse_id_list( $parsed_args['include'] );
2529          $parsed_args['posts_per_page'] = count( $incposts );  // Only the number of posts included.
2530          $parsed_args['post__in']       = $incposts;
2531      } elseif ( ! empty( $parsed_args['exclude'] ) ) {
2532          $parsed_args['post__not_in'] = wp_parse_id_list( $parsed_args['exclude'] );
2533      }
2534  
2535      $parsed_args['ignore_sticky_posts'] = true;
2536      $parsed_args['no_found_rows']       = true;
2537  
2538      $get_posts = new WP_Query();
2539      return $get_posts->query( $parsed_args );
2540  }
2541  
2542  //
2543  // Post meta functions.
2544  //
2545  
2546  /**
2547   * Adds a meta field to the given post.
2548   *
2549   * Post meta data is called "Custom Fields" on the Administration Screen.
2550   *
2551   * @since 1.5.0
2552   *
2553   * @param int    $post_id    Post ID.
2554   * @param string $meta_key   Metadata name.
2555   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
2556   * @param bool   $unique     Optional. Whether the same key should not be added.
2557   *                           Default false.
2558   * @return int|false Meta ID on success, false on failure.
2559   */
2560  function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
2561      // Make sure meta is added to the post, not a revision.
2562      $the_post = wp_is_post_revision( $post_id );
2563      if ( $the_post ) {
2564          $post_id = $the_post;
2565      }
2566  
2567      return add_metadata( 'post', $post_id, $meta_key, $meta_value, $unique );
2568  }
2569  
2570  /**
2571   * Deletes a post meta field for the given post ID.
2572   *
2573   * You can match based on the key, or key and value. Removing based on key and
2574   * value, will keep from removing duplicate metadata with the same key. It also
2575   * allows removing all metadata matching the key, if needed.
2576   *
2577   * @since 1.5.0
2578   *
2579   * @param int    $post_id    Post ID.
2580   * @param string $meta_key   Metadata name.
2581   * @param mixed  $meta_value Optional. Metadata value. If provided,
2582   *                           rows will only be removed that match the value.
2583   *                           Must be serializable if non-scalar. Default empty.
2584   * @return bool True on success, false on failure.
2585   */
2586  function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
2587      // Make sure meta is deleted from the post, not from a revision.
2588      $the_post = wp_is_post_revision( $post_id );
2589      if ( $the_post ) {
2590          $post_id = $the_post;
2591      }
2592  
2593      return delete_metadata( 'post', $post_id, $meta_key, $meta_value );
2594  }
2595  
2596  /**
2597   * Retrieves a post meta field for the given post ID.
2598   *
2599   * @since 1.5.0
2600   *
2601   * @param int    $post_id Post ID.
2602   * @param string $key     Optional. The meta key to retrieve. By default,
2603   *                        returns data for all keys. Default empty.
2604   * @param bool   $single  Optional. Whether to return a single value.
2605   *                        This parameter has no effect if `$key` is not specified.
2606   *                        Default false.
2607   * @return mixed An array of values if `$single` is false.
2608   *               The value of the meta field if `$single` is true.
2609   *               False for an invalid `$post_id` (non-numeric, zero, or negative value).
2610   *               An empty array if a valid but non-existing post ID is passed and `$single` is false.
2611   *               An empty string if a valid but non-existing post ID is passed and `$single` is true.
2612   */
2613  function get_post_meta( $post_id, $key = '', $single = false ) {
2614      return get_metadata( 'post', $post_id, $key, $single );
2615  }
2616  
2617  /**
2618   * Updates a post meta field based on the given post ID.
2619   *
2620   * Use the `$prev_value` parameter to differentiate between meta fields with the
2621   * same key and post ID.
2622   *
2623   * If the meta field for the post does not exist, it will be added and its ID returned.
2624   *
2625   * Can be used in place of add_post_meta().
2626   *
2627   * @since 1.5.0
2628   *
2629   * @param int    $post_id    Post ID.
2630   * @param string $meta_key   Metadata key.
2631   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
2632   * @param mixed  $prev_value Optional. Previous value to check before updating.
2633   *                           If specified, only update existing metadata entries with
2634   *                           this value. Otherwise, update all entries. Default empty.
2635   * @return int|bool Meta ID if the key didn't exist, true on successful update,
2636   *                  false on failure or if the value passed to the function
2637   *                  is the same as the one that is already in the database.
2638   */
2639  function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
2640      // Make sure meta is updated for the post, not for a revision.
2641      $the_post = wp_is_post_revision( $post_id );
2642      if ( $the_post ) {
2643          $post_id = $the_post;
2644      }
2645  
2646      return update_metadata( 'post', $post_id, $meta_key, $meta_value, $prev_value );
2647  }
2648  
2649  /**
2650   * Deletes everything from post meta matching the given meta key.
2651   *
2652   * @since 2.3.0
2653   *
2654   * @param string $post_meta_key Key to search for when deleting.
2655   * @return bool Whether the post meta key was deleted from the database.
2656   */
2657  function delete_post_meta_by_key( $post_meta_key ) {
2658      return delete_metadata( 'post', null, $post_meta_key, '', true );
2659  }
2660  
2661  /**
2662   * Registers a meta key for posts.
2663   *
2664   * @since 4.9.8
2665   *
2666   * @param string $post_type Post type to register a meta key for. Pass an empty string
2667   *                          to register the meta key across all existing post types.
2668   * @param string $meta_key  The meta key to register.
2669   * @param array  $args      Data used to describe the meta key when registered. See
2670   *                          {@see register_meta()} for a list of supported arguments.
2671   * @return bool True if the meta key was successfully registered, false if not.
2672   */
2673  function register_post_meta( $post_type, $meta_key, array $args ) {
2674      $args['object_subtype'] = $post_type;
2675  
2676      return register_meta( 'post', $meta_key, $args );
2677  }
2678  
2679  /**
2680   * Unregisters a meta key for posts.
2681   *
2682   * @since 4.9.8
2683   *
2684   * @param string $post_type Post type the meta key is currently registered for. Pass
2685   *                          an empty string if the meta key is registered across all
2686   *                          existing post types.
2687   * @param string $meta_key  The meta key to unregister.
2688   * @return bool True on success, false if the meta key was not previously registered.
2689   */
2690  function unregister_post_meta( $post_type, $meta_key ) {
2691      return unregister_meta_key( 'post', $meta_key, $post_type );
2692  }
2693  
2694  /**
2695   * Retrieves post meta fields, based on post ID.
2696   *
2697   * The post meta fields are retrieved from the cache where possible,
2698   * so the function is optimized to be called more than once.
2699   *
2700   * @since 1.2.0
2701   *
2702   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
2703   * @return mixed An array of values.
2704   *               False for an invalid `$post_id` (non-numeric, zero, or negative value).
2705   *               An empty string if a valid but non-existing post ID is passed.
2706   */
2707  function get_post_custom( $post_id = 0 ) {
2708      $post_id = absint( $post_id );
2709  
2710      if ( ! $post_id ) {
2711          $post_id = get_the_ID();
2712      }
2713  
2714      return get_post_meta( $post_id );
2715  }
2716  
2717  /**
2718   * Retrieves meta field names for a post.
2719   *
2720   * If there are no meta fields, then nothing (null) will be returned.
2721   *
2722   * @since 1.2.0
2723   *
2724   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
2725   * @return array|void Array of the keys, if retrieved.
2726   */
2727  function get_post_custom_keys( $post_id = 0 ) {
2728      $custom = get_post_custom( $post_id );
2729  
2730      if ( ! is_array( $custom ) ) {
2731          return;
2732      }
2733  
2734      $keys = array_keys( $custom );
2735      if ( $keys ) {
2736          return $keys;
2737      }
2738  }
2739  
2740  /**
2741   * Retrieves values for a custom post field.
2742   *
2743   * The parameters must not be considered optional. All of the post meta fields
2744   * will be retrieved and only the meta field key values returned.
2745   *
2746   * @since 1.2.0
2747   *
2748   * @param string $key     Optional. Meta field key. Default empty.
2749   * @param int    $post_id Optional. Post ID. Default is the ID of the global `$post`.
2750   * @return array|null Meta field values.
2751   */
2752  function get_post_custom_values( $key = '', $post_id = 0 ) {
2753      if ( ! $key ) {
2754          return null;
2755      }
2756  
2757      $custom = get_post_custom( $post_id );
2758  
2759      return isset( $custom[ $key ] ) ? $custom[ $key ] : null;
2760  }
2761  
2762  /**
2763   * Determines whether a post is sticky.
2764   *
2765   * Sticky posts should remain at the top of The Loop. If the post ID is not
2766   * given, then The Loop ID for the current post will be used.
2767   *
2768   * For more information on this and similar theme functions, check out
2769   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
2770   * Conditional Tags} article in the Theme Developer Handbook.
2771   *
2772   * @since 2.7.0
2773   *
2774   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
2775   * @return bool Whether post is sticky.
2776   */
2777  function is_sticky( $post_id = 0 ) {
2778      $post_id = absint( $post_id );
2779  
2780      if ( ! $post_id ) {
2781          $post_id = get_the_ID();
2782      }
2783  
2784      $stickies = get_option( 'sticky_posts' );
2785  
2786      if ( is_array( $stickies ) ) {
2787          $stickies  = array_map( 'intval', $stickies );
2788          $is_sticky = in_array( $post_id, $stickies, true );
2789      } else {
2790          $is_sticky = false;
2791      }
2792  
2793      /**
2794       * Filters whether a post is sticky.
2795       *
2796       * @since 5.3.0
2797       *
2798       * @param bool $is_sticky Whether a post is sticky.
2799       * @param int  $post_id   Post ID.
2800       */
2801      return apply_filters( 'is_sticky', $is_sticky, $post_id );
2802  }
2803  
2804  /**
2805   * Sanitizes every post field.
2806   *
2807   * If the context is 'raw', then the post object or array will get minimal
2808   * sanitization of the integer fields.
2809   *
2810   * @since 2.3.0
2811   *
2812   * @see sanitize_post_field()
2813   *
2814   * @param object|WP_Post|array $post    The post object or array
2815   * @param string               $context Optional. How to sanitize post fields.
2816   *                                      Accepts 'raw', 'edit', 'db', 'display',
2817   *                                      'attribute', or 'js'. Default 'display'.
2818   * @return object|WP_Post|array The now sanitized post object or array (will be the
2819   *                              same type as `$post`).
2820   */
2821  function sanitize_post( $post, $context = 'display' ) {
2822      if ( is_object( $post ) ) {
2823          // Check if post already filtered for this context.
2824          if ( isset( $post->filter ) && $context == $post->filter ) {
2825              return $post;
2826          }
2827          if ( ! isset( $post->ID ) ) {
2828              $post->ID = 0;
2829          }
2830          foreach ( array_keys( get_object_vars( $post ) ) as $field ) {
2831              $post->$field = sanitize_post_field( $field, $post->$field, $post->ID, $context );
2832          }
2833          $post->filter = $context;
2834      } elseif ( is_array( $post ) ) {
2835          // Check if post already filtered for this context.
2836          if ( isset( $post['filter'] ) && $context == $post['filter'] ) {
2837              return $post;
2838          }
2839          if ( ! isset( $post['ID'] ) ) {
2840              $post['ID'] = 0;
2841          }
2842          foreach ( array_keys( $post ) as $field ) {
2843              $post[ $field ] = sanitize_post_field( $field, $post[ $field ], $post['ID'], $context );
2844          }
2845          $post['filter'] = $context;
2846      }
2847      return $post;
2848  }
2849  
2850  /**
2851   * Sanitizes a post field based on context.
2852   *
2853   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and
2854   * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
2855   * are treated like 'display' when calling filters.
2856   *
2857   * @since 2.3.0
2858   * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
2859   *
2860   * @param string $field   The Post Object field name.
2861   * @param mixed  $value   The Post Object value.
2862   * @param int    $post_id Post ID.
2863   * @param string $context Optional. How to sanitize the field. Possible values are 'raw', 'edit',
2864   *                        'db', 'display', 'attribute' and 'js'. Default 'display'.
2865   * @return mixed Sanitized value.
2866   */
2867  function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
2868      $int_fields = array( 'ID', 'post_parent', 'menu_order' );
2869      if ( in_array( $field, $int_fields, true ) ) {
2870          $value = (int) $value;
2871      }
2872  
2873      // Fields which contain arrays of integers.
2874      $array_int_fields = array( 'ancestors' );
2875      if ( in_array( $field, $array_int_fields, true ) ) {
2876          $value = array_map( 'absint', $value );
2877          return $value;
2878      }
2879  
2880      if ( 'raw' === $context ) {
2881          return $value;
2882      }
2883  
2884      $prefixed = false;
2885      if ( str_contains( $field, 'post_' ) ) {
2886          $prefixed        = true;
2887          $field_no_prefix = str_replace( 'post_', '', $field );
2888      }
2889  
2890      if ( 'edit' === $context ) {
2891          $format_to_edit = array( 'post_content', 'post_excerpt', 'post_title', 'post_password' );
2892  
2893          if ( $prefixed ) {
2894  
2895              /**
2896               * Filters the value of a specific post field to edit.
2897               *
2898               * The dynamic portion of the hook name, `$field`, refers to the post
2899               * field name.
2900               *
2901               * @since 2.3.0
2902               *
2903               * @param mixed $value   Value of the post field.
2904               * @param int   $post_id Post ID.
2905               */
2906              $value = apply_filters( "edit_{$field}", $value, $post_id );
2907  
2908              /**
2909               * Filters the value of a specific post field to edit.
2910               *
2911               * The dynamic portion of the hook name, `$field_no_prefix`, refers to
2912               * the post field name.
2913               *
2914               * @since 2.3.0
2915               *
2916               * @param mixed $value   Value of the post field.
2917               * @param int   $post_id Post ID.
2918               */
2919              $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
2920          } else {
2921              $value = apply_filters( "edit_post_{$field}", $value, $post_id );
2922          }
2923  
2924          if ( in_array( $field, $format_to_edit, true ) ) {
2925              if ( 'post_content' === $field ) {
2926                  $value = format_to_edit( $value, user_can_richedit() );
2927              } else {
2928                  $value = format_to_edit( $value );
2929              }
2930          } else {
2931              $value = esc_attr( $value );
2932          }
2933      } elseif ( 'db' === $context ) {
2934          if ( $prefixed ) {
2935  
2936              /**
2937               * Filters the value of a specific post field before saving.
2938               *
2939               * The dynamic portion of the hook name, `$field`, refers to the post
2940               * field name.
2941               *
2942               * @since 2.3.0
2943               *
2944               * @param mixed $value Value of the post field.
2945               */
2946              $value = apply_filters( "pre_{$field}", $value );
2947  
2948              /**
2949               * Filters the value of a specific field before saving.
2950               *
2951               * The dynamic portion of the hook name, `$field_no_prefix`, refers
2952               * to the post field name.
2953               *
2954               * @since 2.3.0
2955               *
2956               * @param mixed $value Value of the post field.
2957               */
2958              $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
2959          } else {
2960              $value = apply_filters( "pre_post_{$field}", $value );
2961  
2962              /**
2963               * Filters the value of a specific post field before saving.
2964               *
2965               * The dynamic portion of the hook name, `$field`, refers to the post
2966               * field name.
2967               *
2968               * @since 2.3.0
2969               *
2970               * @param mixed $value Value of the post field.
2971               */
2972              $value = apply_filters( "{$field}_pre", $value );
2973          }
2974      } else {
2975  
2976          // Use display filters by default.
2977          if ( $prefixed ) {
2978  
2979              /**
2980               * Filters the value of a specific post field for display.
2981               *
2982               * The dynamic portion of the hook name, `$field`, refers to the post
2983               * field name.
2984               *
2985               * @since 2.3.0
2986               *
2987               * @param mixed  $value   Value of the prefixed post field.
2988               * @param int    $post_id Post ID.
2989               * @param string $context Context for how to sanitize the field.
2990               *                        Accepts 'raw', 'edit', 'db', 'display',
2991               *                        'attribute', or 'js'. Default 'display'.
2992               */
2993              $value = apply_filters( "{$field}", $value, $post_id, $context );
2994          } else {
2995              $value = apply_filters( "post_{$field}", $value, $post_id, $context );
2996          }
2997  
2998          if ( 'attribute' === $context ) {
2999              $value = esc_attr( $value );
3000          } elseif ( 'js' === $context ) {
3001              $value = esc_js( $value );
3002          }
3003      }
3004  
3005      // Restore the type for integer fields after esc_attr().
3006      if ( in_array( $field, $int_fields, true ) ) {
3007          $value = (int) $value;
3008      }
3009  
3010      return $value;
3011  }
3012  
3013  /**
3014   * Makes a post sticky.
3015   *
3016   * Sticky posts should be displayed at the top of the front page.
3017   *
3018   * @since 2.7.0
3019   *
3020   * @param int $post_id Post ID.
3021   */
3022  function stick_post( $post_id ) {
3023      $post_id  = (int) $post_id;
3024      $stickies = get_option( 'sticky_posts' );
3025      $updated  = false;
3026  
3027      if ( ! is_array( $stickies ) ) {
3028          $stickies = array();
3029      } else {
3030          $stickies = array_unique( array_map( 'intval', $stickies ) );
3031      }
3032  
3033      if ( ! in_array( $post_id, $stickies, true ) ) {
3034          $stickies[] = $post_id;
3035          $updated    = update_option( 'sticky_posts', array_values( $stickies ) );
3036      }
3037  
3038      if ( $updated ) {
3039          /**
3040           * Fires once a post has been added to the sticky list.
3041           *
3042           * @since 4.6.0
3043           *
3044           * @param int $post_id ID of the post that was stuck.
3045           */
3046          do_action( 'post_stuck', $post_id );
3047      }
3048  }
3049  
3050  /**
3051   * Un-sticks a post.
3052   *
3053   * Sticky posts should be displayed at the top of the front page.
3054   *
3055   * @since 2.7.0
3056   *
3057   * @param int $post_id Post ID.
3058   */
3059  function unstick_post( $post_id ) {
3060      $post_id  = (int) $post_id;
3061      $stickies = get_option( 'sticky_posts' );
3062  
3063      if ( ! is_array( $stickies ) ) {
3064          return;
3065      }
3066  
3067      $stickies = array_values( array_unique( array_map( 'intval', $stickies ) ) );
3068  
3069      if ( ! in_array( $post_id, $stickies, true ) ) {
3070          return;
3071      }
3072  
3073      $offset = array_search( $post_id, $stickies, true );
3074      if ( false === $offset ) {
3075          return;
3076      }
3077  
3078      array_splice( $stickies, $offset, 1 );
3079  
3080      $updated = update_option( 'sticky_posts', $stickies );
3081  
3082      if ( $updated ) {
3083          /**
3084           * Fires once a post has been removed from the sticky list.
3085           *
3086           * @since 4.6.0
3087           *
3088           * @param int $post_id ID of the post that was unstuck.
3089           */
3090          do_action( 'post_unstuck', $post_id );
3091      }
3092  }
3093  
3094  /**
3095   * Returns the cache key for wp_count_posts() based on the passed arguments.
3096   *
3097   * @since 3.9.0
3098   * @access private
3099   *
3100   * @param string $type Optional. Post type to retrieve count Default 'post'.
3101   * @param string $perm Optional. 'readable' or empty. Default empty.
3102   * @return string The cache key.
3103   */
3104  function _count_posts_cache_key( $type = 'post', $perm = '' ) {
3105      $cache_key = 'posts-' . $type;
3106  
3107      if ( 'readable' === $perm && is_user_logged_in() ) {
3108          $post_type_object = get_post_type_object( $type );
3109  
3110          if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
3111              $cache_key .= '_' . $perm . '_' . get_current_user_id();
3112          }
3113      }
3114  
3115      return $cache_key;
3116  }
3117  
3118  /**
3119   * Counts number of posts of a post type and if user has permissions to view.
3120   *
3121   * This function provides an efficient method of finding the amount of post's
3122   * type a blog has. Another method is to count the amount of items in
3123   * get_posts(), but that method has a lot of overhead with doing so. Therefore,
3124   * when developing for 2.5+, use this function instead.
3125   *
3126   * The $perm parameter checks for 'readable' value and if the user can read
3127   * private posts, it will display that for the user that is signed in.
3128   *
3129   * @since 2.5.0
3130   *
3131   * @global wpdb $wpdb WordPress database abstraction object.
3132   *
3133   * @param string $type Optional. Post type to retrieve count. Default 'post'.
3134   * @param string $perm Optional. 'readable' or empty. Default empty.
3135   * @return stdClass An object containing the number of posts for each status,
3136   *                  or an empty object if the post type does not exist.
3137   */
3138  function wp_count_posts( $type = 'post', $perm = '' ) {
3139      global $wpdb;
3140  
3141      if ( ! post_type_exists( $type ) ) {
3142          return new stdClass();
3143      }
3144  
3145      $cache_key = _count_posts_cache_key( $type, $perm );
3146  
3147      $counts = wp_cache_get( $cache_key, 'counts' );
3148      if ( false !== $counts ) {
3149          // We may have cached this before every status was registered.
3150          foreach ( get_post_stati() as $status ) {
3151              if ( ! isset( $counts->{$status} ) ) {
3152                  $counts->{$status} = 0;
3153              }
3154          }
3155  
3156          /** This filter is documented in wp-includes/post.php */
3157          return apply_filters( 'wp_count_posts', $counts, $type, $perm );
3158      }
3159  
3160      $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
3161  
3162      if ( 'readable' === $perm && is_user_logged_in() ) {
3163          $post_type_object = get_post_type_object( $type );
3164          if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
3165              $query .= $wpdb->prepare(
3166                  " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
3167                  get_current_user_id()
3168              );
3169          }
3170      }
3171  
3172      $query .= ' GROUP BY post_status';
3173  
3174      $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
3175      $counts  = array_fill_keys( get_post_stati(), 0 );
3176  
3177      foreach ( $results as $row ) {
3178          $counts[ $row['post_status'] ] = $row['num_posts'];
3179      }
3180  
3181      $counts = (object) $counts;
3182      wp_cache_set( $cache_key, $counts, 'counts' );
3183  
3184      /**
3185       * Filters the post counts by status for the current post type.
3186       *
3187       * @since 3.7.0
3188       *
3189       * @param stdClass $counts An object containing the current post_type's post
3190       *                         counts by status.
3191       * @param string   $type   Post type.
3192       * @param string   $perm   The permission to determine if the posts are 'readable'
3193       *                         by the current user.
3194       */
3195      return apply_filters( 'wp_count_posts', $counts, $type, $perm );
3196  }
3197  
3198  /**
3199   * Counts number of attachments for the mime type(s).
3200   *
3201   * If you set the optional mime_type parameter, then an array will still be
3202   * returned, but will only have the item you are looking for. It does not give
3203   * you the number of attachments that are children of a post. You can get that
3204   * by counting the number of children that post has.
3205   *
3206   * @since 2.5.0
3207   *
3208   * @global wpdb $wpdb WordPress database abstraction object.
3209   *
3210   * @param string|string[] $mime_type Optional. Array or comma-separated list of
3211   *                                   MIME patterns. Default empty.
3212   * @return stdClass An object containing the attachment counts by mime type.
3213   */
3214  function wp_count_attachments( $mime_type = '' ) {
3215      global $wpdb;
3216  
3217      $cache_key = sprintf(
3218          'attachments%s',
3219          ! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : ''
3220      );
3221  
3222      $counts = wp_cache_get( $cache_key, 'counts' );
3223      if ( false == $counts ) {
3224          $and   = wp_post_mime_type_where( $mime_type );
3225          $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 );
3226  
3227          $counts = array();
3228          foreach ( (array) $count as $row ) {
3229              $counts[ $row['post_mime_type'] ] = $row['num_posts'];
3230          }
3231          $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
3232  
3233          wp_cache_set( $cache_key, (object) $counts, 'counts' );
3234      }
3235  
3236      /**
3237       * Filters the attachment counts by mime type.
3238       *
3239       * @since 3.7.0
3240       *
3241       * @param stdClass        $counts    An object containing the attachment counts by
3242       *                                   mime type.
3243       * @param string|string[] $mime_type Array or comma-separated list of MIME patterns.
3244       */
3245      return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
3246  }
3247  
3248  /**
3249   * Gets default post mime types.
3250   *
3251   * @since 2.9.0
3252   * @since 5.3.0 Added the 'Documents', 'Spreadsheets', and 'Archives' mime type groups.
3253   *
3254   * @return array List of post mime types.
3255   */
3256  function get_post_mime_types() {
3257      $post_mime_types = array(   // array( adj, noun )
3258          'image'       => array(
3259              __( 'Images' ),
3260              __( 'Manage Images' ),
3261              /* translators: %s: Number of images. */
3262              _n_noop(
3263                  'Image <span class="count">(%s)</span>',
3264                  'Images <span class="count">(%s)</span>'
3265              ),
3266          ),
3267          'audio'       => array(
3268              _x( 'Audio', 'file type group' ),
3269              __( 'Manage Audio' ),
3270              /* translators: %s: Number of audio files. */
3271              _n_noop(
3272                  'Audio <span class="count">(%s)</span>',
3273                  'Audio <span class="count">(%s)</span>'
3274              ),
3275          ),
3276          'video'       => array(
3277              _x( 'Video', 'file type group' ),
3278              __( 'Manage Video' ),
3279              /* translators: %s: Number of video files. */
3280              _n_noop(
3281                  'Video <span class="count">(%s)</span>',
3282                  'Video <span class="count">(%s)</span>'
3283              ),
3284          ),
3285          'document'    => array(
3286              __( 'Documents' ),
3287              __( 'Manage Documents' ),
3288              /* translators: %s: Number of documents. */
3289              _n_noop(
3290                  'Document <span class="count">(%s)</span>',
3291                  'Documents <span class="count">(%s)</span>'
3292              ),
3293          ),
3294          'spreadsheet' => array(
3295              __( 'Spreadsheets' ),
3296              __( 'Manage Spreadsheets' ),
3297              /* translators: %s: Number of spreadsheets. */
3298              _n_noop(
3299                  'Spreadsheet <span class="count">(%s)</span>',
3300                  'Spreadsheets <span class="count">(%s)</span>'
3301              ),
3302          ),
3303          'archive'     => array(
3304              _x( 'Archives', 'file type group' ),
3305              __( 'Manage Archives' ),
3306              /* translators: %s: Number of archives. */
3307              _n_noop(
3308                  'Archive <span class="count">(%s)</span>',
3309                  'Archives <span class="count">(%s)</span>'
3310              ),
3311          ),
3312      );
3313  
3314      $ext_types  = wp_get_ext_types();
3315      $mime_types = wp_get_mime_types();
3316  
3317      foreach ( $post_mime_types as $group => $labels ) {
3318          if ( in_array( $group, array( 'image', 'audio', 'video' ), true ) ) {
3319              continue;
3320          }
3321  
3322          if ( ! isset( $ext_types[ $group ] ) ) {
3323              unset( $post_mime_types[ $group ] );
3324              continue;
3325          }
3326  
3327          $group_mime_types = array();
3328          foreach ( $ext_types[ $group ] as $extension ) {
3329              foreach ( $mime_types as $exts => $mime ) {
3330                  if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
3331                      $group_mime_types[] = $mime;
3332                      break;
3333                  }
3334              }
3335          }
3336          $group_mime_types = implode( ',', array_unique( $group_mime_types ) );
3337  
3338          $post_mime_types[ $group_mime_types ] = $labels;
3339          unset( $post_mime_types[ $group ] );
3340      }
3341  
3342      /**
3343       * Filters the default list of post mime types.
3344       *
3345       * @since 2.5.0
3346       *
3347       * @param array $post_mime_types Default list of post mime types.
3348       */
3349      return apply_filters( 'post_mime_types', $post_mime_types );
3350  }
3351  
3352  /**
3353   * Checks a MIME-Type against a list.
3354   *
3355   * If the `$wildcard_mime_types` parameter is a string, it must be comma separated
3356   * list. If the `$real_mime_types` is a string, it is also comma separated to
3357   * create the list.
3358   *
3359   * @since 2.5.0
3360   *
3361   * @param string|string[] $wildcard_mime_types Mime types, e.g. `audio/mpeg`, `image` (same as `image/*`),
3362   *                                             or `flash` (same as `*flash*`).
3363   * @param string|string[] $real_mime_types     Real post mime type values.
3364   * @return array array(wildcard=>array(real types)).
3365   */
3366  function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
3367      $matches = array();
3368      if ( is_string( $wildcard_mime_types ) ) {
3369          $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
3370      }
3371      if ( is_string( $real_mime_types ) ) {
3372          $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
3373      }
3374  
3375      $patternses = array();
3376      $wild       = '[-._a-z0-9]*';
3377  
3378      foreach ( (array) $wildcard_mime_types as $type ) {
3379          $mimes = array_map( 'trim', explode( ',', $type ) );
3380          foreach ( $mimes as $mime ) {
3381              $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
3382  
3383              $patternses[][ $type ] = "^$regex$";
3384  
3385              if ( ! str_contains( $mime, '/' ) ) {
3386                  $patternses[][ $type ] = "^$regex/";
3387                  $patternses[][ $type ] = $regex;
3388              }
3389          }
3390      }
3391      asort( $patternses );
3392  
3393      foreach ( $patternses as $patterns ) {
3394          foreach ( $patterns as $type => $pattern ) {
3395              foreach ( (array) $real_mime_types as $real ) {
3396                  if ( preg_match( "#$pattern#", $real )
3397                      && ( empty( $matches[ $type ] ) || false === array_search( $real, $matches[ $type ], true ) )
3398                  ) {
3399                      $matches[ $type ][] = $real;
3400                  }
3401              }
3402          }
3403      }
3404  
3405      return $matches;
3406  }
3407  
3408  /**
3409   * Converts MIME types into SQL.
3410   *
3411   * @since 2.5.0
3412   *
3413   * @param string|string[] $post_mime_types List of mime types or comma separated string
3414   *                                         of mime types.
3415   * @param string          $table_alias     Optional. Specify a table alias, if needed.
3416   *                                         Default empty.
3417   * @return string The SQL AND clause for mime searching.
3418   */
3419  function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
3420      $where     = '';
3421      $wildcards = array( '', '%', '%/%' );
3422      if ( is_string( $post_mime_types ) ) {
3423          $post_mime_types = array_map( 'trim', explode( ',', $post_mime_types ) );
3424      }
3425  
3426      $where_clauses = array();
3427  
3428      foreach ( (array) $post_mime_types as $mime_type ) {
3429          $mime_type = preg_replace( '/\s/', '', $mime_type );
3430          $slashpos  = strpos( $mime_type, '/' );
3431          if ( false !== $slashpos ) {
3432              $mime_group    = preg_replace( '/[^-*.a-zA-Z0-9]/', '', substr( $mime_type, 0, $slashpos ) );
3433              $mime_subgroup = preg_replace( '/[^-*.+a-zA-Z0-9]/', '', substr( $mime_type, $slashpos + 1 ) );
3434              if ( empty( $mime_subgroup ) ) {
3435                  $mime_subgroup = '*';
3436              } else {
3437                  $mime_subgroup = str_replace( '/', '', $mime_subgroup );
3438              }
3439              $mime_pattern = "$mime_group/$mime_subgroup";
3440          } else {
3441              $mime_pattern = preg_replace( '/[^-*.a-zA-Z0-9]/', '', $mime_type );
3442              if ( ! str_contains( $mime_pattern, '*' ) ) {
3443                  $mime_pattern .= '/*';
3444              }
3445          }
3446  
3447          $mime_pattern = preg_replace( '/\*+/', '%', $mime_pattern );
3448  
3449          if ( in_array( $mime_type, $wildcards, true ) ) {
3450              return '';
3451          }
3452  
3453          if ( str_contains( $mime_pattern, '%' ) ) {
3454              $where_clauses[] = empty( $table_alias ) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
3455          } else {
3456              $where_clauses[] = empty( $table_alias ) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
3457          }
3458      }
3459  
3460      if ( ! empty( $where_clauses ) ) {
3461          $where = ' AND (' . implode( ' OR ', $where_clauses ) . ') ';
3462      }
3463  
3464      return $where;
3465  }
3466  
3467  /**
3468   * Trashes or deletes a post or page.
3469   *
3470   * When the post and page is permanently deleted, everything that is tied to
3471   * it is deleted also. This includes comments, post meta fields, and terms
3472   * associated with the post.
3473   *
3474   * The post or page is moved to Trash instead of permanently deleted unless
3475   * Trash is disabled, item is already in the Trash, or $force_delete is true.
3476   *
3477   * @since 1.0.0
3478   *
3479   * @global wpdb $wpdb WordPress database abstraction object.
3480   * @see wp_delete_attachment()
3481   * @see wp_trash_post()
3482   *
3483   * @param int  $post_id      Optional. Post ID. Default 0.
3484   * @param bool $force_delete Optional. Whether to bypass Trash and force deletion.
3485   *                           Default false.
3486   * @return WP_Post|false|null Post data on success, false or null on failure.
3487   */
3488  function wp_delete_post( $post_id = 0, $force_delete = false ) {
3489      global $wpdb;
3490  
3491      $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) );
3492  
3493      if ( ! $post ) {
3494          return $post;
3495      }
3496  
3497      $post = get_post( $post );
3498  
3499      if ( ! $force_delete
3500          && ( 'post' === $post->post_type || 'page' === $post->post_type )
3501          && 'trash' !== get_post_status( $post_id ) && EMPTY_TRASH_DAYS
3502      ) {
3503          return wp_trash_post( $post_id );
3504      }
3505  
3506      if ( 'attachment' === $post->post_type ) {
3507          return wp_delete_attachment( $post_id, $force_delete );
3508      }
3509  
3510      /**
3511       * Filters whether a post deletion should take place.
3512       *
3513       * @since 4.4.0
3514       *
3515       * @param WP_Post|false|null $delete       Whether to go forward with deletion.
3516       * @param WP_Post            $post         Post object.
3517       * @param bool               $force_delete Whether to bypass the Trash.
3518       */
3519      $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
3520      if ( null !== $check ) {
3521          return $check;
3522      }
3523  
3524      /**
3525       * Fires before a post is deleted, at the start of wp_delete_post().
3526       *
3527       * @since 3.2.0
3528       * @since 5.5.0 Added the `$post` parameter.
3529       *
3530       * @see wp_delete_post()
3531       *
3532       * @param int     $post_id Post ID.
3533       * @param WP_Post $post    Post object.
3534       */
3535      do_action( 'before_delete_post', $post_id, $post );
3536  
3537      delete_post_meta( $post_id, '_wp_trash_meta_status' );
3538      delete_post_meta( $post_id, '_wp_trash_meta_time' );
3539  
3540      wp_delete_object_term_relationships( $post_id, get_object_taxonomies( $post->post_type ) );
3541  
3542      $parent_data  = array( 'post_parent' => $post->post_parent );
3543      $parent_where = array( 'post_parent' => $post_id );
3544  
3545      if ( is_post_type_hierarchical( $post->post_type ) ) {
3546          // Point children of this page to its parent, also clean the cache of affected children.
3547          $children_query = $wpdb->prepare(
3548              "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s",
3549              $post_id,
3550              $post->post_type
3551          );
3552  
3553          $children = $wpdb->get_results( $children_query );
3554  
3555          if ( $children ) {
3556              $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
3557          }
3558      }
3559  
3560      // Do raw query. wp_get_post_revisions() is filtered.
3561      $revision_ids = $wpdb->get_col(
3562          $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $post_id )
3563      );
3564  
3565      // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
3566      foreach ( $revision_ids as $revision_id ) {
3567          wp_delete_post_revision( $revision_id );
3568      }
3569  
3570      // Point all attachments to this post up one level.
3571      $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
3572  
3573      wp_defer_comment_counting( true );
3574  
3575      $comment_ids = $wpdb->get_col(
3576          $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d ORDER BY comment_ID DESC", $post_id )
3577      );
3578  
3579      foreach ( $comment_ids as $comment_id ) {
3580          wp_delete_comment( $comment_id, true );
3581      }
3582  
3583      wp_defer_comment_counting( false );
3584  
3585      $post_meta_ids = $wpdb->get_col(
3586          $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id )
3587      );
3588  
3589      foreach ( $post_meta_ids as $mid ) {
3590          delete_metadata_by_mid( 'post', $mid );
3591      }
3592  
3593      /**
3594       * Fires immediately before a post is deleted from the database.
3595       *
3596       * The dynamic portion of the hook name, `$post->post_type`, refers to
3597       * the post type slug.
3598       *
3599       * @since 6.6.0
3600       *
3601       * @param int     $post_id Post ID.
3602       * @param WP_Post $post    Post object.
3603       */
3604      do_action( "delete_post_{$post->post_type}", $post_id, $post );
3605  
3606      /**
3607       * Fires immediately before a post is deleted from the database.
3608       *
3609       * @since 1.2.0
3610       * @since 5.5.0 Added the `$post` parameter.
3611       *
3612       * @param int     $post_id Post ID.
3613       * @param WP_Post $post    Post object.
3614       */
3615      do_action( 'delete_post', $post_id, $post );
3616  
3617      $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
3618      if ( ! $result ) {
3619          return false;
3620      }
3621  
3622      /**
3623       * Fires immediately after a post is deleted from the database.
3624       *
3625       * The dynamic portion of the hook name, `$post->post_type`, refers to
3626       * the post type slug.
3627       *
3628       * @since 6.6.0
3629       *
3630       * @param int     $post_id Post ID.
3631       * @param WP_Post $post    Post object.
3632       */
3633      do_action( "deleted_post_{$post->post_type}", $post_id, $post );
3634  
3635      /**
3636       * Fires immediately after a post is deleted from the database.
3637       *
3638       * @since 2.2.0
3639       * @since 5.5.0 Added the `$post` parameter.
3640       *
3641       * @param int     $post_id Post ID.
3642       * @param WP_Post $post    Post object.
3643       */
3644      do_action( 'deleted_post', $post_id, $post );
3645  
3646      clean_post_cache( $post );
3647  
3648      if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
3649          foreach ( $children as $child ) {
3650              clean_post_cache( $child );
3651          }
3652      }
3653  
3654      wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) );
3655  
3656      /**
3657       * Fires after a post is deleted, at the conclusion of wp_delete_post().
3658       *
3659       * @since 3.2.0
3660       * @since 5.5.0 Added the `$post` parameter.
3661       *
3662       * @see wp_delete_post()
3663       *
3664       * @param int     $post_id Post ID.
3665       * @param WP_Post $post    Post object.
3666       */
3667      do_action( 'after_delete_post', $post_id, $post );
3668  
3669      return $post;
3670  }
3671  
3672  /**
3673   * Resets the page_on_front, show_on_front, and page_for_post settings when
3674   * a linked page is deleted or trashed.
3675   *
3676   * Also ensures the post is no longer sticky.
3677   *
3678   * @since 3.7.0
3679   * @access private
3680   *
3681   * @param int $post_id Post ID.
3682   */
3683  function _reset_front_page_settings_for_post( $post_id ) {
3684      $post = get_post( $post_id );
3685  
3686      if ( 'page' === $post->post_type ) {
3687          /*
3688           * If the page is defined in option page_on_front or post_for_posts,
3689           * adjust the corresponding options.
3690           */
3691          if ( get_option( 'page_on_front' ) == $post->ID ) {
3692              update_option( 'show_on_front', 'posts' );
3693              update_option( 'page_on_front', 0 );
3694          }
3695          if ( get_option( 'page_for_posts' ) == $post->ID ) {
3696              update_option( 'page_for_posts', 0 );
3697          }
3698      }
3699  
3700      unstick_post( $post->ID );
3701  }
3702  
3703  /**
3704   * Moves a post or page to the Trash
3705   *
3706   * If Trash is disabled, the post or page is permanently deleted.
3707   *
3708   * @since 2.9.0
3709   *
3710   * @see wp_delete_post()
3711   *
3712   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`
3713   *                     if `EMPTY_TRASH_DAYS` equals true.
3714   * @return WP_Post|false|null Post data on success, false or null on failure.
3715   */
3716  function wp_trash_post( $post_id = 0 ) {
3717      if ( ! EMPTY_TRASH_DAYS ) {
3718          return wp_delete_post( $post_id, true );
3719      }
3720  
3721      $post = get_post( $post_id );
3722  
3723      if ( ! $post ) {
3724          return $post;
3725      }
3726  
3727      if ( 'trash' === $post->post_status ) {
3728          return false;
3729      }
3730  
3731      $previous_status = $post->post_status;
3732  
3733      /**
3734       * Filters whether a post trashing should take place.
3735       *
3736       * @since 4.9.0
3737       * @since 6.3.0 Added the `$previous_status` parameter.
3738       *
3739       * @param bool|null $trash           Whether to go forward with trashing.
3740       * @param WP_Post   $post            Post object.
3741       * @param string    $previous_status The status of the post about to be trashed.
3742       */
3743      $check = apply_filters( 'pre_trash_post', null, $post, $previous_status );
3744  
3745      if ( null !== $check ) {
3746          return $check;
3747      }
3748  
3749      /**
3750       * Fires before a post is sent to the Trash.
3751       *
3752       * @since 3.3.0
3753       * @since 6.3.0 Added the `$previous_status` parameter.
3754       *
3755       * @param int    $post_id         Post ID.
3756       * @param string $previous_status The status of the post about to be trashed.
3757       */
3758      do_action( 'wp_trash_post', $post_id, $previous_status );
3759  
3760      add_post_meta( $post_id, '_wp_trash_meta_status', $previous_status );
3761      add_post_meta( $post_id, '_wp_trash_meta_time', time() );
3762  
3763      $post_updated = wp_update_post(
3764          array(
3765              'ID'          => $post_id,
3766              'post_status' => 'trash',
3767          )
3768      );
3769  
3770      if ( ! $post_updated ) {
3771          return false;
3772      }
3773  
3774      wp_trash_post_comments( $post_id );
3775  
3776      /**
3777       * Fires after a post is sent to the Trash.
3778       *
3779       * @since 2.9.0
3780       * @since 6.3.0 Added the `$previous_status` parameter.
3781       *
3782       * @param int    $post_id         Post ID.
3783       * @param string $previous_status The status of the post at the point where it was trashed.
3784       */
3785      do_action( 'trashed_post', $post_id, $previous_status );
3786  
3787      return $post;
3788  }
3789  
3790  /**
3791   * Restores a post from the Trash.
3792   *
3793   * @since 2.9.0
3794   * @since 5.6.0 An untrashed post is now returned to 'draft' status by default, except for
3795   *              attachments which are returned to their original 'inherit' status.
3796   *
3797   * @param int $post_id Optional. Post ID. Default is the ID of the global `$post`.
3798   * @return WP_Post|false|null Post data on success, false or null on failure.
3799   */
3800  function wp_untrash_post( $post_id = 0 ) {
3801      $post = get_post( $post_id );
3802  
3803      if ( ! $post ) {
3804          return $post;
3805      }
3806  
3807      $post_id = $post->ID;
3808  
3809      if ( 'trash' !== $post->post_status ) {
3810          return false;
3811      }
3812  
3813      $previous_status = get_post_meta( $post_id, '_wp_trash_meta_status', true );
3814  
3815      /**
3816       * Filters whether a post untrashing should take place.
3817       *
3818       * @since 4.9.0
3819       * @since 5.6.0 Added the `$previous_status` parameter.
3820       *
3821       * @param bool|null $untrash         Whether to go forward with untrashing.
3822       * @param WP_Post   $post            Post object.
3823       * @param string    $previous_status The status of the post at the point where it was trashed.
3824       */
3825      $check = apply_filters( 'pre_untrash_post', null, $post, $previous_status );
3826      if ( null !== $check ) {
3827          return $check;
3828      }
3829  
3830      /**
3831       * Fires before a post is restored from the Trash.
3832       *
3833       * @since 2.9.0
3834       * @since 5.6.0 Added the `$previous_status` parameter.
3835       *
3836       * @param int    $post_id         Post ID.
3837       * @param string $previous_status The status of the post at the point where it was trashed.
3838       */
3839      do_action( 'untrash_post', $post_id, $previous_status );
3840  
3841      $new_status = ( 'attachment' === $post->post_type ) ? 'inherit' : 'draft';
3842  
3843      /**
3844       * Filters the status that a post gets assigned when it is restored from the trash (untrashed).
3845       *
3846       * By default posts that are restored will be assigned a status of 'draft'. Return the value of `$previous_status`
3847       * in order to assign the status that the post had before it was trashed. The `wp_untrash_post_set_previous_status()`
3848       * function is available for this.
3849       *
3850       * Prior to WordPress 5.6.0, restored posts were always assigned their original status.
3851       *
3852       * @since 5.6.0
3853       *
3854       * @param string $new_status      The new status of the post being restored.
3855       * @param int    $post_id         The ID of the post being restored.
3856       * @param string $previous_status The status of the post at the point where it was trashed.
3857       */
3858      $post_status = apply_filters( 'wp_untrash_post_status', $new_status, $post_id, $previous_status );
3859  
3860      delete_post_meta( $post_id, '_wp_trash_meta_status' );
3861      delete_post_meta( $post_id, '_wp_trash_meta_time' );
3862  
3863      $post_updated = wp_update_post(
3864          array(
3865              'ID'          => $post_id,
3866              'post_status' => $post_status,
3867          )
3868      );
3869  
3870      if ( ! $post_updated ) {
3871          return false;
3872      }
3873  
3874      wp_untrash_post_comments( $post_id );
3875  
3876      /**
3877       * Fires after a post is restored from the Trash.
3878       *
3879       * @since 2.9.0
3880       * @since 5.6.0 Added the `$previous_status` parameter.
3881       *
3882       * @param int    $post_id         Post ID.
3883       * @param string $previous_status The status of the post at the point where it was trashed.
3884       */
3885      do_action( 'untrashed_post', $post_id, $previous_status );
3886  
3887      return $post;
3888  }
3889  
3890  /**
3891   * Moves comments for a post to the Trash.
3892   *
3893   * @since 2.9.0
3894   *
3895   * @global wpdb $wpdb WordPress database abstraction object.
3896   *
3897   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
3898   * @return mixed|void False on failure.
3899   */
3900  function wp_trash_post_comments( $post = null ) {
3901      global $wpdb;
3902  
3903      $post = get_post( $post );
3904  
3905      if ( ! $post ) {
3906          return;
3907      }
3908  
3909      $post_id = $post->ID;
3910  
3911      /**
3912       * Fires before comments are sent to the Trash.
3913       *
3914       * @since 2.9.0
3915       *
3916       * @param int $post_id Post ID.
3917       */
3918      do_action( 'trash_post_comments', $post_id );
3919  
3920      $comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ) );
3921  
3922      if ( ! $comments ) {
3923          return;
3924      }
3925  
3926      // Cache current status for each comment.
3927      $statuses = array();
3928      foreach ( $comments as $comment ) {
3929          $statuses[ $comment->comment_ID ] = $comment->comment_approved;
3930      }
3931      add_post_meta( $post_id, '_wp_trash_meta_comments_status', $statuses );
3932  
3933      // Set status for all comments to post-trashed.
3934      $result = $wpdb->update( $wpdb->comments, array( 'comment_approved' => 'post-trashed' ), array( 'comment_post_ID' => $post_id ) );
3935  
3936      clean_comment_cache( array_keys( $statuses ) );
3937  
3938      /**
3939       * Fires after comments are sent to the Trash.
3940       *
3941       * @since 2.9.0
3942       *
3943       * @param int   $post_id  Post ID.
3944       * @param array $statuses Array of comment statuses.
3945       */
3946      do_action( 'trashed_post_comments', $post_id, $statuses );
3947  
3948      return $result;
3949  }
3950  
3951  /**
3952   * Restores comments for a post from the Trash.
3953   *
3954   * @since 2.9.0
3955   *
3956   * @global wpdb $wpdb WordPress database abstraction object.
3957   *
3958   * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
3959   * @return true|void
3960   */
3961  function wp_untrash_post_comments( $post = null ) {
3962      global $wpdb;
3963  
3964      $post = get_post( $post );
3965  
3966      if ( ! $post ) {
3967          return;
3968      }
3969  
3970      $post_id = $post->ID;
3971  
3972      $statuses = get_post_meta( $post_id, '_wp_trash_meta_comments_status', true );
3973  
3974      if ( ! $statuses ) {
3975          return true;
3976      }
3977  
3978      /**
3979       * Fires before comments are restored for a post from the Trash.
3980       *
3981       * @since 2.9.0
3982       *
3983       * @param int $post_id Post ID.
3984       */
3985      do_action( 'untrash_post_comments', $post_id );
3986  
3987      // Restore each comment to its original status.
3988      $group_by_status = array();
3989      foreach ( $statuses as $comment_id => $comment_status ) {
3990          $group_by_status[ $comment_status ][] = $comment_id;
3991      }
3992  
3993      foreach ( $group_by_status as $status => $comments ) {
3994          // Confidence check. This shouldn't happen.
3995          if ( 'post-trashed' === $status ) {
3996              $status = '0';
3997          }
3998          $comments_in = implode( ', ', array_map( 'intval', $comments ) );
3999          $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
4000      }
4001  
4002      clean_comment_cache( array_keys( $statuses ) );
4003  
4004      delete_post_meta( $post_id, '_wp_trash_meta_comments_status' );
4005  
4006      /**
4007       * Fires after comments are restored for a post from the Trash.
4008       *
4009       * @since 2.9.0
4010       *
4011       * @param int $post_id Post ID.
4012       */
4013      do_action( 'untrashed_post_comments', $post_id );
4014  }
4015  
4016  /**
4017   * Retrieves the list of categories for a post.
4018   *
4019   * Compatibility layer for themes and plugins. Also an easy layer of abstraction
4020   * away from the complexity of the taxonomy layer.
4021   *
4022   * @since 2.1.0
4023   *
4024   * @see wp_get_object_terms()
4025   *
4026   * @param int   $post_id Optional. The Post ID. Does not default to the ID of the
4027   *                       global $post. Default 0.
4028   * @param array $args    Optional. Category query parameters. Default empty array.
4029   *                       See WP_Term_Query::__construct() for supported arguments.
4030   * @return array|WP_Error List of categories. If the `$fields` argument passed via `$args` is 'all' or
4031   *                        'all_with_object_id', an array of WP_Term objects will be returned. If `$fields`
4032   *                        is 'ids', an array of category IDs. If `$fields` is 'names', an array of category names.
4033   *                        WP_Error object if 'category' taxonomy doesn't exist.
4034   */
4035  function wp_get_post_categories( $post_id = 0, $args = array() ) {
4036      $post_id = (int) $post_id;
4037  
4038      $defaults = array( 'fields' => 'ids' );
4039      $args     = wp_parse_args( $args, $defaults );
4040  
4041      $cats = wp_get_object_terms( $post_id, 'category', $args );
4042      return $cats;
4043  }
4044  
4045  /**
4046   * Retrieves the tags for a post.
4047   *
4048   * There is only one default for this function, called 'fields' and by default
4049   * is set to 'all'. There are other defaults that can be overridden in
4050   * wp_get_object_terms().
4051   *
4052   * @since 2.3.0
4053   *
4054   * @param int   $post_id Optional. The Post ID. Does not default to the ID of the
4055   *                       global $post. Default 0.
4056   * @param array $args    Optional. Tag query parameters. Default empty array.
4057   *                       See WP_Term_Query::__construct() for supported arguments.
4058   * @return array|WP_Error Array of WP_Term objects on success or empty array if no tags were found.
4059   *                        WP_Error object if 'post_tag' taxonomy doesn't exist.
4060   */
4061  function wp_get_post_tags( $post_id = 0, $args = array() ) {
4062      return wp_get_post_terms( $post_id, 'post_tag', $args );
4063  }
4064  
4065  /**
4066   * Retrieves the terms for a post.
4067   *
4068   * @since 2.8.0
4069   *
4070   * @param int             $post_id  Optional. The Post ID. Does not default to the ID of the
4071   *                                  global $post. Default 0.
4072   * @param string|string[] $taxonomy Optional. The taxonomy slug or array of slugs for which
4073   *                                  to retrieve terms. Default 'post_tag'.
4074   * @param array           $args     {
4075   *     Optional. Term query parameters. See WP_Term_Query::__construct() for supported arguments.
4076   *
4077   *     @type string $fields Term fields to retrieve. Default 'all'.
4078   * }
4079   * @return array|WP_Error Array of WP_Term objects on success or empty array if no terms were found.
4080   *                        WP_Error object if `$taxonomy` doesn't exist.
4081   */
4082  function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
4083      $post_id = (int) $post_id;
4084  
4085      $defaults = array( 'fields' => 'all' );
4086      $args     = wp_parse_args( $args, $defaults );
4087  
4088      $tags = wp_get_object_terms( $post_id, $taxonomy, $args );
4089  
4090      return $tags;
4091  }
4092  
4093  /**
4094   * Retrieves a number of recent posts.
4095   *
4096   * @since 1.0.0
4097   *
4098   * @see get_posts()
4099   *
4100   * @param array  $args   Optional. Arguments to retrieve posts. Default empty array.
4101   * @param string $output Optional. The required return type. One of OBJECT or ARRAY_A, which
4102   *                       correspond to a WP_Post object or an associative array, respectively.
4103   *                       Default ARRAY_A.
4104   * @return array|false Array of recent posts, where the type of each element is determined
4105   *                     by the `$output` parameter. Empty array on failure.
4106   */
4107  function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
4108  
4109      if ( is_numeric( $args ) ) {
4110          _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
4111          $args = array( 'numberposts' => absint( $args ) );
4112      }
4113  
4114      // Set default arguments.
4115      $defaults = array(
4116          'numberposts'      => 10,
4117          'offset'           => 0,
4118          'category'         => 0,
4119          'orderby'          => 'post_date',
4120          'order'            => 'DESC',
4121          'include'          => '',
4122          'exclude'          => '',
4123          'meta_key'         => '',
4124          'meta_value'       => '',
4125          'post_type'        => 'post',
4126          'post_status'      => 'draft, publish, future, pending, private',
4127          'suppress_filters' => true,
4128      );
4129  
4130      $parsed_args = wp_parse_args( $args, $defaults );
4131  
4132      $results = get_posts( $parsed_args );
4133  
4134      // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
4135      if ( ARRAY_A === $output ) {
4136          foreach ( $results as $key => $result ) {
4137              $results[ $key ] = get_object_vars( $result );
4138          }
4139          return $results ? $results : array();
4140      }
4141  
4142      return $results ? $results : false;
4143  }
4144  
4145  /**
4146   * Inserts or update a post.
4147   *
4148   * If the $postarr parameter has 'ID' set to a value, then post will be updated.
4149   *
4150   * You can set the post date manually, by setting the values for 'post_date'
4151   * and 'post_date_gmt' keys. You can close the comments or open the comments by
4152   * setting the value for 'comment_status' key.
4153   *
4154   * @since 1.0.0
4155   * @since 2.6.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
4156   * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
4157   * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
4158   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
4159   *
4160   * @see sanitize_post()
4161   * @global wpdb $wpdb WordPress database abstraction object.
4162   *
4163   * @param array $postarr {
4164   *     An array of elements that make up a post to update or insert.
4165   *
4166   *     @type int    $ID                    The post ID. If equal to something other than 0,
4167   *                                         the post with that ID will be updated. Default 0.
4168   *     @type int    $post_author           The ID of the user who added the post. Default is
4169   *                                         the current user ID.
4170   *     @type string $post_date             The date of the post. Default is the current time.
4171   *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
4172   *                                         the value of `$post_date`.
4173   *     @type string $post_content          The post content. Default empty.
4174   *     @type string $post_content_filtered The filtered post content. Default empty.
4175   *     @type string $post_title            The post title. Default empty.
4176   *     @type string $post_excerpt          The post excerpt. Default empty.
4177   *     @type string $post_status           The post status. Default 'draft'.
4178   *     @type string $post_type             The post type. Default 'post'.
4179   *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
4180   *                                         Default is the value of 'default_comment_status' option.
4181   *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
4182   *                                         Default is the value of 'default_ping_status' option.
4183   *     @type string $post_password         The password to access the post. Default empty.
4184   *     @type string $post_name             The post name. Default is the sanitized post title
4185   *                                         when creating a new post.
4186   *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
4187   *                                         Default empty.
4188   *     @type string $pinged                Space or carriage return-separated list of URLs that have
4189   *                                         been pinged. Default empty.
4190   *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
4191   *     @type int    $menu_order            The order the post should be displayed in. Default 0.
4192   *     @type string $post_mime_type        The mime type of the post. Default empty.
4193   *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
4194   *     @type int    $import_id             The post ID to be used when inserting a new post.
4195   *                                         If specified, must not match any existing post ID. Default 0.
4196   *     @type int[]  $post_category         Array of category IDs.
4197   *                                         Defaults to value of the 'default_category' option.
4198   *     @type array  $tags_input            Array of tag names, slugs, or IDs. Default empty.
4199   *     @type array  $tax_input             An array of taxonomy terms keyed by their taxonomy name.
4200   *                                         If the taxonomy is hierarchical, the term list needs to be
4201   *                                         either an array of term IDs or a comma-separated string of IDs.
4202   *                                         If the taxonomy is non-hierarchical, the term list can be an array
4203   *                                         that contains term names or slugs, or a comma-separated string
4204   *                                         of names or slugs. This is because, in hierarchical taxonomy,
4205   *                                         child terms can have the same names with different parent terms,
4206   *                                         so the only way to connect them is using ID. Default empty.
4207   *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
4208   *     @type string $page_template         Page template to use.
4209   * }
4210   * @param bool  $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
4211   * @param bool  $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
4212   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
4213   */
4214  function wp_insert_post( $postarr, $wp_error = false, $fire_after_hooks = true ) {
4215      global $wpdb;
4216  
4217      // Capture original pre-sanitized array for passing into filters.
4218      $unsanitized_postarr = $postarr;
4219  
4220      $user_id = get_current_user_id();
4221  
4222      $defaults = array(
4223          'post_author'           => $user_id,
4224          'post_content'          => '',
4225          'post_content_filtered' => '',
4226          'post_title'            => '',
4227          'post_excerpt'          => '',
4228          'post_status'           => 'draft',
4229          'post_type'             => 'post',
4230          'comment_status'        => '',
4231          'ping_status'           => '',
4232          'post_password'         => '',
4233          'to_ping'               => '',
4234          'pinged'                => '',
4235          'post_parent'           => 0,
4236          'menu_order'            => 0,
4237          'guid'                  => '',
4238          'import_id'             => 0,
4239          'context'               => '',
4240          'post_date'             => '',
4241          'post_date_gmt'         => '',
4242      );
4243  
4244      $postarr = wp_parse_args( $postarr, $defaults );
4245  
4246      unset( $postarr['filter'] );
4247  
4248      $postarr = sanitize_post( $postarr, 'db' );
4249  
4250      // Are we updating or creating?
4251      $post_id = 0;
4252      $update  = false;
4253      $guid    = $postarr['guid'];
4254  
4255      if ( ! empty( $postarr['ID'] ) ) {
4256          $update = true;
4257  
4258          // Get the post ID and GUID.
4259          $post_id     = $postarr['ID'];
4260          $post_before = get_post( $post_id );
4261  
4262          if ( is_null( $post_before ) ) {
4263              if ( $wp_error ) {
4264                  return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
4265              }
4266              return 0;
4267          }
4268  
4269          $guid            = get_post_field( 'guid', $post_id );
4270          $previous_status = get_post_field( 'post_status', $post_id );
4271      } else {
4272          $previous_status = 'new';
4273          $post_before     = null;
4274      }
4275  
4276      $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
4277  
4278      $post_title   = $postarr['post_title'];
4279      $post_content = $postarr['post_content'];
4280      $post_excerpt = $postarr['post_excerpt'];
4281  
4282      if ( isset( $postarr['post_name'] ) ) {
4283          $post_name = $postarr['post_name'];
4284      } elseif ( $update ) {
4285          // For an update, don't modify the post_name if it wasn't supplied as an argument.
4286          $post_name = $post_before->post_name;
4287      }
4288  
4289      $maybe_empty = 'attachment' !== $post_type
4290          && ! $post_content && ! $post_title && ! $post_excerpt
4291          && post_type_supports( $post_type, 'editor' )
4292          && post_type_supports( $post_type, 'title' )
4293          && post_type_supports( $post_type, 'excerpt' );
4294  
4295      /**
4296       * Filters whether the post should be considered "empty".
4297       *
4298       * The post is considered "empty" if both:
4299       * 1. The post type supports the title, editor, and excerpt fields
4300       * 2. The title, editor, and excerpt fields are all empty
4301       *
4302       * Returning a truthy value from the filter will effectively short-circuit
4303       * the new post being inserted and return 0. If $wp_error is true, a WP_Error
4304       * will be returned instead.
4305       *
4306       * @since 3.3.0
4307       *
4308       * @param bool  $maybe_empty Whether the post should be considered "empty".
4309       * @param array $postarr     Array of post data.
4310       */
4311      if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
4312          if ( $wp_error ) {
4313              return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
4314          } else {
4315              return 0;
4316          }
4317      }
4318  
4319      $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
4320  
4321      if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash', 'auto-draft' ), true ) ) {
4322          $post_status = 'inherit';
4323      }
4324  
4325      if ( ! empty( $postarr['post_category'] ) ) {
4326          // Filter out empty terms.
4327          $post_category = array_filter( $postarr['post_category'] );
4328      } elseif ( $update && ! isset( $postarr['post_category'] ) ) {
4329          $post_category = $post_before->post_category;
4330      }
4331  
4332      // Make sure we set a valid category.
4333      if ( empty( $post_category ) || 0 === count( $post_category ) || ! is_array( $post_category ) ) {
4334          // 'post' requires at least one category.
4335          if ( 'post' === $post_type && 'auto-draft' !== $post_status ) {
4336              $post_category = array( get_option( 'default_category' ) );
4337          } else {
4338              $post_category = array();
4339          }
4340      }
4341  
4342      /*
4343       * Don't allow contributors to set the post slug for pending review posts.
4344       *
4345       * For new posts check the primitive capability, for updates check the meta capability.
4346       */
4347      if ( 'pending' === $post_status ) {
4348          $post_type_object = get_post_type_object( $post_type );
4349  
4350          if ( ! $update && $post_type_object && ! current_user_can( $post_type_object->cap->publish_posts ) ) {
4351              $post_name = '';
4352          } elseif ( $update && ! current_user_can( 'publish_post', $post_id ) ) {
4353              $post_name = '';
4354          }
4355      }
4356  
4357      /*
4358       * Create a valid post name. Drafts and pending posts are allowed to have
4359       * an empty post name.
4360       */
4361      if ( empty( $post_name ) ) {
4362          if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true ) ) {
4363              $post_name = sanitize_title( $post_title );
4364          } else {
4365              $post_name = '';
4366          }
4367      } else {
4368          // On updates, we need to check to see if it's using the old, fixed sanitization context.
4369          $check_name = sanitize_title( $post_name, '', 'old-save' );
4370  
4371          if ( $update
4372              && strtolower( urlencode( $post_name ) ) === $check_name
4373              && get_post_field( 'post_name', $post_id ) === $check_name
4374          ) {
4375              $post_name = $check_name;
4376          } else { // New post, or slug has changed.
4377              $post_name = sanitize_title( $post_name );
4378          }
4379      }
4380  
4381      /*
4382       * Resolve the post date from any provided post date or post date GMT strings;
4383       * if none are provided, the date will be set to now.
4384       */
4385      $post_date = wp_resolve_post_date( $postarr['post_date'], $postarr['post_date_gmt'] );
4386  
4387      if ( ! $post_date ) {
4388          if ( $wp_error ) {
4389              return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
4390          } else {
4391              return 0;
4392          }
4393      }
4394  
4395      if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' === $postarr['post_date_gmt'] ) {
4396          if ( ! in_array( $post_status, get_post_stati( array( 'date_floating' => true ) ), true ) ) {
4397              $post_date_gmt = get_gmt_from_date( $post_date );
4398          } else {
4399              $post_date_gmt = '0000-00-00 00:00:00';
4400          }
4401      } else {
4402          $post_date_gmt = $postarr['post_date_gmt'];
4403      }
4404  
4405      if ( $update || '0000-00-00 00:00:00' === $post_date ) {
4406          $post_modified     = current_time( 'mysql' );
4407          $post_modified_gmt = current_time( 'mysql', 1 );
4408      } else {
4409          $post_modified     = $post_date;
4410          $post_modified_gmt = $post_date_gmt;
4411      }
4412  
4413      if ( 'attachment' !== $post_type ) {
4414          $now = gmdate( 'Y-m-d H:i:s' );
4415  
4416          if ( 'publish' === $post_status ) {
4417              if ( strtotime( $post_date_gmt ) - strtotime( $now ) >= MINUTE_IN_SECONDS ) {
4418                  $post_status = 'future';
4419              }
4420          } elseif ( 'future' === $post_status ) {
4421              if ( strtotime( $post_date_gmt ) - strtotime( $now ) < MINUTE_IN_SECONDS ) {
4422                  $post_status = 'publish';
4423              }
4424          }
4425      }
4426  
4427      // Comment status.
4428      if ( empty( $postarr['comment_status'] ) ) {
4429          if ( $update ) {
4430              $comment_status = 'closed';
4431          } else {
4432              $comment_status = get_default_comment_status( $post_type );
4433          }
4434      } else {
4435          $comment_status = $postarr['comment_status'];
4436      }
4437  
4438      // These variables are needed by compact() later.
4439      $post_content_filtered = $postarr['post_content_filtered'];
4440      $post_author           = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
4441      $ping_status           = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
4442      $to_ping               = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
4443      $pinged                = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
4444      $import_id             = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
4445  
4446      /*
4447       * The 'wp_insert_post_parent' filter expects all variables to be present.
4448       * Previously, these variables would have already been extracted
4449       */
4450      if ( isset( $postarr['menu_order'] ) ) {
4451          $menu_order = (int) $postarr['menu_order'];
4452      } else {
4453          $menu_order = 0;
4454      }
4455  
4456      $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
4457      if ( 'private' === $post_status ) {
4458          $post_password = '';
4459      }
4460  
4461      if ( isset( $postarr['post_parent'] ) ) {
4462          $post_parent = (int) $postarr['post_parent'];
4463      } else {
4464          $post_parent = 0;
4465      }
4466  
4467      $new_postarr = array_merge(
4468          array(
4469              'ID' => $post_id,
4470          ),
4471          compact( array_diff( array_keys( $defaults ), array( 'context', 'filter' ) ) )
4472      );
4473  
4474      /**
4475       * Filters the post parent -- used to check for and prevent hierarchy loops.
4476       *
4477       * @since 3.1.0
4478       *
4479       * @param int   $post_parent Post parent ID.
4480       * @param int   $post_id     Post ID.
4481       * @param array $new_postarr Array of parsed post data.
4482       * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
4483       */
4484      $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_id, $new_postarr, $postarr );
4485  
4486      /*
4487       * If the post is being untrashed and it has a desired slug stored in post meta,
4488       * reassign it.
4489       */
4490      if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
4491          $desired_post_slug = get_post_meta( $post_id, '_wp_desired_post_slug', true );
4492  
4493          if ( $desired_post_slug ) {
4494              delete_post_meta( $post_id, '_wp_desired_post_slug' );
4495              $post_name = $desired_post_slug;
4496          }
4497      }
4498  
4499      // If a trashed post has the desired slug, change it and let this post have it.
4500      if ( 'trash' !== $post_status && $post_name ) {
4501          /**
4502           * Filters whether or not to add a `__trashed` suffix to trashed posts that match the name of the updated post.
4503           *
4504           * @since 5.4.0
4505           *
4506           * @param bool   $add_trashed_suffix Whether to attempt to add the suffix.
4507           * @param string $post_name          The name of the post being updated.
4508           * @param int    $post_id            Post ID.
4509           */
4510          $add_trashed_suffix = apply_filters( 'add_trashed_suffix_to_trashed_posts', true, $post_name, $post_id );
4511  
4512          if ( $add_trashed_suffix ) {
4513              wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_id );
4514          }
4515      }
4516  
4517      // When trashing an existing post, change its slug to allow non-trashed posts to use it.
4518      if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
4519          $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_id );
4520      }
4521  
4522      $post_name = wp_unique_post_slug( $post_name, $post_id, $post_status, $post_type, $post_parent );
4523  
4524      // Don't unslash.
4525      $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
4526  
4527      // Expected_slashed (everything!).
4528      $data = compact(
4529          'post_author',
4530          'post_date',
4531          'post_date_gmt',
4532          'post_content',
4533          'post_content_filtered',
4534          'post_title',
4535          'post_excerpt',
4536          'post_status',
4537          'post_type',
4538          'comment_status',
4539          'ping_status',
4540          'post_password',
4541          'post_name',
4542          'to_ping',
4543          'pinged',
4544          'post_modified',
4545          'post_modified_gmt',
4546          'post_parent',
4547          'menu_order',
4548          'post_mime_type',
4549          'guid'
4550      );
4551  
4552      $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
4553  
4554      foreach ( $emoji_fields as $emoji_field ) {
4555          if ( isset( $data[ $emoji_field ] ) ) {
4556              $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
4557  
4558              if ( 'utf8' === $charset ) {
4559                  $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
4560              }
4561          }
4562      }
4563  
4564      if ( 'attachment' === $post_type ) {
4565          /**
4566           * Filters attachment post data before it is updated in or added to the database.
4567           *
4568           * @since 3.9.0
4569           * @since 5.4.1 The `$unsanitized_postarr` parameter was added.
4570           * @since 6.0.0 The `$update` parameter was added.
4571           *
4572           * @param array $data                An array of slashed, sanitized, and processed attachment post data.
4573           * @param array $postarr             An array of slashed and sanitized attachment post data, but not processed.
4574           * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed attachment post data
4575           *                                   as originally passed to wp_insert_post().
4576           * @param bool  $update              Whether this is an existing attachment post being updated.
4577           */
4578          $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr, $unsanitized_postarr, $update );
4579      } else {
4580          /**
4581           * Filters slashed post data just before it is inserted into the database.
4582           *
4583           * @since 2.7.0
4584           * @since 5.4.1 The `$unsanitized_postarr` parameter was added.
4585           * @since 6.0.0 The `$update` parameter was added.
4586           *
4587           * @param array $data                An array of slashed, sanitized, and processed post data.
4588           * @param array $postarr             An array of sanitized (and slashed) but otherwise unmodified post data.
4589           * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as
4590           *                                   originally passed to wp_insert_post().
4591           * @param bool  $update              Whether this is an existing post being updated.
4592           */
4593          $data = apply_filters( 'wp_insert_post_data', $data, $postarr, $unsanitized_postarr, $update );
4594      }
4595  
4596      $data  = wp_unslash( $data );
4597      $where = array( 'ID' => $post_id );
4598  
4599      if ( $update ) {
4600          /**
4601           * Fires immediately before an existing post is updated in the database.
4602           *
4603           * @since 2.5.0
4604           *
4605           * @param int   $post_id Post ID.
4606           * @param array $data    Array of unslashed post data.
4607           */
4608          do_action( 'pre_post_update', $post_id, $data );
4609  
4610          if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
4611              if ( $wp_error ) {
4612                  if ( 'attachment' === $post_type ) {
4613                      $message = __( 'Could not update attachment in the database.' );
4614                  } else {
4615                      $message = __( 'Could not update post in the database.' );
4616                  }
4617  
4618                  return new WP_Error( 'db_update_error', $message, $wpdb->last_error );
4619              } else {
4620                  return 0;
4621              }
4622          }
4623      } else {
4624          // If there is a suggested ID, use it if not already present.
4625          if ( ! empty( $import_id ) ) {
4626              $import_id = (int) $import_id;
4627  
4628              if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id ) ) ) {
4629                  $data['ID'] = $import_id;
4630              }
4631          }
4632  
4633          if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
4634              if ( $wp_error ) {
4635                  if ( 'attachment' === $post_type ) {
4636                      $message = __( 'Could not insert attachment into the database.' );
4637                  } else {
4638                      $message = __( 'Could not insert post into the database.' );
4639                  }
4640  
4641                  return new WP_Error( 'db_insert_error', $message, $wpdb->last_error );
4642              } else {
4643                  return 0;
4644              }
4645          }
4646  
4647          $post_id = (int) $wpdb->insert_id;
4648  
4649          // Use the newly generated $post_id.
4650          $where = array( 'ID' => $post_id );
4651      }
4652  
4653      if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ), true ) ) {
4654          $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_id ), $post_id, $data['post_status'], $post_type, $post_parent );
4655  
4656          $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
4657          clean_post_cache( $post_id );
4658      }
4659  
4660      if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
4661          wp_set_post_categories( $post_id, $post_category );
4662      }
4663  
4664      if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
4665          wp_set_post_tags( $post_id, $postarr['tags_input'] );
4666      }
4667  
4668      // Add default term for all associated custom taxonomies.
4669      if ( 'auto-draft' !== $post_status ) {
4670          foreach ( get_object_taxonomies( $post_type, 'object' ) as $taxonomy => $tax_object ) {
4671  
4672              if ( ! empty( $tax_object->default_term ) ) {
4673  
4674                  // Filter out empty terms.
4675                  if ( isset( $postarr['tax_input'][ $taxonomy ] ) && is_array( $postarr['tax_input'][ $taxonomy ] ) ) {
4676                      $postarr['tax_input'][ $taxonomy ] = array_filter( $postarr['tax_input'][ $taxonomy ] );
4677                  }
4678  
4679                  // Passed custom taxonomy list overwrites the existing list if not empty.
4680                  $terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
4681                  if ( ! empty( $terms ) && empty( $postarr['tax_input'][ $taxonomy ] ) ) {
4682                      $postarr['tax_input'][ $taxonomy ] = $terms;
4683                  }
4684  
4685                  if ( empty( $postarr['tax_input'][ $taxonomy ] ) ) {
4686                      $default_term_id = get_option( 'default_term_' . $taxonomy );
4687                      if ( ! empty( $default_term_id ) ) {
4688                          $postarr['tax_input'][ $taxonomy ] = array( (int) $default_term_id );
4689                      }
4690                  }
4691              }
4692          }
4693      }
4694  
4695      // New-style support for all custom taxonomies.
4696      if ( ! empty( $postarr['tax_input'] ) ) {
4697          foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
4698              $taxonomy_obj = get_taxonomy( $taxonomy );
4699  
4700              if ( ! $taxonomy_obj ) {
4701                  /* translators: %s: Taxonomy name. */
4702                  _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
4703                  continue;
4704              }
4705  
4706              // array = hierarchical, string = non-hierarchical.
4707              if ( is_array( $tags ) ) {
4708                  $tags = array_filter( $tags );
4709              }
4710  
4711              if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
4712                  wp_set_post_terms( $post_id, $tags, $taxonomy );
4713              }
4714          }
4715      }
4716  
4717      if ( ! empty( $postarr['meta_input'] ) ) {
4718          foreach ( $postarr['meta_input'] as $field => $value ) {
4719              update_post_meta( $post_id, $field, $value );
4720          }
4721      }
4722  
4723      $current_guid = get_post_field( 'guid', $post_id );
4724  
4725      // Set GUID.
4726      if ( ! $update && '' === $current_guid ) {
4727          $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_id ) ), $where );
4728      }
4729  
4730      if ( 'attachment' === $postarr['post_type'] ) {
4731          if ( ! empty( $postarr['file'] ) ) {
4732              update_attached_file( $post_id, $postarr['file'] );
4733          }
4734  
4735          if ( ! empty( $postarr['context'] ) ) {
4736              add_post_meta( $post_id, '_wp_attachment_context', $postarr['context'], true );
4737          }
4738      }
4739  
4740      // Set or remove featured image.
4741      if ( isset( $postarr['_thumbnail_id'] ) ) {
4742          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
4743  
4744          if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
4745              if ( wp_attachment_is( 'audio', $post_id ) ) {
4746                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
4747              } elseif ( wp_attachment_is( 'video', $post_id ) ) {
4748                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
4749              }
4750          }
4751  
4752          if ( $thumbnail_support ) {
4753              $thumbnail_id = (int) $postarr['_thumbnail_id'];
4754              if ( -1 === $thumbnail_id ) {
4755                  delete_post_thumbnail( $post_id );
4756              } else {
4757                  set_post_thumbnail( $post_id, $thumbnail_id );
4758              }
4759          }
4760      }
4761  
4762      clean_post_cache( $post_id );
4763  
4764      $post = get_post( $post_id );
4765  
4766      if ( ! empty( $postarr['page_template'] ) ) {
4767          $post->page_template = $postarr['page_template'];
4768          $page_templates      = wp_get_theme()->get_page_templates( $post );
4769  
4770          if ( 'default' !== $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
4771              if ( $wp_error ) {
4772                  return new WP_Error( 'invalid_page_template', __( 'Invalid page template.' ) );
4773              }
4774  
4775              update_post_meta( $post_id, '_wp_page_template', 'default' );
4776          } else {
4777              update_post_meta( $post_id, '_wp_page_template', $postarr['page_template'] );
4778          }
4779      }
4780  
4781      if ( 'attachment' !== $postarr['post_type'] ) {
4782          wp_transition_post_status( $data['post_status'], $previous_status, $post );
4783      } else {
4784          if ( $update ) {
4785              /**
4786               * Fires once an existing attachment has been updated.
4787               *
4788               * @since 2.0.0
4789               *
4790               * @param int $post_id Attachment ID.
4791               */
4792              do_action( 'edit_attachment', $post_id );
4793  
4794              $post_after = get_post( $post_id );
4795  
4796              /**
4797               * Fires once an existing attachment has been updated.
4798               *
4799               * @since 4.4.0
4800               *
4801               * @param int     $post_id      Post ID.
4802               * @param WP_Post $post_after   Post object following the update.
4803               * @param WP_Post $post_before  Post object before the update.
4804               */
4805              do_action( 'attachment_updated', $post_id, $post_after, $post_before );
4806          } else {
4807  
4808              /**
4809               * Fires once an attachment has been added.
4810               *
4811               * @since 2.0.0
4812               *
4813               * @param int $post_id Attachment ID.
4814               */
4815              do_action( 'add_attachment', $post_id );
4816          }
4817  
4818          return $post_id;
4819      }
4820  
4821      if ( $update ) {
4822          /**
4823           * Fires once an existing post has been updated.
4824           *
4825           * The dynamic portion of the hook name, `$post->post_type`, refers to
4826           * the post type slug.
4827           *
4828           * Possible hook names include:
4829           *
4830           *  - `edit_post_post`
4831           *  - `edit_post_page`
4832           *
4833           * @since 5.1.0
4834           *
4835           * @param int     $post_id Post ID.
4836           * @param WP_Post $post    Post object.
4837           */
4838          do_action( "edit_post_{$post->post_type}", $post_id, $post );
4839  
4840          /**
4841           * Fires once an existing post has been updated.
4842           *
4843           * @since 1.2.0
4844           *
4845           * @param int     $post_id Post ID.
4846           * @param WP_Post $post    Post object.
4847           */
4848          do_action( 'edit_post', $post_id, $post );
4849  
4850          $post_after = get_post( $post_id );
4851  
4852          /**
4853           * Fires once an existing post has been updated.
4854           *
4855           * @since 3.0.0
4856           *
4857           * @param int     $post_id      Post ID.
4858           * @param WP_Post $post_after   Post object following the update.
4859           * @param WP_Post $post_before  Post object before the update.
4860           */
4861          do_action( 'post_updated', $post_id, $post_after, $post_before );
4862      }
4863  
4864      /**
4865       * Fires once a post has been saved.
4866       *
4867       * The dynamic portion of the hook name, `$post->post_type`, refers to
4868       * the post type slug.
4869       *
4870       * Possible hook names include:
4871       *
4872       *  - `save_post_post`
4873       *  - `save_post_page`
4874       *
4875       * @since 3.7.0
4876       *
4877       * @param int     $post_id Post ID.
4878       * @param WP_Post $post    Post object.
4879       * @param bool    $update  Whether this is an existing post being updated.
4880       */
4881      do_action( "save_post_{$post->post_type}", $post_id, $post, $update );
4882  
4883      /**
4884       * Fires once a post has been saved.
4885       *
4886       * @since 1.5.0
4887       *
4888       * @param int     $post_id Post ID.
4889       * @param WP_Post $post    Post object.
4890       * @param bool    $update  Whether this is an existing post being updated.
4891       */
4892      do_action( 'save_post', $post_id, $post, $update );
4893  
4894      /**
4895       * Fires once a post has been saved.
4896       *
4897       * @since 2.0.0
4898       *
4899       * @param int     $post_id Post ID.
4900       * @param WP_Post $post    Post object.
4901       * @param bool    $update  Whether this is an existing post being updated.
4902       */
4903      do_action( 'wp_insert_post', $post_id, $post, $update );
4904  
4905      if ( $fire_after_hooks ) {
4906          wp_after_insert_post( $post, $update, $post_before );
4907      }
4908  
4909      return $post_id;
4910  }
4911  
4912  /**
4913   * Updates a post with new post data.
4914   *
4915   * The date does not have to be set for drafts. You can set the date and it will
4916   * not be overridden.
4917   *
4918   * @since 1.0.0
4919   * @since 3.5.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
4920   * @since 5.6.0 Added the `$fire_after_hooks` parameter.
4921   *
4922   * @param array|object $postarr          Optional. Post data. Arrays are expected to be escaped,
4923   *                                       objects are not. See wp_insert_post() for accepted arguments.
4924   *                                       Default array.
4925   * @param bool         $wp_error         Optional. Whether to return a WP_Error on failure. Default false.
4926   * @param bool         $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
4927   * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
4928   */
4929  function wp_update_post( $postarr = array(), $wp_error = false, $fire_after_hooks = true ) {
4930      if ( is_object( $postarr ) ) {
4931          // Non-escaped post was passed.
4932          $postarr = get_object_vars( $postarr );
4933          $postarr = wp_slash( $postarr );
4934      }
4935  
4936      // First, get all of the original fields.
4937      $post = get_post( $postarr['ID'], ARRAY_A );
4938  
4939      if ( is_null( $post ) ) {
4940          if ( $wp_error ) {
4941              return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
4942          }
4943          return 0;
4944      }
4945  
4946      // Escape data pulled from DB.
4947      $post = wp_slash( $post );
4948  
4949      // Passed post category list overwrites existing category list if not empty.
4950      if ( isset( $postarr['post_category'] ) && is_array( $postarr['post_category'] )
4951          && count( $postarr['post_category'] ) > 0
4952      ) {
4953          $post_cats = $postarr['post_category'];
4954      } else {
4955          $post_cats = $post['post_category'];
4956      }
4957  
4958      // Drafts shouldn't be assigned a date unless explicitly done so by the user.
4959      if ( isset( $post['post_status'] )
4960          && in_array( $post['post_status'], array( 'draft', 'pending', 'auto-draft' ), true )
4961          && empty( $postarr['edit_date'] ) && ( '0000-00-00 00:00:00' === $post['post_date_gmt'] )
4962      ) {
4963          $clear_date = true;
4964      } else {
4965          $clear_date = false;
4966      }
4967  
4968      // Merge old and new fields with new fields overwriting old ones.
4969      $postarr                  = array_merge( $post, $postarr );
4970      $postarr['post_category'] = $post_cats;
4971      if ( $clear_date ) {
4972          $postarr['post_date']     = current_time( 'mysql' );
4973          $postarr['post_date_gmt'] = '';
4974      }
4975  
4976      if ( 'attachment' === $postarr['post_type'] ) {
4977          return wp_insert_attachment( $postarr, false, 0, $wp_error );
4978      }
4979  
4980      // Discard 'tags_input' parameter if it's the same as existing post tags.
4981      if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $postarr['post_type'], 'post_tag' ) ) {
4982          $tags      = get_the_terms( $postarr['ID'], 'post_tag' );
4983          $tag_names = array();
4984  
4985          if ( $tags && ! is_wp_error( $tags ) ) {
4986              $tag_names = wp_list_pluck( $tags, 'name' );
4987          }
4988  
4989          if ( $postarr['tags_input'] === $tag_names ) {
4990              unset( $postarr['tags_input'] );
4991          }
4992      }
4993  
4994      return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
4995  }
4996  
4997  /**
4998   * Publishes a post by transitioning the post status.
4999   *
5000   * @since 2.1.0
5001   *
5002   * @global wpdb $wpdb WordPress database abstraction object.
5003   *
5004   * @param int|WP_Post $post Post ID or post object.
5005   */
5006  function wp_publish_post( $post ) {
5007      global $wpdb;
5008  
5009      $post = get_post( $post );
5010  
5011      if ( ! $post ) {
5012          return;
5013      }
5014  
5015      if ( 'publish' === $post->post_status ) {
5016          return;
5017      }
5018  
5019      $post_before = get_post( $post->ID );
5020  
5021      // Ensure at least one term is applied for taxonomies with a default term.
5022      foreach ( get_object_taxonomies( $post->post_type, 'object' ) as $taxonomy => $tax_object ) {
5023          // Skip taxonomy if no default term is set.
5024          if (
5025              'category' !== $taxonomy &&
5026              empty( $tax_object->default_term )
5027          ) {
5028              continue;
5029          }
5030  
5031          // Do not modify previously set terms.
5032          if ( ! empty( get_the_terms( $post, $taxonomy ) ) ) {
5033              continue;
5034          }
5035  
5036          if ( 'category' === $taxonomy ) {
5037              $default_term_id = (int) get_option( 'default_category', 0 );
5038          } else {
5039              $default_term_id = (int) get_option( 'default_term_' . $taxonomy, 0 );
5040          }
5041  
5042          if ( ! $default_term_id ) {
5043              continue;
5044          }
5045          wp_set_post_terms( $post->ID, array( $default_term_id ), $taxonomy );
5046      }
5047  
5048      $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
5049  
5050      clean_post_cache( $post->ID );
5051  
5052      $old_status        = $post->post_status;
5053      $post->post_status = 'publish';
5054      wp_transition_post_status( 'publish', $old_status, $post );
5055  
5056      /** This action is documented in wp-includes/post.php */
5057      do_action( "edit_post_{$post->post_type}", $post->ID, $post );
5058  
5059      /** This action is documented in wp-includes/post.php */
5060      do_action( 'edit_post', $post->ID, $post );
5061  
5062      /** This action is documented in wp-includes/post.php */
5063      do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
5064  
5065      /** This action is documented in wp-includes/post.php */
5066      do_action( 'save_post', $post->ID, $post, true );
5067  
5068      /** This action is documented in wp-includes/post.php */
5069      do_action( 'wp_insert_post', $post->ID, $post, true );
5070  
5071      wp_after_insert_post( $post, true, $post_before );
5072  }
5073  
5074  /**
5075   * Publishes future post and make sure post ID has future post status.
5076   *
5077   * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
5078   * from publishing drafts, etc.
5079   *
5080   * @since 2.5.0
5081   *
5082   * @param int|WP_Post $post Post ID or post object.
5083   */
5084  function check_and_publish_future_post( $post ) {
5085      $post = get_post( $post );
5086  
5087      if ( ! $post ) {
5088          return;
5089      }
5090  
5091      if ( 'future' !== $post->post_status ) {
5092          return;
5093      }
5094  
5095      $time = strtotime( $post->post_date_gmt . ' GMT' );
5096  
5097      // Uh oh, someone jumped the gun!
5098      if ( $time > time() ) {
5099          wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); // Clear anything else in the system.
5100          wp_schedule_single_event( $time, 'publish_future_post', array( $post->ID ) );
5101          return;
5102      }
5103  
5104      // wp_publish_post() returns no meaningful value.
5105      wp_publish_post( $post->ID );
5106  }
5107  
5108  /**
5109   * Uses wp_checkdate to return a valid Gregorian-calendar value for post_date.
5110   * If post_date is not provided, this first checks post_date_gmt if provided,
5111   * then falls back to use the current time.
5112   *
5113   * For back-compat purposes in wp_insert_post, an empty post_date and an invalid
5114   * post_date_gmt will continue to return '1970-01-01 00:00:00' rather than false.
5115   *
5116   * @since 5.7.0
5117   *
5118   * @param string $post_date     The date in mysql format (`Y-m-d H:i:s`).
5119   * @param string $post_date_gmt The GMT date in mysql format (`Y-m-d H:i:s`).
5120   * @return string|false A valid Gregorian-calendar date string, or false on failure.
5121   */
5122  function wp_resolve_post_date( $post_date = '', $post_date_gmt = '' ) {
5123      // If the date is empty, set the date to now.
5124      if ( empty( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
5125          if ( empty( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
5126              $post_date = current_time( 'mysql' );
5127          } else {
5128              $post_date = get_date_from_gmt( $post_date_gmt );
5129          }
5130      }
5131  
5132      // Validate the date.
5133      $month = (int) substr( $post_date, 5, 2 );
5134      $day   = (int) substr( $post_date, 8, 2 );
5135      $year  = (int) substr( $post_date, 0, 4 );
5136  
5137      $valid_date = wp_checkdate( $month, $day, $year, $post_date );
5138  
5139      if ( ! $valid_date ) {
5140          return false;
5141      }
5142      return $post_date;
5143  }
5144  
5145  /**
5146   * Computes a unique slug for the post, when given the desired slug and some post details.
5147   *
5148   * @since 2.8.0
5149   *
5150   * @global wpdb       $wpdb       WordPress database abstraction object.
5151   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
5152   *
5153   * @param string $slug        The desired slug (post_name).
5154   * @param int    $post_id     Post ID.
5155   * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
5156   * @param string $post_type   Post type.
5157   * @param int    $post_parent Post parent ID.
5158   * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
5159   */
5160  function wp_unique_post_slug( $slug, $post_id, $post_status, $post_type, $post_parent ) {
5161      if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true )
5162          || ( 'inherit' === $post_status && 'revision' === $post_type ) || 'user_request' === $post_type
5163      ) {
5164          return $slug;
5165      }
5166  
5167      /**
5168       * Filters the post slug before it is generated to be unique.
5169       *
5170       * Returning a non-null value will short-circuit the
5171       * unique slug generation, returning the passed value instead.
5172       *
5173       * @since 5.1.0
5174       *
5175       * @param string|null $override_slug Short-circuit return value.
5176       * @param string      $slug          The desired slug (post_name).
5177       * @param int         $post_id       Post ID.
5178       * @param string      $post_status   The post status.
5179       * @param string      $post_type     Post type.
5180       * @param int         $post_parent   Post parent ID.
5181       */
5182      $override_slug = apply_filters( 'pre_wp_unique_post_slug', null, $slug, $post_id, $post_status, $post_type, $post_parent );
5183      if ( null !== $override_slug ) {
5184          return $override_slug;
5185      }
5186  
5187      global $wpdb, $wp_rewrite;
5188  
5189      $original_slug = $slug;
5190  
5191      $feeds = $wp_rewrite->feeds;
5192      if ( ! is_array( $feeds ) ) {
5193          $feeds = array();
5194      }
5195  
5196      if ( 'attachment' === $post_type ) {
5197          // Attachment slugs must be unique across all types.
5198          $check_sql       = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
5199          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_id ) );
5200  
5201          /**
5202           * Filters whether the post slug would make a bad attachment slug.
5203           *
5204           * @since 3.1.0
5205           *
5206           * @param bool   $bad_slug Whether the slug would be bad as an attachment slug.
5207           * @param string $slug     The post slug.
5208           */
5209          $is_bad_attachment_slug = apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug );
5210  
5211          if ( $post_name_check
5212              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5213              || $is_bad_attachment_slug
5214          ) {
5215              $suffix = 2;
5216              do {
5217                  $alt_post_name   = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5218                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_id ) );
5219                  ++$suffix;
5220              } while ( $post_name_check );
5221              $slug = $alt_post_name;
5222          }
5223      } elseif ( is_post_type_hierarchical( $post_type ) ) {
5224          if ( 'nav_menu_item' === $post_type ) {
5225              return $slug;
5226          }
5227  
5228          /*
5229           * Page slugs must be unique within their own trees. Pages are in a separate
5230           * namespace than posts so page slugs are allowed to overlap post slugs.
5231           */
5232          $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";
5233          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_id, $post_parent ) );
5234  
5235          /**
5236           * Filters whether the post slug would make a bad hierarchical post slug.
5237           *
5238           * @since 3.1.0
5239           *
5240           * @param bool   $bad_slug    Whether the post slug would be bad in a hierarchical post context.
5241           * @param string $slug        The post slug.
5242           * @param string $post_type   Post type.
5243           * @param int    $post_parent Post parent ID.
5244           */
5245          $is_bad_hierarchical_slug = apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent );
5246  
5247          if ( $post_name_check
5248              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5249              || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )
5250              || $is_bad_hierarchical_slug
5251          ) {
5252              $suffix = 2;
5253              do {
5254                  $alt_post_name   = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5255                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_id, $post_parent ) );
5256                  ++$suffix;
5257              } while ( $post_name_check );
5258              $slug = $alt_post_name;
5259          }
5260      } else {
5261          // Post slugs must be unique across all posts.
5262          $check_sql       = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
5263          $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_id ) );
5264  
5265          $post = get_post( $post_id );
5266  
5267          // Prevent new post slugs that could result in URLs that conflict with date archives.
5268          $conflicts_with_date_archive = false;
5269          if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) ) {
5270              $slug_num = (int) $slug;
5271  
5272              if ( $slug_num ) {
5273                  $permastructs   = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
5274                  $postname_index = array_search( '%postname%', $permastructs, true );
5275  
5276                  /*
5277                  * Potential date clashes are as follows:
5278                  *
5279                  * - Any integer in the first permastruct position could be a year.
5280                  * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
5281                  * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
5282                  */
5283                  if ( 0 === $postname_index ||
5284                      ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
5285                      ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
5286                  ) {
5287                      $conflicts_with_date_archive = true;
5288                  }
5289              }
5290          }
5291  
5292          /**
5293           * Filters whether the post slug would be bad as a flat slug.
5294           *
5295           * @since 3.1.0
5296           *
5297           * @param bool   $bad_slug  Whether the post slug would be bad as a flat slug.
5298           * @param string $slug      The post slug.
5299           * @param string $post_type Post type.
5300           */
5301          $is_bad_flat_slug = apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type );
5302  
5303          if ( $post_name_check
5304              || in_array( $slug, $feeds, true ) || 'embed' === $slug
5305              || $conflicts_with_date_archive
5306              || $is_bad_flat_slug
5307          ) {
5308              $suffix = 2;
5309              do {
5310                  $alt_post_name   = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
5311                  $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_id ) );
5312                  ++$suffix;
5313              } while ( $post_name_check );
5314              $slug = $alt_post_name;
5315          }
5316      }
5317  
5318      /**
5319       * Filters the unique post slug.
5320       *
5321       * @since 3.3.0
5322       *
5323       * @param string $slug          The post slug.
5324       * @param int    $post_id       Post ID.
5325       * @param string $post_status   The post status.
5326       * @param string $post_type     Post type.
5327       * @param int    $post_parent   Post parent ID
5328       * @param string $original_slug The original post slug.
5329       */
5330      return apply_filters( 'wp_unique_post_slug', $slug, $post_id, $post_status, $post_type, $post_parent, $original_slug );
5331  }
5332  
5333  /**
5334   * Truncates a post slug.
5335   *
5336   * @since 3.6.0
5337   * @access private
5338   *
5339   * @see utf8_uri_encode()
5340   *
5341   * @param string $slug   The slug to truncate.
5342   * @param int    $length Optional. Max length of the slug. Default 200 (characters).
5343   * @return string The truncated slug.
5344   */
5345  function _truncate_post_slug( $slug, $length = 200 ) {
5346      if ( strlen( $slug ) > $length ) {
5347          $decoded_slug = urldecode( $slug );
5348          if ( $decoded_slug === $slug ) {
5349              $slug = substr( $slug, 0, $length );
5350          } else {
5351              $slug = utf8_uri_encode( $decoded_slug, $length, true );
5352          }
5353      }
5354  
5355      return rtrim( $slug, '-' );
5356  }
5357  
5358  /**
5359   * Adds tags to a post.
5360   *
5361   * @see wp_set_post_tags()
5362   *
5363   * @since 2.3.0
5364   *
5365   * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
5366   * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
5367   *                              separated by commas. Default empty.
5368   * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
5369   */
5370  function wp_add_post_tags( $post_id = 0, $tags = '' ) {
5371      return wp_set_post_tags( $post_id, $tags, true );
5372  }
5373  
5374  /**
5375   * Sets the tags for a post.
5376   *
5377   * @since 2.3.0
5378   *
5379   * @see wp_set_object_terms()
5380   *
5381   * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
5382   * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
5383   *                              separated by commas. Default empty.
5384   * @param bool         $append  Optional. If true, don't delete existing tags, just add on. If false,
5385   *                              replace the tags with the new tags. Default false.
5386   * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
5387   */
5388  function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
5389      return wp_set_post_terms( $post_id, $tags, 'post_tag', $append );
5390  }
5391  
5392  /**
5393   * Sets the terms for a post.
5394   *
5395   * @since 2.8.0
5396   *
5397   * @see wp_set_object_terms()
5398   *
5399   * @param int          $post_id  Optional. The Post ID. Does not default to the ID of the global $post.
5400   * @param string|array $terms    Optional. An array of terms to set for the post, or a string of terms
5401   *                               separated by commas. Hierarchical taxonomies must always pass IDs rather
5402   *                               than names so that children with the same names but different parents
5403   *                               aren't confused. Default empty.
5404   * @param string       $taxonomy Optional. Taxonomy name. Default 'post_tag'.
5405   * @param bool         $append   Optional. If true, don't delete existing terms, just add on. If false,
5406   *                               replace the terms with the new terms. Default false.
5407   * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
5408   */
5409  function wp_set_post_terms( $post_id = 0, $terms = '', $taxonomy = 'post_tag', $append = false ) {
5410      $post_id = (int) $post_id;
5411  
5412      if ( ! $post_id ) {
5413          return false;
5414      }
5415  
5416      if ( empty( $terms ) ) {
5417          $terms = array();
5418      }
5419  
5420      if ( ! is_array( $terms ) ) {
5421          $comma = _x( ',', 'tag delimiter' );
5422          if ( ',' !== $comma ) {
5423              $terms = str_replace( $comma, ',', $terms );
5424          }
5425          $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
5426      }
5427  
5428      /*
5429       * Hierarchical taxonomies must always pass IDs rather than names so that
5430       * children with the same names but different parents aren't confused.
5431       */
5432      if ( is_taxonomy_hierarchical( $taxonomy ) ) {
5433          $terms = array_unique( array_map( 'intval', $terms ) );
5434      }
5435  
5436      return wp_set_object_terms( $post_id, $terms, $taxonomy, $append );
5437  }
5438  
5439  /**
5440   * Sets categories for a post.
5441   *
5442   * If no categories are provided, the default category is used.
5443   *
5444   * @since 2.1.0
5445   *
5446   * @param int       $post_id         Optional. The Post ID. Does not default to the ID
5447   *                                   of the global $post. Default 0.
5448   * @param int[]|int $post_categories Optional. List of category IDs, or the ID of a single category.
5449   *                                   Default empty array.
5450   * @param bool      $append          If true, don't delete existing categories, just add on.
5451   *                                   If false, replace the categories with the new categories.
5452   * @return array|false|WP_Error Array of term taxonomy IDs of affected categories. WP_Error or false on failure.
5453   */
5454  function wp_set_post_categories( $post_id = 0, $post_categories = array(), $append = false ) {
5455      $post_id     = (int) $post_id;
5456      $post_type   = get_post_type( $post_id );
5457      $post_status = get_post_status( $post_id );
5458  
5459      // If $post_categories isn't already an array, make it one.
5460      $post_categories = (array) $post_categories;
5461  
5462      if ( empty(