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