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