| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * REST API: WP_REST_Posts_Controller class 4 * 5 * @package WordPress 6 * @subpackage REST_API 7 * @since 4.7.0 8 */ 9 10 /** 11 * Core class to access posts via the REST API. 12 * 13 * @since 4.7.0 14 * 15 * @see WP_REST_Controller 16 */ 17 class WP_REST_Posts_Controller extends WP_REST_Controller { 18 /** 19 * Post type. 20 * 21 * @since 4.7.0 22 * @var string 23 */ 24 protected $post_type; 25 26 /** 27 * Instance of a post meta fields object. 28 * 29 * @since 4.7.0 30 * @var WP_REST_Post_Meta_Fields 31 */ 32 protected $meta; 33 34 /** 35 * Passwordless post access permitted. 36 * 37 * @since 5.7.1 38 * @var int[] 39 */ 40 protected $password_check_passed = array(); 41 42 /** 43 * Whether the controller supports batching. 44 * 45 * @since 5.9.0 46 * @var array|false 47 */ 48 protected $allow_batch = array( 'v1' => true ); 49 50 /** 51 * Constructor. 52 * 53 * @since 4.7.0 54 * 55 * @param string $post_type Post type. 56 */ 57 public function __construct( $post_type ) { 58 $this->post_type = $post_type; 59 $obj = get_post_type_object( $post_type ); 60 $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name; 61 $this->namespace = ! empty( $obj->rest_namespace ) ? $obj->rest_namespace : 'wp/v2'; 62 63 $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type ); 64 } 65 66 /** 67 * Registers the routes for posts. 68 * 69 * @since 4.7.0 70 * 71 * @see register_rest_route() 72 */ 73 public function register_routes() { 74 75 register_rest_route( 76 $this->namespace, 77 '/' . $this->rest_base, 78 array( 79 array( 80 'methods' => WP_REST_Server::READABLE, 81 'callback' => array( $this, 'get_items' ), 82 'permission_callback' => array( $this, 'get_items_permissions_check' ), 83 'args' => $this->get_collection_params(), 84 ), 85 array( 86 'methods' => WP_REST_Server::CREATABLE, 87 'callback' => array( $this, 'create_item' ), 88 'permission_callback' => array( $this, 'create_item_permissions_check' ), 89 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ), 90 ), 91 'allow_batch' => $this->allow_batch, 92 'schema' => array( $this, 'get_public_item_schema' ), 93 ) 94 ); 95 96 $schema = $this->get_item_schema(); 97 $get_item_args = array( 98 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 99 ); 100 if ( isset( $schema['properties']['excerpt'] ) ) { 101 $get_item_args['excerpt_length'] = array( 102 'description' => __( 'Override the default excerpt length.' ), 103 'type' => 'integer', 104 ); 105 } 106 if ( isset( $schema['properties']['password'] ) ) { 107 $get_item_args['password'] = array( 108 'description' => __( 'The password for the post if it is password protected.' ), 109 'type' => 'string', 110 ); 111 } 112 register_rest_route( 113 $this->namespace, 114 '/' . $this->rest_base . '/(?P<id>[\d]+)', 115 array( 116 'args' => array( 117 'id' => array( 118 'description' => __( 'Unique identifier for the post.' ), 119 'type' => 'integer', 120 ), 121 ), 122 array( 123 'methods' => WP_REST_Server::READABLE, 124 'callback' => array( $this, 'get_item' ), 125 'permission_callback' => array( $this, 'get_item_permissions_check' ), 126 'args' => $get_item_args, 127 ), 128 array( 129 'methods' => WP_REST_Server::EDITABLE, 130 'callback' => array( $this, 'update_item' ), 131 'permission_callback' => array( $this, 'update_item_permissions_check' ), 132 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), 133 ), 134 array( 135 'methods' => WP_REST_Server::DELETABLE, 136 'callback' => array( $this, 'delete_item' ), 137 'permission_callback' => array( $this, 'delete_item_permissions_check' ), 138 'args' => array( 139 'force' => array( 140 'type' => 'boolean', 141 'default' => false, 142 'description' => __( 'Whether to bypass Trash and force deletion.' ), 143 ), 144 ), 145 ), 146 'allow_batch' => $this->allow_batch, 147 'schema' => array( $this, 'get_public_item_schema' ), 148 ) 149 ); 150 } 151 152 /** 153 * Checks if a given request has access to read posts. 154 * 155 * @since 4.7.0 156 * 157 * @param WP_REST_Request $request Full details about the request. 158 * @return true|WP_Error True if the request has read access, WP_Error object otherwise. 159 */ 160 public function get_items_permissions_check( $request ) { 161 162 $post_type = get_post_type_object( $this->post_type ); 163 164 if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) { 165 return new WP_Error( 166 'rest_forbidden_context', 167 __( 'Sorry, you are not allowed to edit posts in this post type.' ), 168 array( 'status' => rest_authorization_required_code() ) 169 ); 170 } 171 172 return true; 173 } 174 175 /** 176 * Overrides the result of the post password check for REST requested posts. 177 * 178 * Allow users to read the content of password protected posts if they have 179 * previously passed a permission check or if they have the `edit_post` capability 180 * for the post being checked. 181 * 182 * @since 5.7.1 183 * 184 * @param bool $required Whether the post requires a password check. 185 * @param WP_Post|null $post The post being password checked, or null if no post is found. 186 * @return bool Result of password check taking into account REST API considerations. 187 */ 188 public function check_password_required( $required, $post ) { 189 if ( ! $required ) { 190 return $required; 191 } 192 193 $post = get_post( $post ); 194 195 if ( ! $post ) { 196 return $required; 197 } 198 199 if ( ! empty( $this->password_check_passed[ $post->ID ] ) ) { 200 // Password previously checked and approved. 201 return false; 202 } 203 204 return ! current_user_can( 'edit_post', $post->ID ); 205 } 206 207 /** 208 * Retrieves a collection of posts. 209 * 210 * @since 4.7.0 211 * 212 * @param WP_REST_Request $request Full details about the request. 213 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. 214 */ 215 public function get_items( $request ) { 216 217 // Ensure a search string is set in case the orderby is set to 'relevance'. 218 if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) { 219 return new WP_Error( 220 'rest_no_search_term_defined', 221 __( 'You need to define a search term to order by relevance.' ), 222 array( 'status' => 400 ) 223 ); 224 } 225 226 // Ensure an include parameter is set in case the orderby is set to 'include'. 227 if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) { 228 return new WP_Error( 229 'rest_orderby_include_missing_include', 230 __( 'You need to define an include parameter to order by include.' ), 231 array( 'status' => 400 ) 232 ); 233 } 234 235 // Retrieve the list of registered collection query parameters. 236 $registered = $this->get_collection_params(); 237 $args = array(); 238 239 /* 240 * This array defines mappings between public API query parameters whose 241 * values are accepted as-passed, and their internal WP_Query parameter 242 * name equivalents (some are the same). Only values which are also 243 * present in $registered will be set. 244 */ 245 $parameter_mappings = array( 246 'author' => 'author__in', 247 'author_exclude' => 'author__not_in', 248 'exclude' => 'post__not_in', 249 'include' => 'post__in', 250 'ignore_sticky' => 'ignore_sticky_posts', 251 'menu_order' => 'menu_order', 252 'offset' => 'offset', 253 'order' => 'order', 254 'orderby' => 'orderby', 255 'page' => 'paged', 256 'parent' => 'post_parent__in', 257 'parent_exclude' => 'post_parent__not_in', 258 'search' => 's', 259 'search_columns' => 'search_columns', 260 'slug' => 'post_name__in', 261 'status' => 'post_status', 262 ); 263 264 /* 265 * For each known parameter which is both registered and present in the request, 266 * set the parameter's value on the query $args. 267 */ 268 foreach ( $parameter_mappings as $api_param => $wp_param ) { 269 if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) { 270 $args[ $wp_param ] = $request[ $api_param ]; 271 } 272 } 273 274 // Check for & assign any parameters which require special handling or setting. 275 $args['date_query'] = array(); 276 277 if ( isset( $registered['before'], $request['before'] ) ) { 278 $args['date_query'][] = array( 279 'before' => $request['before'], 280 'column' => 'post_date', 281 ); 282 } 283 284 if ( isset( $registered['modified_before'], $request['modified_before'] ) ) { 285 $args['date_query'][] = array( 286 'before' => $request['modified_before'], 287 'column' => 'post_modified', 288 ); 289 } 290 291 if ( isset( $registered['after'], $request['after'] ) ) { 292 $args['date_query'][] = array( 293 'after' => $request['after'], 294 'column' => 'post_date', 295 ); 296 } 297 298 if ( isset( $registered['modified_after'], $request['modified_after'] ) ) { 299 $args['date_query'][] = array( 300 'after' => $request['modified_after'], 301 'column' => 'post_modified', 302 ); 303 } 304 305 // Ensure our per_page parameter overrides any provided posts_per_page filter. 306 if ( isset( $registered['per_page'] ) ) { 307 $args['posts_per_page'] = $request['per_page']; 308 } 309 310 if ( isset( $registered['sticky'], $request['sticky'] ) ) { 311 $sticky_posts = get_option( 'sticky_posts', array() ); 312 if ( ! is_array( $sticky_posts ) ) { 313 $sticky_posts = array(); 314 } 315 if ( $request['sticky'] ) { 316 /* 317 * As post__in will be used to only get sticky posts, 318 * we have to support the case where post__in was already 319 * specified. 320 */ 321 $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts; 322 323 /* 324 * If we intersected, but there are no post IDs in common, 325 * WP_Query won't return "no posts" for post__in = array() 326 * so we have to fake it a bit. 327 */ 328 if ( ! $args['post__in'] ) { 329 $args['post__in'] = array( 0 ); 330 } 331 } elseif ( $sticky_posts ) { 332 /* 333 * As post___not_in will be used to only get posts that 334 * are not sticky, we have to support the case where post__not_in 335 * was already specified. 336 */ 337 $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts ); 338 } 339 } 340 341 /* 342 * Honor the original REST API `post__in` behavior. Don't prepend sticky posts 343 * when `post__in` has been specified. 344 */ 345 if ( ! empty( $args['post__in'] ) ) { 346 unset( $args['ignore_sticky_posts'] ); 347 } 348 349 if ( 350 isset( $registered['search_semantics'], $request['search_semantics'] ) 351 && 'exact' === $request['search_semantics'] 352 ) { 353 $args['exact'] = true; 354 } 355 356 $args = $this->prepare_tax_query( $args, $request ); 357 358 if ( isset( $registered['format'], $request['format'] ) ) { 359 $formats = $request['format']; 360 /* 361 * The relation needs to be set to `OR` since the request can contain 362 * two separate conditions. The user may be querying for items that have 363 * either the `standard` format or a specific format. 364 */ 365 $formats_query = array( 'relation' => 'OR' ); 366 367 /* 368 * The default post format, `standard`, is not stored in the database. 369 * If `standard` is part of the request, the query needs to exclude all post items that 370 * have a format assigned. 371 */ 372 if ( in_array( 'standard', $formats, true ) ) { 373 $formats_query[] = array( 374 'taxonomy' => 'post_format', 375 'field' => 'slug', 376 'operator' => 'NOT EXISTS', 377 ); 378 // Remove the `standard` format, since it cannot be queried. 379 unset( $formats[ array_search( 'standard', $formats, true ) ] ); 380 } 381 382 // Add any remaining formats to the formats query. 383 if ( ! empty( $formats ) ) { 384 // Add the `post-format-` prefix. 385 $terms = array_map( 386 static function ( $format ) { 387 return "post-format-$format"; 388 }, 389 $formats 390 ); 391 392 $formats_query[] = array( 393 'taxonomy' => 'post_format', 394 'field' => 'slug', 395 'terms' => $terms, 396 'operator' => 'IN', 397 ); 398 } 399 400 // Enable filtering by both post formats and other taxonomies by combining them with `AND`. 401 if ( isset( $args['tax_query'] ) ) { 402 $args['tax_query'][] = array( 403 'relation' => 'AND', 404 $formats_query, 405 ); 406 } else { 407 $args['tax_query'] = $formats_query; 408 } 409 } 410 411 // Force the post_type argument, since it's not a user input variable. 412 $args['post_type'] = $this->post_type; 413 414 $is_head_request = $request->is_method( 'HEAD' ); 415 if ( $is_head_request ) { 416 // Force the 'fields' argument. For HEAD requests, only post IDs are required to calculate pagination. 417 $args['fields'] = 'ids'; 418 // Disable priming post meta for HEAD requests to improve performance. 419 $args['update_post_term_cache'] = false; 420 $args['update_post_meta_cache'] = false; 421 } 422 423 /** 424 * Filters WP_Query arguments when querying posts via the REST API. 425 * 426 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 427 * 428 * Possible hook names include: 429 * 430 * - `rest_post_query` 431 * - `rest_page_query` 432 * - `rest_attachment_query` 433 * 434 * Enables adding extra arguments or setting defaults for a post collection request. 435 * 436 * @since 4.7.0 437 * @since 5.7.0 Moved after the `tax_query` query arg is generated. 438 * 439 * @link https://developer.wordpress.org/reference/classes/wp_query/ 440 * 441 * @param array $args Array of arguments for WP_Query. 442 * @param WP_REST_Request $request The REST API request. 443 */ 444 $args = apply_filters( "rest_{$this->post_type}_query", $args, $request ); 445 if ( ! is_array( $args ) ) { 446 $args = array(); 447 } 448 $query_args = $this->prepare_items_query( $args, $request ); 449 450 $posts_query = new WP_Query(); 451 $query_result = $posts_query->query( $query_args ); 452 453 // Allow access to all password protected posts if the context is edit. 454 if ( 'edit' === $request['context'] ) { 455 add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 ); 456 } 457 458 $posts = array(); 459 if ( ! $is_head_request ) { 460 update_post_author_caches( $query_result ); 461 update_post_parent_caches( $query_result ); 462 463 if ( post_type_supports( $this->post_type, 'thumbnail' ) ) { 464 update_post_thumbnail_cache( $posts_query ); 465 } 466 467 foreach ( $query_result as $post ) { 468 if ( 'edit' === $request['context'] ) { 469 $permission = $this->check_update_permission( $post ); 470 } else { 471 $permission = $this->check_read_permission( $post ); 472 } 473 474 if ( ! $permission ) { 475 continue; 476 } 477 478 $data = $this->prepare_item_for_response( $post, $request ); 479 $posts[] = $this->prepare_response_for_collection( $data ); 480 } 481 } 482 483 // Reset filter. 484 if ( 'edit' === $request['context'] ) { 485 remove_filter( 'post_password_required', array( $this, 'check_password_required' ) ); 486 } 487 488 $page = (int) ( $query_args['paged'] ?? 0 ); 489 $total_posts = $posts_query->found_posts; 490 491 if ( $total_posts < 1 && $page > 1 ) { 492 // Out-of-bounds, run the query without pagination/offset to get the total count. 493 unset( $query_args['paged'] ); 494 495 $count_query = new WP_Query(); 496 $query_args['fields'] = 'ids'; 497 $query_args['posts_per_page'] = 1; 498 $query_args['update_post_meta_cache'] = false; 499 $query_args['update_post_term_cache'] = false; 500 501 $count_query->query( $query_args ); 502 $total_posts = $count_query->found_posts; 503 } 504 505 $max_pages = (int) ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] ); 506 507 if ( $page > $max_pages && $total_posts > 0 ) { 508 return new WP_Error( 509 'rest_post_invalid_page_number', 510 __( 'The page number requested is larger than the number of pages available.' ), 511 array( 'status' => 400 ) 512 ); 513 } 514 515 $response = $is_head_request ? new WP_REST_Response( array() ) : rest_ensure_response( $posts ); 516 517 $response->header( 'X-WP-Total', (int) $total_posts ); 518 $response->header( 'X-WP-TotalPages', (int) $max_pages ); 519 520 $request_params = $request->get_query_params(); 521 $collection_url = rest_url( rest_get_route_for_post_type_items( $this->post_type ) ); 522 $base = add_query_arg( urlencode_deep( $request_params ), $collection_url ); 523 524 if ( $page > 1 ) { 525 $prev_page = $page - 1; 526 527 if ( $prev_page > $max_pages ) { 528 $prev_page = $max_pages; 529 } 530 531 $prev_link = add_query_arg( 'page', $prev_page, $base ); 532 $response->link_header( 'prev', $prev_link ); 533 } 534 if ( $max_pages > $page ) { 535 $next_page = $page + 1; 536 $next_link = add_query_arg( 'page', $next_page, $base ); 537 538 $response->link_header( 'next', $next_link ); 539 } 540 541 return $response; 542 } 543 544 /** 545 * Gets the post, if the ID is valid. 546 * 547 * @since 4.7.2 548 * 549 * @param int $id Supplied ID. 550 * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise. 551 */ 552 protected function get_post( $id ) { 553 $error = new WP_Error( 554 'rest_post_invalid_id', 555 __( 'Invalid post ID.' ), 556 array( 'status' => 404 ) 557 ); 558 559 if ( (int) $id <= 0 ) { 560 return $error; 561 } 562 563 $post = get_post( (int) $id ); 564 if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) { 565 return $error; 566 } 567 568 return $post; 569 } 570 571 /** 572 * Checks if a given request has access to read a post. 573 * 574 * @since 4.7.0 575 * 576 * @param WP_REST_Request $request Full details about the request. 577 * @return bool|WP_Error True if the request has read access for the item, WP_Error object or false otherwise. 578 */ 579 public function get_item_permissions_check( $request ) { 580 $post = $this->get_post( $request['id'] ); 581 if ( is_wp_error( $post ) ) { 582 return $post; 583 } 584 585 if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) { 586 return new WP_Error( 587 'rest_forbidden_context', 588 __( 'Sorry, you are not allowed to edit this post.' ), 589 array( 'status' => rest_authorization_required_code() ) 590 ); 591 } 592 593 if ( $post && ! empty( $request->get_query_params()['password'] ) ) { 594 // Check post password, and return error if invalid. 595 if ( ! hash_equals( $post->post_password, $request->get_query_params()['password'] ) ) { 596 return new WP_Error( 597 'rest_post_incorrect_password', 598 __( 'Incorrect post password.' ), 599 array( 'status' => 403 ) 600 ); 601 } 602 } 603 604 // Allow access to all password protected posts if the context is edit. 605 if ( 'edit' === $request['context'] ) { 606 add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 ); 607 } 608 609 if ( $post ) { 610 return $this->check_read_permission( $post ); 611 } 612 613 return true; 614 } 615 616 /** 617 * Checks if the user can access password-protected content. 618 * 619 * This method determines whether we need to override the regular password 620 * check in core with a filter. 621 * 622 * @since 4.7.0 623 * 624 * @param WP_Post $post Post to check against. 625 * @param WP_REST_Request $request Request data to check. 626 * @return bool True if the user can access password-protected content, otherwise false. 627 */ 628 public function can_access_password_content( $post, $request ) { 629 if ( empty( $post->post_password ) ) { 630 // No filter required. 631 return false; 632 } 633 634 /* 635 * Users always gets access to password protected content in the edit 636 * context if they have the `edit_post` meta capability. 637 */ 638 if ( 639 'edit' === $request['context'] && 640 current_user_can( 'edit_post', $post->ID ) 641 ) { 642 return true; 643 } 644 645 // No password, no auth. 646 if ( empty( $request['password'] ) ) { 647 return false; 648 } 649 650 // Double-check the request password. 651 return hash_equals( $post->post_password, $request['password'] ); 652 } 653 654 /** 655 * Retrieves a single post. 656 * 657 * @since 4.7.0 658 * 659 * @param WP_REST_Request $request Full details about the request. 660 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. 661 */ 662 public function get_item( $request ) { 663 $post = $this->get_post( $request['id'] ); 664 if ( is_wp_error( $post ) ) { 665 return $post; 666 } 667 668 $data = $this->prepare_item_for_response( $post, $request ); 669 $response = rest_ensure_response( $data ); 670 671 if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) { 672 $response->link_header( 'alternate', get_permalink( $post->ID ), array( 'type' => 'text/html' ) ); 673 } 674 675 return $response; 676 } 677 678 /** 679 * Checks if a given request has access to create a post. 680 * 681 * @since 4.7.0 682 * 683 * @param WP_REST_Request $request Full details about the request. 684 * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. 685 */ 686 public function create_item_permissions_check( $request ) { 687 if ( ! empty( $request['id'] ) ) { 688 return new WP_Error( 689 'rest_post_exists', 690 __( 'Cannot create existing post.' ), 691 array( 'status' => 400 ) 692 ); 693 } 694 695 $post_type = get_post_type_object( $this->post_type ); 696 697 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) { 698 return new WP_Error( 699 'rest_cannot_edit_others', 700 __( 'Sorry, you are not allowed to create posts as this user.' ), 701 array( 'status' => rest_authorization_required_code() ) 702 ); 703 } 704 705 if ( ! empty( $request['sticky'] ) && ( ! current_user_can( $post_type->cap->edit_others_posts ) || ! current_user_can( $post_type->cap->publish_posts ) ) ) { 706 return new WP_Error( 707 'rest_cannot_assign_sticky', 708 __( 'Sorry, you are not allowed to make posts sticky.' ), 709 array( 'status' => rest_authorization_required_code() ) 710 ); 711 } 712 713 if ( ! current_user_can( $post_type->cap->create_posts ) ) { 714 return new WP_Error( 715 'rest_cannot_create', 716 __( 'Sorry, you are not allowed to create posts as this user.' ), 717 array( 'status' => rest_authorization_required_code() ) 718 ); 719 } 720 721 if ( ! $this->check_assign_terms_permission( $request ) ) { 722 return new WP_Error( 723 'rest_cannot_assign_term', 724 __( 'Sorry, you are not allowed to assign the provided terms.' ), 725 array( 'status' => rest_authorization_required_code() ) 726 ); 727 } 728 729 return true; 730 } 731 732 /** 733 * Creates a single post. 734 * 735 * @since 4.7.0 736 * 737 * @param WP_REST_Request $request Full details about the request. 738 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. 739 */ 740 public function create_item( $request ) { 741 if ( ! empty( $request['id'] ) ) { 742 return new WP_Error( 743 'rest_post_exists', 744 __( 'Cannot create existing post.' ), 745 array( 'status' => 400 ) 746 ); 747 } 748 749 $prepared_post = $this->prepare_item_for_database( $request ); 750 751 if ( is_wp_error( $prepared_post ) ) { 752 return $prepared_post; 753 } 754 755 $prepared_post->post_type = $this->post_type; 756 757 if ( ! empty( $prepared_post->post_name ) 758 && ! empty( $prepared_post->post_status ) 759 && in_array( $prepared_post->post_status, array( 'draft', 'pending' ), true ) 760 ) { 761 /* 762 * `wp_unique_post_slug()` returns the same slug for 'draft' or 'pending' posts. 763 * 764 * To ensure that a unique slug is generated, pass the post data with the 'publish' status. 765 */ 766 $prepared_post->post_name = wp_unique_post_slug( 767 $prepared_post->post_name, 768 $prepared_post->id, 769 'publish', 770 $prepared_post->post_type, 771 $prepared_post->post_parent 772 ); 773 } 774 775 $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true, false ); 776 777 if ( is_wp_error( $post_id ) ) { 778 779 if ( 'db_insert_error' === $post_id->get_error_code() ) { 780 $post_id->add_data( array( 'status' => 500 ) ); 781 } else { 782 $post_id->add_data( array( 'status' => 400 ) ); 783 } 784 785 return $post_id; 786 } 787 788 $post = get_post( $post_id ); 789 790 /** 791 * Fires after a single post is created or updated via the REST API. 792 * 793 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 794 * 795 * Possible hook names include: 796 * 797 * - `rest_insert_post` 798 * - `rest_insert_page` 799 * - `rest_insert_attachment` 800 * 801 * @since 4.7.0 802 * 803 * @param WP_Post $post Inserted or updated post object. 804 * @param WP_REST_Request $request Request object. 805 * @param bool $creating True when creating a post, false when updating. 806 */ 807 do_action( "rest_insert_{$this->post_type}", $post, $request, true ); 808 809 $schema = $this->get_item_schema(); 810 811 if ( ! empty( $schema['properties']['sticky'] ) ) { 812 if ( ! empty( $request['sticky'] ) ) { 813 stick_post( $post_id ); 814 } else { 815 unstick_post( $post_id ); 816 } 817 } 818 819 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { 820 $this->handle_featured_media( $request['featured_media'], $post_id ); 821 } 822 823 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) { 824 set_post_format( $post, $request['format'] ); 825 } 826 827 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) { 828 $this->handle_template( $request['template'], $post_id, true ); 829 } 830 831 $terms_update = $this->handle_terms( $post_id, $request ); 832 833 if ( is_wp_error( $terms_update ) ) { 834 return $terms_update; 835 } 836 837 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { 838 $meta_update = $this->meta->update_value( $request['meta'], $post_id ); 839 840 if ( is_wp_error( $meta_update ) ) { 841 return $meta_update; 842 } 843 } 844 845 $post = get_post( $post_id ); 846 $fields_update = $this->update_additional_fields_for_object( $post, $request ); 847 848 if ( is_wp_error( $fields_update ) ) { 849 return $fields_update; 850 } 851 852 $request->set_param( 'context', 'edit' ); 853 854 /** 855 * Fires after a single post is completely created or updated via the REST API. 856 * 857 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 858 * 859 * Possible hook names include: 860 * 861 * - `rest_after_insert_post` 862 * - `rest_after_insert_page` 863 * - `rest_after_insert_attachment` 864 * 865 * @since 5.0.0 866 * 867 * @param WP_Post $post Inserted or updated post object. 868 * @param WP_REST_Request $request Request object. 869 * @param bool $creating True when creating a post, false when updating. 870 */ 871 do_action( "rest_after_insert_{$this->post_type}", $post, $request, true ); 872 873 wp_after_insert_post( $post, false, null ); 874 875 $response = $this->prepare_item_for_response( $post, $request ); 876 $response = rest_ensure_response( $response ); 877 878 $response->set_status( 201 ); 879 $response->header( 'Location', rest_url( rest_get_route_for_post( $post ) ) ); 880 881 return $response; 882 } 883 884 /** 885 * Checks if a given request has access to update a post. 886 * 887 * @since 4.7.0 888 * 889 * @param WP_REST_Request $request Full details about the request. 890 * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. 891 */ 892 public function update_item_permissions_check( $request ) { 893 $post = $this->get_post( $request['id'] ); 894 if ( is_wp_error( $post ) ) { 895 return $post; 896 } 897 898 $post_type = get_post_type_object( $this->post_type ); 899 900 if ( $post && ! $this->check_update_permission( $post ) ) { 901 return new WP_Error( 902 'rest_cannot_edit', 903 __( 'Sorry, you are not allowed to edit this post.' ), 904 array( 'status' => rest_authorization_required_code() ) 905 ); 906 } 907 908 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) { 909 return new WP_Error( 910 'rest_cannot_edit_others', 911 __( 'Sorry, you are not allowed to update posts as this user.' ), 912 array( 'status' => rest_authorization_required_code() ) 913 ); 914 } 915 916 if ( isset( $request['sticky'] ) && is_sticky( $post->ID ) !== (bool) $request['sticky'] && ( ! current_user_can( $post_type->cap->edit_others_posts ) || ! current_user_can( $post_type->cap->publish_posts ) ) ) { 917 return new WP_Error( 918 'rest_cannot_assign_sticky', 919 __( 'Sorry, you are not allowed to make posts sticky.' ), 920 array( 'status' => rest_authorization_required_code() ) 921 ); 922 } 923 924 if ( ! $this->check_assign_terms_permission( $request ) ) { 925 return new WP_Error( 926 'rest_cannot_assign_term', 927 __( 'Sorry, you are not allowed to assign the provided terms.' ), 928 array( 'status' => rest_authorization_required_code() ) 929 ); 930 } 931 932 return true; 933 } 934 935 /** 936 * Updates a single post. 937 * 938 * @since 4.7.0 939 * 940 * @param WP_REST_Request $request Full details about the request. 941 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. 942 */ 943 public function update_item( $request ) { 944 $valid_check = $this->get_post( $request['id'] ); 945 if ( is_wp_error( $valid_check ) ) { 946 return $valid_check; 947 } 948 949 $post_before = get_post( $request['id'] ); 950 $post = $this->prepare_item_for_database( $request ); 951 952 if ( is_wp_error( $post ) ) { 953 return $post; 954 } 955 956 if ( ! empty( $post->post_status ) ) { 957 $post_status = $post->post_status; 958 } else { 959 $post_status = $post_before->post_status; 960 } 961 962 /* 963 * `wp_unique_post_slug()` returns the same slug for 'draft' or 'pending' posts. 964 * 965 * To ensure that a unique slug is generated, pass the post data with the 'publish' status. 966 */ 967 if ( ! empty( $post->post_name ) && in_array( $post_status, array( 'draft', 'pending' ), true ) ) { 968 $post_parent = ! empty( $post->post_parent ) ? $post->post_parent : 0; 969 $post->post_name = wp_unique_post_slug( 970 $post->post_name, 971 $post->ID, 972 'publish', 973 $post->post_type, 974 $post_parent 975 ); 976 } 977 978 // Convert the post object to an array, otherwise wp_update_post() will expect non-escaped input. 979 $post_id = wp_update_post( wp_slash( (array) $post ), true, false ); 980 981 if ( is_wp_error( $post_id ) ) { 982 if ( 'db_update_error' === $post_id->get_error_code() ) { 983 $post_id->add_data( array( 'status' => 500 ) ); 984 } else { 985 $post_id->add_data( array( 'status' => 400 ) ); 986 } 987 return $post_id; 988 } 989 990 $post = get_post( $post_id ); 991 992 /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ 993 do_action( "rest_insert_{$this->post_type}", $post, $request, false ); 994 995 $schema = $this->get_item_schema(); 996 997 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) { 998 set_post_format( $post, $request['format'] ); 999 } 1000 1001 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { 1002 $this->handle_featured_media( $request['featured_media'], $post_id ); 1003 } 1004 1005 if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) { 1006 if ( ! empty( $request['sticky'] ) ) { 1007 stick_post( $post_id ); 1008 } else { 1009 unstick_post( $post_id ); 1010 } 1011 } 1012 1013 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) { 1014 $this->handle_template( $request['template'], $post->ID ); 1015 } 1016 1017 $terms_update = $this->handle_terms( $post->ID, $request ); 1018 1019 if ( is_wp_error( $terms_update ) ) { 1020 return $terms_update; 1021 } 1022 1023 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { 1024 $meta_update = $this->meta->update_value( $request['meta'], $post->ID ); 1025 1026 if ( is_wp_error( $meta_update ) ) { 1027 return $meta_update; 1028 } 1029 } 1030 1031 $post = get_post( $post_id ); 1032 $fields_update = $this->update_additional_fields_for_object( $post, $request ); 1033 1034 if ( is_wp_error( $fields_update ) ) { 1035 return $fields_update; 1036 } 1037 1038 $request->set_param( 'context', 'edit' ); 1039 1040 // Filter is fired in WP_REST_Attachments_Controller subclass. 1041 if ( 'attachment' === $this->post_type ) { 1042 $response = $this->prepare_item_for_response( $post, $request ); 1043 return rest_ensure_response( $response ); 1044 } 1045 1046 /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ 1047 do_action( "rest_after_insert_{$this->post_type}", $post, $request, false ); 1048 1049 wp_after_insert_post( $post, true, $post_before ); 1050 1051 $response = $this->prepare_item_for_response( $post, $request ); 1052 1053 return rest_ensure_response( $response ); 1054 } 1055 1056 /** 1057 * Checks if a given request has access to delete a post. 1058 * 1059 * @since 4.7.0 1060 * 1061 * @param WP_REST_Request $request Full details about the request. 1062 * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. 1063 */ 1064 public function delete_item_permissions_check( $request ) { 1065 $post = $this->get_post( $request['id'] ); 1066 if ( is_wp_error( $post ) ) { 1067 return $post; 1068 } 1069 1070 if ( $post && ! $this->check_delete_permission( $post ) ) { 1071 return new WP_Error( 1072 'rest_cannot_delete', 1073 __( 'Sorry, you are not allowed to delete this post.' ), 1074 array( 'status' => rest_authorization_required_code() ) 1075 ); 1076 } 1077 1078 return true; 1079 } 1080 1081 /** 1082 * Deletes a single post. 1083 * 1084 * @since 4.7.0 1085 * 1086 * @param WP_REST_Request $request Full details about the request. 1087 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. 1088 */ 1089 public function delete_item( $request ) { 1090 $post = $this->get_post( $request['id'] ); 1091 if ( is_wp_error( $post ) ) { 1092 return $post; 1093 } 1094 1095 $id = $post->ID; 1096 $force = (bool) $request['force']; 1097 1098 $supports_trash = ( EMPTY_TRASH_DAYS > 0 ); 1099 1100 if ( 'attachment' === $post->post_type ) { 1101 $supports_trash = $supports_trash && MEDIA_TRASH; 1102 } 1103 1104 /** 1105 * Filters whether a post is trashable. 1106 * 1107 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 1108 * 1109 * Possible hook names include: 1110 * 1111 * - `rest_post_trashable` 1112 * - `rest_page_trashable` 1113 * - `rest_attachment_trashable` 1114 * 1115 * Pass false to disable Trash support for the post. 1116 * 1117 * @since 4.7.0 1118 * 1119 * @param bool $supports_trash Whether the post type support trashing. 1120 * @param WP_Post $post The Post object being considered for trashing support. 1121 */ 1122 $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post ); 1123 1124 if ( ! $this->check_delete_permission( $post ) ) { 1125 return new WP_Error( 1126 'rest_user_cannot_delete_post', 1127 __( 'Sorry, you are not allowed to delete this post.' ), 1128 array( 'status' => rest_authorization_required_code() ) 1129 ); 1130 } 1131 1132 $request->set_param( 'context', 'edit' ); 1133 1134 // If we're forcing, then delete permanently. 1135 if ( $force ) { 1136 $previous = $this->prepare_item_for_response( $post, $request ); 1137 $result = wp_delete_post( $id, true ); 1138 $response = new WP_REST_Response(); 1139 $response->set_data( 1140 array( 1141 'deleted' => true, 1142 'previous' => $previous->get_data(), 1143 ) 1144 ); 1145 } else { 1146 // If we don't support trashing for this type, error out. 1147 if ( ! $supports_trash ) { 1148 return new WP_Error( 1149 'rest_trash_not_supported', 1150 /* translators: %s: force=true */ 1151 sprintf( __( "The post does not support trashing. Set '%s' to delete." ), 'force=true' ), 1152 array( 'status' => 501 ) 1153 ); 1154 } 1155 1156 // Otherwise, only trash if we haven't already. 1157 if ( 'trash' === $post->post_status ) { 1158 return new WP_Error( 1159 'rest_already_trashed', 1160 __( 'The post has already been deleted.' ), 1161 array( 'status' => 410 ) 1162 ); 1163 } 1164 1165 /* 1166 * (Note that internally this falls through to `wp_delete_post()` 1167 * if the Trash is disabled.) 1168 */ 1169 $result = wp_trash_post( $id ); 1170 $post = get_post( $id ); 1171 $response = $this->prepare_item_for_response( $post, $request ); 1172 } 1173 1174 if ( ! $result ) { 1175 return new WP_Error( 1176 'rest_cannot_delete', 1177 __( 'The post cannot be deleted.' ), 1178 array( 'status' => 500 ) 1179 ); 1180 } 1181 1182 /** 1183 * Fires immediately after a single post is deleted or trashed via the REST API. 1184 * 1185 * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 1186 * 1187 * Possible hook names include: 1188 * 1189 * - `rest_delete_post` 1190 * - `rest_delete_page` 1191 * - `rest_delete_attachment` 1192 * 1193 * @since 4.7.0 1194 * 1195 * @param WP_Post $post The deleted or trashed post. 1196 * @param WP_REST_Response $response The response data. 1197 * @param WP_REST_Request $request The request sent to the API. 1198 */ 1199 do_action( "rest_delete_{$this->post_type}", $post, $response, $request ); 1200 1201 return $response; 1202 } 1203 1204 /** 1205 * Determines the allowed query_vars for a get_items() response and prepares 1206 * them for WP_Query. 1207 * 1208 * @since 4.7.0 1209 * 1210 * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array. 1211 * @param WP_REST_Request $request Optional. Full details about the request. 1212 * @return array Items query arguments. 1213 */ 1214 protected function prepare_items_query( $prepared_args = array(), $request = null ) { 1215 $query_args = array(); 1216 if ( ! is_array( $prepared_args ) ) { 1217 $prepared_args = array(); 1218 } 1219 1220 foreach ( $prepared_args as $key => $value ) { 1221 /** 1222 * Filters the query_vars used in get_items() for the constructed query. 1223 * 1224 * The dynamic portion of the hook name, `$key`, refers to the query_var key. 1225 * 1226 * @since 4.7.0 1227 * 1228 * @param string $value The query_var value. 1229 */ 1230 $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores 1231 } 1232 1233 if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) { 1234 $query_args['ignore_sticky_posts'] = true; 1235 } 1236 1237 // Map to proper WP_Query orderby param. 1238 if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) { 1239 $orderby_mappings = array( 1240 'id' => 'ID', 1241 'include' => 'post__in', 1242 'slug' => 'post_name', 1243 'include_slugs' => 'post_name__in', 1244 ); 1245 1246 if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) { 1247 $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ]; 1248 } 1249 } 1250 1251 return $query_args; 1252 } 1253 1254 /** 1255 * Checks the post_date_gmt or modified_gmt and prepare any post or 1256 * modified date for single post output. 1257 * 1258 * @since 4.7.0 1259 * 1260 * @param string $date_gmt GMT publication time. 1261 * @param string|null $date Optional. Local publication time. Default null. 1262 * @return string|null ISO8601/RFC3339 formatted datetime. 1263 */ 1264 protected function prepare_date_response( $date_gmt, $date = null ) { 1265 // Use the date if passed. 1266 if ( isset( $date ) ) { 1267 return mysql_to_rfc3339( $date ); 1268 } 1269 1270 // Return null if $date_gmt is empty/zeros. 1271 if ( '0000-00-00 00:00:00' === $date_gmt ) { 1272 return null; 1273 } 1274 1275 // Return the formatted datetime. 1276 return mysql_to_rfc3339( $date_gmt ); 1277 } 1278 1279 /** 1280 * Prepares a single post for create or update. 1281 * 1282 * @since 4.7.0 1283 * 1284 * @param WP_REST_Request $request Request object. 1285 * @return stdClass|WP_Error Post object or WP_Error. 1286 */ 1287 protected function prepare_item_for_database( $request ) { 1288 $prepared_post = new stdClass(); 1289 $current_status = ''; 1290 1291 // Post ID. 1292 if ( isset( $request['id'] ) ) { 1293 $existing_post = $this->get_post( $request['id'] ); 1294 if ( is_wp_error( $existing_post ) ) { 1295 return $existing_post; 1296 } 1297 1298 $prepared_post->ID = $existing_post->ID; 1299 $current_status = $existing_post->post_status; 1300 } 1301 1302 $schema = $this->get_item_schema(); 1303 1304 // Post title. 1305 if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) { 1306 if ( is_string( $request['title'] ) ) { 1307 $prepared_post->post_title = $request['title']; 1308 } elseif ( ! empty( $request['title']['raw'] ) ) { 1309 $prepared_post->post_title = $request['title']['raw']; 1310 } 1311 } 1312 1313 // Post content. 1314 if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) { 1315 if ( is_string( $request['content'] ) ) { 1316 $prepared_post->post_content = $request['content']; 1317 } elseif ( isset( $request['content']['raw'] ) ) { 1318 $prepared_post->post_content = $request['content']['raw']; 1319 } 1320 } 1321 1322 // Post excerpt. 1323 if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) { 1324 if ( is_string( $request['excerpt'] ) ) { 1325 $prepared_post->post_excerpt = $request['excerpt']; 1326 } elseif ( isset( $request['excerpt']['raw'] ) ) { 1327 $prepared_post->post_excerpt = $request['excerpt']['raw']; 1328 } 1329 } 1330 1331 // Post type. 1332 if ( empty( $request['id'] ) ) { 1333 // Creating new post, use default type for the controller. 1334 $prepared_post->post_type = $this->post_type; 1335 } else { 1336 // Updating a post, use previous type. 1337 $prepared_post->post_type = get_post_type( $request['id'] ); 1338 } 1339 1340 $post_type = get_post_type_object( $prepared_post->post_type ); 1341 1342 // Post status. 1343 if ( 1344 ! empty( $schema['properties']['status'] ) && 1345 isset( $request['status'] ) && 1346 ( ! $current_status || $current_status !== $request['status'] ) 1347 ) { 1348 $status = $this->handle_status_param( $request['status'], $post_type ); 1349 1350 if ( is_wp_error( $status ) ) { 1351 return $status; 1352 } 1353 1354 $prepared_post->post_status = $status; 1355 } 1356 1357 // Post date. 1358 if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) { 1359 $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date : false; 1360 $date_data = rest_get_date_with_gmt( $request['date'] ); 1361 1362 if ( ! empty( $date_data ) && $current_date !== $date_data[0] ) { 1363 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data; 1364 $prepared_post->edit_date = true; 1365 } 1366 } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) { 1367 $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date_gmt : false; 1368 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true ); 1369 1370 if ( ! empty( $date_data ) && $current_date !== $date_data[1] ) { 1371 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data; 1372 $prepared_post->edit_date = true; 1373 } 1374 } 1375 1376 /* 1377 * Sending a null date or date_gmt value resets date and date_gmt to their 1378 * default values (`0000-00-00 00:00:00`). 1379 */ 1380 if ( 1381 ( ! empty( $schema['properties']['date_gmt'] ) && $request->has_param( 'date_gmt' ) && null === $request['date_gmt'] ) || 1382 ( ! empty( $schema['properties']['date'] ) && $request->has_param( 'date' ) && null === $request['date'] ) 1383 ) { 1384 $prepared_post->post_date_gmt = null; 1385 $prepared_post->post_date = null; 1386 } 1387 1388 // Post slug. 1389 if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) { 1390 $prepared_post->post_name = $request['slug']; 1391 } 1392 1393 // Author. 1394 if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) { 1395 $post_author = (int) $request['author']; 1396 $current_author = isset( $existing_post ) ? (int) $existing_post->post_author : 0; 1397 1398 if ( get_current_user_id() !== $post_author && $current_author !== $post_author ) { 1399 if ( ! is_user_member_of_blog( $post_author ) ) { 1400 return new WP_Error( 1401 'rest_invalid_author', 1402 __( 'Invalid author ID.' ), 1403 array( 'status' => 400 ) 1404 ); 1405 } 1406 } 1407 1408 $prepared_post->post_author = $post_author; 1409 } 1410 1411 // Post password. 1412 if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) { 1413 $prepared_post->post_password = $request['password']; 1414 1415 if ( '' !== $request['password'] ) { 1416 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) { 1417 return new WP_Error( 1418 'rest_invalid_field', 1419 __( 'A post can not be sticky and have a password.' ), 1420 array( 'status' => 400 ) 1421 ); 1422 } 1423 1424 if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) { 1425 return new WP_Error( 1426 'rest_invalid_field', 1427 __( 'A sticky post can not be password protected.' ), 1428 array( 'status' => 400 ) 1429 ); 1430 } 1431 } 1432 } 1433 1434 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) { 1435 if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) { 1436 return new WP_Error( 1437 'rest_invalid_field', 1438 __( 'A password protected post can not be set to sticky.' ), 1439 array( 'status' => 400 ) 1440 ); 1441 } 1442 } 1443 1444 // Parent. 1445 if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) { 1446 if ( 0 === (int) $request['parent'] ) { 1447 $prepared_post->post_parent = 0; 1448 } else { 1449 $parent = get_post( (int) $request['parent'] ); 1450 1451 if ( empty( $parent ) ) { 1452 return new WP_Error( 1453 'rest_post_invalid_id', 1454 __( 'Invalid post parent ID.' ), 1455 array( 'status' => 400 ) 1456 ); 1457 } 1458 1459 $prepared_post->post_parent = (int) $parent->ID; 1460 } 1461 } 1462 1463 // Menu order. 1464 if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) { 1465 $prepared_post->menu_order = (int) $request['menu_order']; 1466 } 1467 1468 // Comment status. 1469 if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) { 1470 $prepared_post->comment_status = $request['comment_status']; 1471 } 1472 1473 // Ping status. 1474 if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) { 1475 $prepared_post->ping_status = $request['ping_status']; 1476 } 1477 1478 if ( ! empty( $schema['properties']['template'] ) ) { 1479 // Force template to null so that it can be handled exclusively by the REST controller. 1480 $prepared_post->page_template = null; 1481 } 1482 1483 /** 1484 * Applies Block Hooks to content-like post types. 1485 * 1486 * Content-like post types are those that support the editor and would benefit 1487 * from Block Hooks functionality. This replaces the individual post type filters 1488 * that were previously hardcoded in default-filters.php. 1489 * 1490 * @since 7.0.0 1491 */ 1492 $content_like_post_types = array( 'post', 'page', 'wp_block', 'wp_navigation' ); 1493 1494 /** 1495 * Filters which post types should have Block Hooks applied. 1496 * 1497 * Allows themes and plugins to add or remove post types that should 1498 * have Block Hooks functionality enabled in the REST API. 1499 * 1500 * @since 7.0.0 1501 * 1502 * @param string[] $content_like_post_types Array of post type names that support Block Hooks. 1503 * @param string $post_type The current post type being processed. 1504 * @param stdClass|WP_Post $prepared_post The prepared post object. 1505 */ 1506 $content_like_post_types = apply_filters( 'rest_block_hooks_post_types', $content_like_post_types, $this->post_type, $prepared_post ); 1507 1508 if ( in_array( $this->post_type, $content_like_post_types, true ) ) { 1509 $prepared_post = update_ignored_hooked_blocks_postmeta( $prepared_post ); 1510 } 1511 1512 /** 1513 * Filters a post before it is inserted via the REST API. 1514 * 1515 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 1516 * 1517 * Possible hook names include: 1518 * 1519 * - `rest_pre_insert_post` 1520 * - `rest_pre_insert_page` 1521 * - `rest_pre_insert_attachment` 1522 * 1523 * @since 4.7.0 1524 * 1525 * @param stdClass $prepared_post An object representing a single post prepared 1526 * for inserting or updating the database. 1527 * @param WP_REST_Request $request Request object. 1528 */ 1529 return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request ); 1530 } 1531 1532 /** 1533 * Checks whether the status is valid for the given post. 1534 * 1535 * Allows for sending an update request with the current status, even if that status would not be acceptable. 1536 * 1537 * @since 5.6.0 1538 * 1539 * @param string $status The provided status. 1540 * @param WP_REST_Request $request The request object. 1541 * @param string $param The parameter name. 1542 * @return true|WP_Error True if the status is valid, or WP_Error if not. 1543 */ 1544 public function check_status( $status, $request, $param ) { 1545 if ( $request['id'] ) { 1546 $post = $this->get_post( $request['id'] ); 1547 1548 if ( ! is_wp_error( $post ) && $post->post_status === $status ) { 1549 return true; 1550 } 1551 } 1552 1553 $args = $request->get_attributes()['args'][ $param ]; 1554 1555 return rest_validate_value_from_schema( $status, $args, $param ); 1556 } 1557 1558 /** 1559 * Determines validity and normalizes the given status parameter. 1560 * 1561 * @since 4.7.0 1562 * 1563 * @param string $post_status Post status. 1564 * @param WP_Post_Type $post_type Post type. 1565 * @return string|WP_Error Post status or WP_Error if lacking the proper permission. 1566 */ 1567 protected function handle_status_param( $post_status, $post_type ) { 1568 1569 switch ( $post_status ) { 1570 case 'draft': 1571 case 'pending': 1572 break; 1573 case 'private': 1574 if ( ! current_user_can( $post_type->cap->publish_posts ) ) { 1575 return new WP_Error( 1576 'rest_cannot_publish', 1577 __( 'Sorry, you are not allowed to create private posts in this post type.' ), 1578 array( 'status' => rest_authorization_required_code() ) 1579 ); 1580 } 1581 break; 1582 case 'publish': 1583 case 'future': 1584 if ( ! current_user_can( $post_type->cap->publish_posts ) ) { 1585 return new WP_Error( 1586 'rest_cannot_publish', 1587 __( 'Sorry, you are not allowed to publish posts in this post type.' ), 1588 array( 'status' => rest_authorization_required_code() ) 1589 ); 1590 } 1591 break; 1592 default: 1593 if ( ! get_post_status_object( $post_status ) ) { 1594 $post_status = 'draft'; 1595 } 1596 break; 1597 } 1598 1599 return $post_status; 1600 } 1601 1602 /** 1603 * Determines the featured media based on a request param. 1604 * 1605 * @since 4.7.0 1606 * 1607 * @param int $featured_media Featured Media ID. 1608 * @param int $post_id Post ID. 1609 * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error. 1610 */ 1611 protected function handle_featured_media( $featured_media, $post_id ) { 1612 1613 $featured_media = (int) $featured_media; 1614 if ( $featured_media ) { 1615 $result = set_post_thumbnail( $post_id, $featured_media ); 1616 if ( $result ) { 1617 return true; 1618 } else { 1619 return new WP_Error( 1620 'rest_invalid_featured_media', 1621 __( 'Invalid featured media ID.' ), 1622 array( 'status' => 400 ) 1623 ); 1624 } 1625 } else { 1626 return delete_post_thumbnail( $post_id ); 1627 } 1628 } 1629 1630 /** 1631 * Checks whether the template is valid for the given post. 1632 * 1633 * @since 4.9.0 1634 * 1635 * @param string $template Page template filename. 1636 * @param WP_REST_Request $request Request. 1637 * @return true|WP_Error True if template is still valid or if the same as existing value, or a WP_Error if template not supported. 1638 */ 1639 public function check_template( $template, $request ) { 1640 1641 if ( ! $template ) { 1642 return true; 1643 } 1644 1645 if ( $request['id'] ) { 1646 $post = get_post( $request['id'] ); 1647 $current_template = get_page_template_slug( $request['id'] ); 1648 } else { 1649 $post = null; 1650 $current_template = ''; 1651 } 1652 1653 // Always allow for updating a post to the same template, even if that template is no longer supported. 1654 if ( $template === $current_template ) { 1655 return true; 1656 } 1657 1658 // If this is a create request, get_post() will return null and wp theme will fallback to the passed post type. 1659 $allowed_templates = wp_get_theme()->get_page_templates( $post, $this->post_type ); 1660 1661 if ( isset( $allowed_templates[ $template ] ) ) { 1662 return true; 1663 } 1664 1665 return new WP_Error( 1666 'rest_invalid_param', 1667 /* translators: 1: Parameter, 2: List of valid values. */ 1668 sprintf( __( '%1$s is not one of %2$s.' ), 'template', implode( ', ', array_keys( $allowed_templates ) ) ) 1669 ); 1670 } 1671 1672 /** 1673 * Sets the template for a post. 1674 * 1675 * @since 4.7.0 1676 * @since 4.9.0 Added the `$validate` parameter. 1677 * 1678 * @param string $template Page template filename. 1679 * @param int $post_id Post ID. 1680 * @param bool $validate Whether to validate that the template selected is valid. 1681 */ 1682 public function handle_template( $template, $post_id, $validate = false ) { 1683 1684 if ( $validate && ! array_key_exists( $template, wp_get_theme()->get_page_templates( get_post( $post_id ) ) ) ) { 1685 $template = ''; 1686 } 1687 1688 update_post_meta( $post_id, '_wp_page_template', $template ); 1689 } 1690 1691 /** 1692 * Updates the post's terms from a REST request. 1693 * 1694 * @since 4.7.0 1695 * 1696 * @param int $post_id The post ID to update the terms form. 1697 * @param WP_REST_Request $request The request object with post and terms data. 1698 * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null. 1699 */ 1700 protected function handle_terms( $post_id, $request ) { 1701 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 1702 1703 foreach ( $taxonomies as $taxonomy ) { 1704 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 1705 1706 if ( ! isset( $request[ $base ] ) ) { 1707 continue; 1708 } 1709 1710 $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name ); 1711 1712 if ( is_wp_error( $result ) ) { 1713 return $result; 1714 } 1715 } 1716 1717 return null; 1718 } 1719 1720 /** 1721 * Checks whether current user can assign all terms sent with the current request. 1722 * 1723 * @since 4.7.0 1724 * 1725 * @param WP_REST_Request $request The request object with post and terms data. 1726 * @return bool Whether the current user can assign the provided terms. 1727 */ 1728 protected function check_assign_terms_permission( $request ) { 1729 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 1730 foreach ( $taxonomies as $taxonomy ) { 1731 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 1732 1733 if ( ! isset( $request[ $base ] ) ) { 1734 continue; 1735 } 1736 1737 foreach ( (array) $request[ $base ] as $term_id ) { 1738 // Invalid terms will be rejected later. 1739 if ( ! get_term( $term_id, $taxonomy->name ) ) { 1740 continue; 1741 } 1742 1743 if ( ! current_user_can( 'assign_term', (int) $term_id ) ) { 1744 return false; 1745 } 1746 } 1747 } 1748 1749 return true; 1750 } 1751 1752 /** 1753 * Checks if a given post type can be viewed or managed. 1754 * 1755 * @since 4.7.0 1756 * 1757 * @param WP_Post_Type|string $post_type Post type name or object. 1758 * @return bool Whether the post type is allowed in REST. 1759 */ 1760 protected function check_is_post_type_allowed( $post_type ) { 1761 if ( ! is_object( $post_type ) ) { 1762 $post_type = get_post_type_object( $post_type ); 1763 } 1764 1765 if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) { 1766 return true; 1767 } 1768 1769 return false; 1770 } 1771 1772 /** 1773 * Checks if a post can be read. 1774 * 1775 * Correctly handles posts with the inherit status. 1776 * 1777 * @since 4.7.0 1778 * 1779 * @param WP_Post $post Post object. 1780 * @return bool Whether the post can be read. 1781 */ 1782 public function check_read_permission( $post ) { 1783 $post_type = get_post_type_object( $post->post_type ); 1784 if ( ! $this->check_is_post_type_allowed( $post_type ) ) { 1785 return false; 1786 } 1787 1788 // Is the post readable? 1789 if ( 'publish' === $post->post_status || current_user_can( 'read_post', $post->ID ) ) { 1790 return true; 1791 } 1792 1793 $post_status_obj = get_post_status_object( $post->post_status ); 1794 if ( $post_status_obj && $post_status_obj->public ) { 1795 return true; 1796 } 1797 1798 // Can we read the parent if we're inheriting? 1799 if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) { 1800 $parent = get_post( $post->post_parent ); 1801 if ( $parent ) { 1802 return $this->check_read_permission( $parent ); 1803 } 1804 } 1805 1806 /* 1807 * If there isn't a parent, but the status is set to inherit, assume 1808 * it's published (as per get_post_status()). 1809 */ 1810 if ( 'inherit' === $post->post_status ) { 1811 return true; 1812 } 1813 1814 return false; 1815 } 1816 1817 /** 1818 * Checks if a post can be edited. 1819 * 1820 * @since 4.7.0 1821 * 1822 * @param WP_Post $post Post object. 1823 * @return bool Whether the post can be edited. 1824 */ 1825 protected function check_update_permission( $post ) { 1826 $post_type = get_post_type_object( $post->post_type ); 1827 1828 if ( ! $this->check_is_post_type_allowed( $post_type ) ) { 1829 return false; 1830 } 1831 1832 return current_user_can( 'edit_post', $post->ID ); 1833 } 1834 1835 /** 1836 * Checks if a post can be created. 1837 * 1838 * @since 4.7.0 1839 * 1840 * @param WP_Post $post Post object. 1841 * @return bool Whether the post can be created. 1842 */ 1843 protected function check_create_permission( $post ) { 1844 $post_type = get_post_type_object( $post->post_type ); 1845 1846 if ( ! $this->check_is_post_type_allowed( $post_type ) ) { 1847 return false; 1848 } 1849 1850 return current_user_can( $post_type->cap->create_posts ); 1851 } 1852 1853 /** 1854 * Checks if a post can be deleted. 1855 * 1856 * @since 4.7.0 1857 * 1858 * @param WP_Post $post Post object. 1859 * @return bool Whether the post can be deleted. 1860 */ 1861 protected function check_delete_permission( $post ) { 1862 $post_type = get_post_type_object( $post->post_type ); 1863 1864 if ( ! $this->check_is_post_type_allowed( $post_type ) ) { 1865 return false; 1866 } 1867 1868 return current_user_can( 'delete_post', $post->ID ); 1869 } 1870 1871 /** 1872 * Prepares a single post output for response. 1873 * 1874 * @since 4.7.0 1875 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. 1876 * 1877 * @global WP_Post $post Global post object. 1878 * 1879 * @param WP_Post $item Post object. 1880 * @param WP_REST_Request $request Request object. 1881 * @return WP_REST_Response Response object. 1882 */ 1883 public function prepare_item_for_response( $item, $request ) { 1884 // Restores the more descriptive, specific name for use within this method. 1885 $post = $item; 1886 1887 $GLOBALS['post'] = $post; 1888 1889 setup_postdata( $post ); 1890 1891 // Don't prepare the response body for HEAD requests. 1892 if ( $request->is_method( 'HEAD' ) ) { 1893 /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ 1894 return apply_filters( "rest_prepare_{$this->post_type}", new WP_REST_Response( array() ), $post, $request ); 1895 } 1896 1897 $fields = $this->get_fields_for_response( $request ); 1898 1899 // Base fields for every post. 1900 $data = array(); 1901 1902 if ( rest_is_field_included( 'id', $fields ) ) { 1903 $data['id'] = $post->ID; 1904 } 1905 1906 if ( rest_is_field_included( 'date', $fields ) ) { 1907 $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date ); 1908 } 1909 1910 if ( rest_is_field_included( 'date_gmt', $fields ) ) { 1911 /* 1912 * For drafts, `post_date_gmt` may not be set, indicating that the date 1913 * of the draft should be updated each time it is saved (see #38883). 1914 * In this case, shim the value based on the `post_date` field 1915 * with the site's timezone offset applied. 1916 */ 1917 if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) { 1918 $post_date_gmt = get_gmt_from_date( $post->post_date ); 1919 } else { 1920 $post_date_gmt = $post->post_date_gmt; 1921 } 1922 $data['date_gmt'] = $this->prepare_date_response( $post_date_gmt ); 1923 } 1924 1925 if ( rest_is_field_included( 'guid', $fields ) ) { 1926 $data['guid'] = array( 1927 /** This filter is documented in wp-includes/post-template.php */ 1928 'rendered' => apply_filters( 'get_the_guid', $post->guid, $post->ID ), 1929 'raw' => $post->guid, 1930 ); 1931 } 1932 1933 if ( rest_is_field_included( 'modified', $fields ) ) { 1934 $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified ); 1935 } 1936 1937 if ( rest_is_field_included( 'modified_gmt', $fields ) ) { 1938 /* 1939 * For drafts, `post_modified_gmt` may not be set (see `post_date_gmt` comments 1940 * above). In this case, shim the value based on the `post_modified` field 1941 * with the site's timezone offset applied. 1942 */ 1943 if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) { 1944 $post_modified_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - (int) ( (float) get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ); 1945 } else { 1946 $post_modified_gmt = $post->post_modified_gmt; 1947 } 1948 $data['modified_gmt'] = $this->prepare_date_response( $post_modified_gmt ); 1949 } 1950 1951 if ( rest_is_field_included( 'password', $fields ) ) { 1952 $data['password'] = $post->post_password; 1953 } 1954 1955 if ( rest_is_field_included( 'slug', $fields ) ) { 1956 $data['slug'] = $post->post_name; 1957 } 1958 1959 if ( rest_is_field_included( 'status', $fields ) ) { 1960 $data['status'] = $post->post_status; 1961 } 1962 1963 if ( rest_is_field_included( 'type', $fields ) ) { 1964 $data['type'] = $post->post_type; 1965 } 1966 1967 if ( rest_is_field_included( 'link', $fields ) ) { 1968 $data['link'] = get_permalink( $post->ID ); 1969 } 1970 1971 if ( rest_is_field_included( 'title', $fields ) ) { 1972 $data['title'] = array(); 1973 } 1974 if ( rest_is_field_included( 'title.raw', $fields ) ) { 1975 $data['title']['raw'] = $post->post_title; 1976 } 1977 if ( rest_is_field_included( 'title.rendered', $fields ) ) { 1978 add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); 1979 add_filter( 'private_title_format', array( $this, 'protected_title_format' ) ); 1980 1981 $data['title']['rendered'] = get_the_title( $post->ID ); 1982 1983 remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); 1984 remove_filter( 'private_title_format', array( $this, 'protected_title_format' ) ); 1985 } 1986 1987 $has_password_filter = false; 1988 1989 if ( $this->can_access_password_content( $post, $request ) ) { 1990 $this->password_check_passed[ $post->ID ] = true; 1991 // Allow access to the post, permissions already checked before. 1992 add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 ); 1993 1994 $has_password_filter = true; 1995 } 1996 1997 if ( rest_is_field_included( 'content', $fields ) ) { 1998 $data['content'] = array(); 1999 } 2000 if ( rest_is_field_included( 'content.raw', $fields ) ) { 2001 $data['content']['raw'] = $post->post_content; 2002 } 2003 if ( rest_is_field_included( 'content.rendered', $fields ) ) { 2004 /** This filter is documented in wp-includes/post-template.php */ 2005 $data['content']['rendered'] = post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ); 2006 } 2007 if ( rest_is_field_included( 'content.protected', $fields ) ) { 2008 $data['content']['protected'] = (bool) $post->post_password; 2009 } 2010 if ( rest_is_field_included( 'content.block_version', $fields ) ) { 2011 $data['content']['block_version'] = block_version( $post->post_content ); 2012 } 2013 2014 if ( rest_is_field_included( 'excerpt', $fields ) ) { 2015 if ( isset( $request['excerpt_length'] ) ) { 2016 $excerpt_length = $request['excerpt_length']; 2017 $override_excerpt_length = static function () use ( $excerpt_length ) { 2018 return $excerpt_length; 2019 }; 2020 2021 add_filter( 2022 'excerpt_length', 2023 $override_excerpt_length, 2024 PHP_INT_MAX 2025 ); 2026 } 2027 2028 /** This filter is documented in wp-includes/post-template.php */ 2029 $excerpt = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ); 2030 2031 /** This filter is documented in wp-includes/post-template.php */ 2032 $excerpt = apply_filters( 'the_excerpt', $excerpt ); 2033 2034 $data['excerpt'] = array( 2035 'raw' => $post->post_excerpt, 2036 'rendered' => post_password_required( $post ) ? '' : $excerpt, 2037 'protected' => (bool) $post->post_password, 2038 ); 2039 2040 if ( isset( $override_excerpt_length ) ) { 2041 remove_filter( 2042 'excerpt_length', 2043 $override_excerpt_length, 2044 PHP_INT_MAX 2045 ); 2046 } 2047 } 2048 2049 if ( $has_password_filter ) { 2050 // Reset filter. 2051 remove_filter( 'post_password_required', array( $this, 'check_password_required' ) ); 2052 } 2053 2054 if ( rest_is_field_included( 'author', $fields ) ) { 2055 $data['author'] = (int) $post->post_author; 2056 } 2057 2058 if ( rest_is_field_included( 'featured_media', $fields ) ) { 2059 $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID ); 2060 } 2061 2062 if ( rest_is_field_included( 'parent', $fields ) ) { 2063 $data['parent'] = (int) $post->post_parent; 2064 } 2065 2066 if ( rest_is_field_included( 'menu_order', $fields ) ) { 2067 $data['menu_order'] = (int) $post->menu_order; 2068 } 2069 2070 if ( rest_is_field_included( 'comment_status', $fields ) ) { 2071 $data['comment_status'] = $post->comment_status; 2072 } 2073 2074 if ( rest_is_field_included( 'ping_status', $fields ) ) { 2075 $data['ping_status'] = $post->ping_status; 2076 } 2077 2078 if ( rest_is_field_included( 'sticky', $fields ) ) { 2079 $data['sticky'] = is_sticky( $post->ID ); 2080 } 2081 2082 if ( rest_is_field_included( 'template', $fields ) ) { 2083 $template = get_page_template_slug( $post->ID ); 2084 if ( $template ) { 2085 $data['template'] = $template; 2086 } else { 2087 $data['template'] = ''; 2088 } 2089 } 2090 2091 if ( rest_is_field_included( 'format', $fields ) ) { 2092 $data['format'] = get_post_format( $post->ID ); 2093 2094 // Fill in blank post format. 2095 if ( empty( $data['format'] ) ) { 2096 $data['format'] = 'standard'; 2097 } 2098 } 2099 2100 if ( rest_is_field_included( 'meta', $fields ) ) { 2101 $data['meta'] = $this->meta->get_value( $post->ID, $request ); 2102 } 2103 2104 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 2105 2106 foreach ( $taxonomies as $taxonomy ) { 2107 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 2108 2109 if ( rest_is_field_included( $base, $fields ) ) { 2110 $terms = get_the_terms( $post, $taxonomy->name ); 2111 $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array(); 2112 } 2113 } 2114 2115 $post_type_obj = get_post_type_object( $post->post_type ); 2116 if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) { 2117 $permalink_template_requested = rest_is_field_included( 'permalink_template', $fields ); 2118 $generated_slug_requested = rest_is_field_included( 'generated_slug', $fields ); 2119 2120 if ( $permalink_template_requested || $generated_slug_requested ) { 2121 if ( ! function_exists( 'get_sample_permalink' ) ) { 2122 require_once ABSPATH . 'wp-admin/includes/post.php'; 2123 } 2124 2125 $sample_permalink = get_sample_permalink( $post->ID, $post->post_title, '' ); 2126 2127 if ( $permalink_template_requested ) { 2128 $data['permalink_template'] = $sample_permalink[0]; 2129 } 2130 2131 if ( $generated_slug_requested ) { 2132 $data['generated_slug'] = $sample_permalink[1]; 2133 } 2134 } 2135 2136 if ( rest_is_field_included( 'class_list', $fields ) ) { 2137 $data['class_list'] = get_post_class( array(), $post->ID ); 2138 } 2139 } 2140 2141 $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; 2142 $data = $this->add_additional_fields_to_object( $data, $request ); 2143 $data = $this->filter_response_by_context( $data, $context ); 2144 2145 // Wrap the data in a response object. 2146 $response = rest_ensure_response( $data ); 2147 2148 if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { 2149 $links = $this->prepare_links( $post ); 2150 $response->add_links( $links ); 2151 2152 if ( ! empty( $links['self']['href'] ) ) { 2153 $actions = $this->get_available_actions( $post, $request ); 2154 2155 $self = $links['self']['href']; 2156 2157 foreach ( $actions as $rel ) { 2158 $response->add_link( $rel, $self ); 2159 } 2160 } 2161 } 2162 2163 /** 2164 * Applies Block Hooks to content-like post types for REST response. 2165 * 2166 * This replaces the individual post type filters that were previously hardcoded 2167 * in default-filters.php. 2168 * 2169 * @since 7.0.0 2170 */ 2171 $content_like_post_types = array( 'post', 'page', 'wp_block', 'wp_navigation' ); 2172 2173 /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ 2174 $content_like_post_types = apply_filters( 'rest_block_hooks_post_types', $content_like_post_types, $this->post_type, $post ); 2175 2176 if ( in_array( $this->post_type, $content_like_post_types, true ) ) { 2177 $response = insert_hooked_blocks_into_rest_response( $response, $post ); 2178 } 2179 2180 /** 2181 * Filters the post data for a REST API response. 2182 * 2183 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. 2184 * 2185 * Possible hook names include: 2186 * 2187 * - `rest_prepare_post` 2188 * - `rest_prepare_page` 2189 * - `rest_prepare_attachment` 2190 * 2191 * @since 4.7.0 2192 * 2193 * @param WP_REST_Response $response The response object. 2194 * @param WP_Post $post Post object. 2195 * @param WP_REST_Request $request Request object. 2196 */ 2197 return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request ); 2198 } 2199 2200 /** 2201 * Overwrites the default protected and private title format. 2202 * 2203 * By default, WordPress will show password protected or private posts with a title of 2204 * "Protected: %s" or "Private: %s", as the REST API communicates the status of a post 2205 * in a machine-readable format, we remove the prefix. 2206 * 2207 * @since 4.7.0 2208 * 2209 * @return string Title format. 2210 */ 2211 public function protected_title_format() { 2212 return '%s'; 2213 } 2214 2215 /** 2216 * Prepares links for the request. 2217 * 2218 * @since 4.7.0 2219 * 2220 * @param WP_Post $post Post object. 2221 * @return array Links for the given post. 2222 */ 2223 protected function prepare_links( $post ) { 2224 // Entity meta. 2225 $links = array( 2226 'self' => array( 2227 'href' => rest_url( rest_get_route_for_post( $post->ID ) ), 2228 ), 2229 'collection' => array( 2230 'href' => rest_url( rest_get_route_for_post_type_items( $this->post_type ) ), 2231 ), 2232 'about' => array( 2233 'href' => rest_url( 'wp/v2/types/' . $this->post_type ), 2234 ), 2235 ); 2236 2237 if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) ) 2238 && ! empty( $post->post_author ) ) { 2239 $links['author'] = array( 2240 'href' => rest_url( 'wp/v2/users/' . $post->post_author ), 2241 'embeddable' => true, 2242 ); 2243 } 2244 2245 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) { 2246 $replies_url = rest_url( 'wp/v2/comments' ); 2247 $replies_url = add_query_arg( 'post', $post->ID, $replies_url ); 2248 2249 $links['replies'] = array( 2250 'href' => $replies_url, 2251 'embeddable' => true, 2252 ); 2253 } 2254 2255 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) { 2256 $revisions = wp_get_latest_revision_id_and_total_count( $post->ID ); 2257 $revisions_count = ! is_wp_error( $revisions ) ? $revisions['count'] : 0; 2258 $revisions_base = sprintf( '/%s/%s/%d/revisions', $this->namespace, $this->rest_base, $post->ID ); 2259 2260 $links['version-history'] = array( 2261 'href' => rest_url( $revisions_base ), 2262 'count' => $revisions_count, 2263 ); 2264 2265 if ( $revisions_count > 0 ) { 2266 $links['predecessor-version'] = array( 2267 'href' => rest_url( $revisions_base . '/' . $revisions['latest_id'] ), 2268 'id' => $revisions['latest_id'], 2269 ); 2270 } 2271 } 2272 2273 $post_type_obj = get_post_type_object( $post->post_type ); 2274 2275 if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) { 2276 $links['up'] = array( 2277 'href' => rest_url( rest_get_route_for_post( $post->post_parent ) ), 2278 'embeddable' => true, 2279 ); 2280 } 2281 2282 // If we have a featured media, add that. 2283 $featured_media = get_post_thumbnail_id( $post->ID ); 2284 if ( $featured_media && ( 'publish' === get_post_status( $featured_media ) || current_user_can( 'read_post', $featured_media ) ) ) { 2285 $image_url = rest_url( rest_get_route_for_post( $featured_media ) ); 2286 2287 $links['https://api.w.org/featuredmedia'] = array( 2288 'href' => $image_url, 2289 'embeddable' => true, 2290 ); 2291 } 2292 2293 if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) { 2294 $attachments_url = rest_url( rest_get_route_for_post_type_items( 'attachment' ) ); 2295 $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url ); 2296 2297 $links['https://api.w.org/attachment'] = array( 2298 'href' => $attachments_url, 2299 ); 2300 } 2301 2302 $taxonomies = get_object_taxonomies( $post->post_type ); 2303 2304 if ( ! empty( $taxonomies ) ) { 2305 $links['https://api.w.org/term'] = array(); 2306 2307 foreach ( $taxonomies as $tax ) { 2308 $taxonomy_route = rest_get_route_for_taxonomy_items( $tax ); 2309 2310 // Skip taxonomies that are not public. 2311 if ( empty( $taxonomy_route ) ) { 2312 continue; 2313 } 2314 $terms_url = add_query_arg( 2315 'post', 2316 $post->ID, 2317 rest_url( $taxonomy_route ) 2318 ); 2319 2320 $links['https://api.w.org/term'][] = array( 2321 'href' => $terms_url, 2322 'taxonomy' => $tax, 2323 'embeddable' => true, 2324 ); 2325 } 2326 } 2327 2328 return $links; 2329 } 2330 2331 /** 2332 * Gets the link relations available for the post and current user. 2333 * 2334 * @since 4.9.8 2335 * @since 7.2.0 Added the `action-trash`, `action-set-homepage`, and `action-set-posts-page` link relations. 2336 * 2337 * @param WP_Post $post Post object. 2338 * @param WP_REST_Request $request Request object. 2339 * @return array List of link relations. 2340 */ 2341 protected function get_available_actions( $post, $request ) { 2342 2343 if ( 'edit' !== $request['context'] ) { 2344 return array(); 2345 } 2346 2347 $rels = array(); 2348 2349 $post_type = get_post_type_object( $post->post_type ); 2350 2351 if ( 'attachment' !== $this->post_type && current_user_can( $post_type->cap->publish_posts ) ) { 2352 $rels[] = 'https://api.w.org/action-publish'; 2353 } 2354 2355 if ( current_user_can( 'unfiltered_html' ) ) { 2356 $rels[] = 'https://api.w.org/action-unfiltered-html'; 2357 } 2358 2359 if ( 'post' === $post_type->name ) { 2360 if ( current_user_can( $post_type->cap->edit_others_posts ) && current_user_can( $post_type->cap->publish_posts ) ) { 2361 $rels[] = 'https://api.w.org/action-sticky'; 2362 } 2363 } 2364 2365 if ( post_type_supports( $post_type->name, 'author' ) ) { 2366 if ( current_user_can( $post_type->cap->edit_others_posts ) ) { 2367 $rels[] = 'https://api.w.org/action-assign-author'; 2368 } 2369 } 2370 2371 if ( 'trash' !== $post->post_status && $this->check_delete_permission( $post ) ) { 2372 $supports_trash = ( EMPTY_TRASH_DAYS > 0 ); 2373 2374 if ( 'attachment' === $post->post_type ) { 2375 $supports_trash = $supports_trash && MEDIA_TRASH; 2376 } 2377 2378 /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ 2379 if ( apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post ) ) { 2380 $rels[] = 'https://api.w.org/action-trash'; 2381 } 2382 } 2383 2384 /* 2385 * Setting a page as the homepage or as the posts page changes the site settings, 2386 * so it requires the same capability as the settings route. The current homepage 2387 * and posts page get neither link. 2388 */ 2389 if ( 'page' === $post_type->name && 'publish' === $post->post_status && current_user_can( 'manage_options' ) ) { 2390 if ( (int) get_option( 'page_on_front' ) !== $post->ID && (int) get_option( 'page_for_posts' ) !== $post->ID ) { 2391 $rels[] = 'https://api.w.org/action-set-homepage'; 2392 $rels[] = 'https://api.w.org/action-set-posts-page'; 2393 } 2394 } 2395 2396 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 2397 2398 foreach ( $taxonomies as $tax ) { 2399 $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name; 2400 $create_cap = is_taxonomy_hierarchical( $tax->name ) ? $tax->cap->edit_terms : $tax->cap->assign_terms; 2401 2402 if ( current_user_can( $create_cap ) ) { 2403 $rels[] = 'https://api.w.org/action-create-' . $tax_base; 2404 } 2405 2406 if ( current_user_can( $tax->cap->assign_terms ) ) { 2407 $rels[] = 'https://api.w.org/action-assign-' . $tax_base; 2408 } 2409 } 2410 2411 return $rels; 2412 } 2413 2414 /** 2415 * Retrieves the post's schema, conforming to JSON Schema. 2416 * 2417 * @since 4.7.0 2418 * 2419 * @return array Item schema data. 2420 * 2421 * @phpstan-return array{ 2422 * title: non-empty-string, 2423 * type: non-empty-string, 2424 * properties: array<string, array<string, mixed>>, 2425 * ... 2426 * } 2427 */ 2428 public function get_item_schema() { 2429 if ( $this->schema ) { 2430 return $this->add_additional_fields_schema( $this->schema ); 2431 } 2432 2433 $schema = array( 2434 '$schema' => 'http://json-schema.org/draft-04/schema#', 2435 'title' => $this->post_type, 2436 'type' => 'object', 2437 // Base properties for every Post. 2438 'properties' => array( 2439 'date' => array( 2440 'description' => __( "The date the post was published, in the site's timezone." ), 2441 'type' => array( 'string', 'null' ), 2442 'format' => 'date-time', 2443 'context' => array( 'view', 'edit', 'embed' ), 2444 ), 2445 'date_gmt' => array( 2446 'description' => __( 'The date the post was published, as GMT.' ), 2447 'type' => array( 'string', 'null' ), 2448 'format' => 'date-time', 2449 'context' => array( 'view', 'edit' ), 2450 ), 2451 'guid' => array( 2452 'description' => __( 'The globally unique identifier for the post.' ), 2453 'type' => 'object', 2454 'context' => array( 'view', 'edit' ), 2455 'readonly' => true, 2456 'properties' => array( 2457 'raw' => array( 2458 'description' => __( 'GUID for the post, as it exists in the database.' ), 2459 'type' => 'string', 2460 'context' => array( 'edit' ), 2461 'readonly' => true, 2462 ), 2463 'rendered' => array( 2464 'description' => __( 'GUID for the post, transformed for display.' ), 2465 'type' => 'string', 2466 'context' => array( 'view', 'edit' ), 2467 'readonly' => true, 2468 ), 2469 ), 2470 ), 2471 'id' => array( 2472 'description' => __( 'Unique identifier for the post.' ), 2473 'type' => 'integer', 2474 'context' => array( 'view', 'edit', 'embed' ), 2475 'readonly' => true, 2476 ), 2477 'link' => array( 2478 'description' => __( 'URL to the post.' ), 2479 'type' => 'string', 2480 'format' => 'uri', 2481 'context' => array( 'view', 'edit', 'embed' ), 2482 'readonly' => true, 2483 ), 2484 'modified' => array( 2485 'description' => __( "The date the post was last modified, in the site's timezone." ), 2486 'type' => 'string', 2487 'format' => 'date-time', 2488 'context' => array( 'view', 'edit' ), 2489 'readonly' => true, 2490 ), 2491 'modified_gmt' => array( 2492 'description' => __( 'The date the post was last modified, as GMT.' ), 2493 'type' => 'string', 2494 'format' => 'date-time', 2495 'context' => array( 'view', 'edit' ), 2496 'readonly' => true, 2497 ), 2498 'slug' => array( 2499 'description' => __( 'An alphanumeric identifier for the post unique to its type.' ), 2500 'type' => 'string', 2501 'context' => array( 'view', 'edit', 'embed' ), 2502 'arg_options' => array( 2503 'sanitize_callback' => array( $this, 'sanitize_slug' ), 2504 ), 2505 ), 2506 'status' => array( 2507 'description' => __( 'A named status for the post.' ), 2508 'type' => 'string', 2509 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ), 2510 'context' => array( 'view', 'edit' ), 2511 'arg_options' => array( 2512 'validate_callback' => array( $this, 'check_status' ), 2513 ), 2514 ), 2515 'type' => array( 2516 'description' => __( 'Type of post.' ), 2517 'type' => 'string', 2518 'context' => array( 'view', 'edit', 'embed' ), 2519 'readonly' => true, 2520 ), 2521 'password' => array( 2522 'description' => __( 'A password to protect access to the content and excerpt.' ), 2523 'type' => 'string', 2524 'context' => array( 'edit' ), 2525 ), 2526 ), 2527 ); 2528 2529 $post_type_obj = get_post_type_object( $this->post_type ); 2530 if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) { 2531 $schema['properties']['permalink_template'] = array( 2532 'description' => __( 'Permalink template for the post.' ), 2533 'type' => 'string', 2534 'context' => array( 'edit' ), 2535 'readonly' => true, 2536 ); 2537 2538 $schema['properties']['generated_slug'] = array( 2539 'description' => __( 'Slug automatically generated from the post title.' ), 2540 'type' => 'string', 2541 'context' => array( 'edit' ), 2542 'readonly' => true, 2543 ); 2544 2545 $schema['properties']['class_list'] = array( 2546 'description' => __( 'An array of the class names for the post container element.' ), 2547 'type' => 'array', 2548 'context' => array( 'view', 'edit' ), 2549 'readonly' => true, 2550 'items' => array( 2551 'type' => 'string', 2552 ), 2553 ); 2554 } 2555 2556 if ( $post_type_obj->hierarchical ) { 2557 $schema['properties']['parent'] = array( 2558 'description' => __( 'The ID for the parent of the post.' ), 2559 'type' => 'integer', 2560 'context' => array( 'view', 'edit' ), 2561 ); 2562 } 2563 2564 $post_type_attributes = array( 2565 'title', 2566 'editor', 2567 'author', 2568 'excerpt', 2569 'thumbnail', 2570 'comments', 2571 'revisions', 2572 'page-attributes', 2573 'post-formats', 2574 'custom-fields', 2575 ); 2576 $fixed_schemas = array( 2577 'post' => array( 2578 'title', 2579 'editor', 2580 'author', 2581 'excerpt', 2582 'thumbnail', 2583 'comments', 2584 'revisions', 2585 'post-formats', 2586 'custom-fields', 2587 ), 2588 'page' => array( 2589 'title', 2590 'editor', 2591 'author', 2592 'excerpt', 2593 'thumbnail', 2594 'comments', 2595 'revisions', 2596 'page-attributes', 2597 'custom-fields', 2598 ), 2599 'attachment' => array( 2600 'title', 2601 'author', 2602 'comments', 2603 'revisions', 2604 'custom-fields', 2605 'thumbnail', 2606 ), 2607 ); 2608 2609 foreach ( $post_type_attributes as $attribute ) { 2610 if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) { 2611 continue; 2612 } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) { 2613 continue; 2614 } 2615 2616 switch ( $attribute ) { 2617 2618 case 'title': 2619 $schema['properties']['title'] = array( 2620 'description' => __( 'The title for the post.' ), 2621 'type' => 'object', 2622 'context' => array( 'view', 'edit', 'embed' ), 2623 'arg_options' => array( 2624 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 2625 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). 2626 ), 2627 'properties' => array( 2628 'raw' => array( 2629 'description' => __( 'Title for the post, as it exists in the database.' ), 2630 'type' => 'string', 2631 'context' => array( 'edit' ), 2632 ), 2633 'rendered' => array( 2634 'description' => __( 'HTML title for the post, transformed for display.' ), 2635 'type' => 'string', 2636 'context' => array( 'view', 'edit', 'embed' ), 2637 'readonly' => true, 2638 ), 2639 ), 2640 ); 2641 break; 2642 2643 case 'editor': 2644 $schema['properties']['content'] = array( 2645 'description' => __( 'The content for the post.' ), 2646 'type' => 'object', 2647 'context' => array( 'view', 'edit' ), 2648 'arg_options' => array( 2649 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 2650 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). 2651 ), 2652 'properties' => array( 2653 'raw' => array( 2654 'description' => __( 'Content for the post, as it exists in the database.' ), 2655 'type' => 'string', 2656 'context' => array( 'edit' ), 2657 ), 2658 'rendered' => array( 2659 'description' => __( 'HTML content for the post, transformed for display.' ), 2660 'type' => 'string', 2661 'context' => array( 'view', 'edit' ), 2662 'readonly' => true, 2663 ), 2664 'block_version' => array( 2665 'description' => __( 'Version of the content block format used by the post.' ), 2666 'type' => 'integer', 2667 'context' => array( 'edit' ), 2668 'readonly' => true, 2669 ), 2670 'protected' => array( 2671 'description' => __( 'Whether the content is protected with a password.' ), 2672 'type' => 'boolean', 2673 'context' => array( 'view', 'edit', 'embed' ), 2674 'readonly' => true, 2675 ), 2676 ), 2677 ); 2678 break; 2679 2680 case 'author': 2681 $schema['properties']['author'] = array( 2682 'description' => __( 'The ID for the author of the post.' ), 2683 'type' => 'integer', 2684 'context' => array( 'view', 'edit', 'embed' ), 2685 ); 2686 break; 2687 2688 case 'excerpt': 2689 $schema['properties']['excerpt'] = array( 2690 'description' => __( 'The excerpt for the post.' ), 2691 'type' => 'object', 2692 'context' => array( 'view', 'edit', 'embed' ), 2693 'arg_options' => array( 2694 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 2695 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). 2696 ), 2697 'properties' => array( 2698 'raw' => array( 2699 'description' => __( 'Excerpt for the post, as it exists in the database.' ), 2700 'type' => 'string', 2701 'context' => array( 'edit' ), 2702 ), 2703 'rendered' => array( 2704 'description' => __( 'HTML excerpt for the post, transformed for display.' ), 2705 'type' => 'string', 2706 'context' => array( 'view', 'edit', 'embed' ), 2707 'readonly' => true, 2708 ), 2709 'protected' => array( 2710 'description' => __( 'Whether the excerpt is protected with a password.' ), 2711 'type' => 'boolean', 2712 'context' => array( 'view', 'edit', 'embed' ), 2713 'readonly' => true, 2714 ), 2715 ), 2716 ); 2717 break; 2718 2719 case 'thumbnail': 2720 $schema['properties']['featured_media'] = array( 2721 'description' => __( 'The ID of the featured media for the post.' ), 2722 'type' => 'integer', 2723 'context' => array( 'view', 'edit', 'embed' ), 2724 ); 2725 break; 2726 2727 case 'comments': 2728 $schema['properties']['comment_status'] = array( 2729 'description' => __( 'Whether or not comments are open on the post.' ), 2730 'type' => 'string', 2731 'enum' => array( 'open', 'closed' ), 2732 'context' => array( 'view', 'edit' ), 2733 ); 2734 $schema['properties']['ping_status'] = array( 2735 'description' => __( 'Whether or not the post can be pinged.' ), 2736 'type' => 'string', 2737 'enum' => array( 'open', 'closed' ), 2738 'context' => array( 'view', 'edit' ), 2739 ); 2740 break; 2741 2742 case 'page-attributes': 2743 $schema['properties']['menu_order'] = array( 2744 'description' => __( 'The order of the post in relation to other posts.' ), 2745 'type' => 'integer', 2746 'context' => array( 'view', 'edit' ), 2747 ); 2748 break; 2749 2750 case 'post-formats': 2751 // Get the native post formats and remove the array keys. 2752 $formats = array_values( get_post_format_slugs() ); 2753 2754 $schema['properties']['format'] = array( 2755 'description' => __( 'The format for the post.' ), 2756 'type' => 'string', 2757 'enum' => $formats, 2758 'context' => array( 'view', 'edit' ), 2759 ); 2760 break; 2761 2762 case 'custom-fields': 2763 $schema['properties']['meta'] = $this->meta->get_field_schema(); 2764 break; 2765 2766 } 2767 } 2768 2769 if ( 'post' === $this->post_type ) { 2770 $schema['properties']['sticky'] = array( 2771 'description' => __( 'Whether or not the post should be treated as sticky.' ), 2772 'type' => 'boolean', 2773 'context' => array( 'view', 'edit' ), 2774 ); 2775 } 2776 2777 $schema['properties']['template'] = array( 2778 'description' => __( 'The theme file to use to display the post.' ), 2779 'type' => 'string', 2780 'context' => array( 'view', 'edit' ), 2781 'arg_options' => array( 2782 'validate_callback' => array( $this, 'check_template' ), 2783 ), 2784 ); 2785 2786 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 2787 2788 foreach ( $taxonomies as $taxonomy ) { 2789 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 2790 2791 if ( array_key_exists( $base, $schema['properties'] ) ) { 2792 $taxonomy_field_name_with_conflict = ! empty( $taxonomy->rest_base ) ? 'rest_base' : 'name'; 2793 _doing_it_wrong( 2794 'register_taxonomy', 2795 sprintf( 2796 /* translators: 1: The taxonomy name, 2: The property name, either 'rest_base' or 'name', 3: The conflicting value. */ 2797 __( 'The "%1$s" taxonomy "%2$s" property (%3$s) conflicts with an existing property on the REST API Posts Controller. Specify a custom "rest_base" when registering the taxonomy to avoid this error.' ), 2798 $taxonomy->name, 2799 $taxonomy_field_name_with_conflict, 2800 $base 2801 ), 2802 '5.4.0' 2803 ); 2804 } 2805 2806 $schema['properties'][ $base ] = array( 2807 /* translators: %s: Taxonomy name. */ 2808 'description' => sprintf( __( 'The terms assigned to the post in the %s taxonomy.' ), $taxonomy->name ), 2809 'type' => 'array', 2810 'items' => array( 2811 'type' => 'integer', 2812 ), 2813 'context' => array( 'view', 'edit' ), 2814 ); 2815 } 2816 2817 $schema_links = $this->get_schema_links(); 2818 2819 if ( $schema_links ) { 2820 $schema['links'] = $schema_links; 2821 } 2822 2823 // Take a snapshot of which fields are in the schema pre-filtering. 2824 $schema_fields = array_keys( $schema['properties'] ); 2825 2826 /** 2827 * Filters the post's schema. 2828 * 2829 * The dynamic portion of the filter, `$this->post_type`, refers to the 2830 * post type slug for the controller. 2831 * 2832 * Possible hook names include: 2833 * 2834 * - `rest_post_item_schema` 2835 * - `rest_page_item_schema` 2836 * - `rest_attachment_item_schema` 2837 * 2838 * @since 5.4.0 2839 * 2840 * @param array $schema Item schema data. 2841 */ 2842 $schema = apply_filters( "rest_{$this->post_type}_item_schema", $schema ); 2843 2844 // Emit a _doing_it_wrong warning if user tries to add new properties using this filter. 2845 $new_fields = array_diff( array_keys( $schema['properties'] ), $schema_fields ); 2846 if ( count( $new_fields ) > 0 ) { 2847 _doing_it_wrong( 2848 __METHOD__, 2849 sprintf( 2850 /* translators: %s: register_rest_field */ 2851 __( 'Please use %s to add new schema properties.' ), 2852 'register_rest_field' 2853 ), 2854 '5.4.0' 2855 ); 2856 } 2857 2858 $this->schema = $schema; 2859 2860 return $this->add_additional_fields_schema( $this->schema ); 2861 } 2862 2863 /** 2864 * Retrieves Link Description Objects that should be added to the Schema for the posts collection. 2865 * 2866 * @since 4.9.8 2867 * @since 7.2.0 Added the `action-trash`, `action-set-homepage`, and `action-set-posts-page` link relations. 2868 * 2869 * @return array 2870 */ 2871 protected function get_schema_links() { 2872 2873 $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" ); 2874 2875 $links = array(); 2876 2877 if ( 'attachment' !== $this->post_type ) { 2878 $links[] = array( 2879 'rel' => 'https://api.w.org/action-publish', 2880 'title' => __( 'The current user can publish this post.' ), 2881 'href' => $href, 2882 'targetSchema' => array( 2883 'type' => 'object', 2884 'properties' => array( 2885 'status' => array( 2886 'type' => 'string', 2887 'enum' => array( 'publish', 'future' ), 2888 ), 2889 ), 2890 ), 2891 ); 2892 } 2893 2894 $links[] = array( 2895 'rel' => 'https://api.w.org/action-unfiltered-html', 2896 'title' => __( 'The current user can post unfiltered HTML markup and JavaScript.' ), 2897 'href' => $href, 2898 'targetSchema' => array( 2899 'type' => 'object', 2900 'properties' => array( 2901 'content' => array( 2902 'type' => 'object', 2903 'properties' => array( 2904 'raw' => array( 2905 'type' => 'string', 2906 ), 2907 ), 2908 ), 2909 ), 2910 ), 2911 ); 2912 2913 if ( 'post' === $this->post_type ) { 2914 $links[] = array( 2915 'rel' => 'https://api.w.org/action-sticky', 2916 'title' => __( 'The current user can sticky this post.' ), 2917 'href' => $href, 2918 'targetSchema' => array( 2919 'type' => 'object', 2920 'properties' => array( 2921 'sticky' => array( 2922 'type' => 'boolean', 2923 ), 2924 ), 2925 ), 2926 ); 2927 } 2928 2929 if ( post_type_supports( $this->post_type, 'author' ) ) { 2930 $links[] = array( 2931 'rel' => 'https://api.w.org/action-assign-author', 2932 'title' => __( 'The current user can change the author on this post.' ), 2933 'href' => $href, 2934 'targetSchema' => array( 2935 'type' => 'object', 2936 'properties' => array( 2937 'author' => array( 2938 'type' => 'integer', 2939 ), 2940 ), 2941 ), 2942 ); 2943 } 2944 2945 $links[] = array( 2946 'rel' => 'https://api.w.org/action-trash', 2947 'title' => __( 'The current user can move this post to the trash.' ), 2948 'href' => $href, 2949 ); 2950 2951 if ( 'page' === $this->post_type ) { 2952 $links[] = array( 2953 'rel' => 'https://api.w.org/action-set-homepage', 2954 'title' => __( 'The current user can set this page as the homepage.' ), 2955 'href' => $href, 2956 ); 2957 2958 $links[] = array( 2959 'rel' => 'https://api.w.org/action-set-posts-page', 2960 'title' => __( 'The current user can set this page as the posts page.' ), 2961 'href' => $href, 2962 ); 2963 } 2964 2965 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 2966 2967 foreach ( $taxonomies as $tax ) { 2968 $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name; 2969 2970 /* translators: %s: Taxonomy name. */ 2971 $assign_title = sprintf( __( 'The current user can assign terms in the %s taxonomy.' ), $tax->name ); 2972 /* translators: %s: Taxonomy name. */ 2973 $create_title = sprintf( __( 'The current user can create terms in the %s taxonomy.' ), $tax->name ); 2974 2975 $links[] = array( 2976 'rel' => 'https://api.w.org/action-assign-' . $tax_base, 2977 'title' => $assign_title, 2978 'href' => $href, 2979 'targetSchema' => array( 2980 'type' => 'object', 2981 'properties' => array( 2982 $tax_base => array( 2983 'type' => 'array', 2984 'items' => array( 2985 'type' => 'integer', 2986 ), 2987 ), 2988 ), 2989 ), 2990 ); 2991 2992 $links[] = array( 2993 'rel' => 'https://api.w.org/action-create-' . $tax_base, 2994 'title' => $create_title, 2995 'href' => $href, 2996 'targetSchema' => array( 2997 'type' => 'object', 2998 'properties' => array( 2999 $tax_base => array( 3000 'type' => 'array', 3001 'items' => array( 3002 'type' => 'integer', 3003 ), 3004 ), 3005 ), 3006 ), 3007 ); 3008 } 3009 3010 return $links; 3011 } 3012 3013 /** 3014 * Retrieves the query params for the posts collection. 3015 * 3016 * @since 4.7.0 3017 * @since 5.4.0 The `tax_relation` query parameter was added. 3018 * @since 5.7.0 The `modified_after` and `modified_before` query parameters were added. 3019 * 3020 * @return array Collection parameters. 3021 */ 3022 public function get_collection_params() { 3023 $query_params = parent::get_collection_params(); 3024 3025 $query_params['context']['default'] = 'view'; 3026 3027 $query_params['after'] = array( 3028 'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ), 3029 'type' => 'string', 3030 'format' => 'date-time', 3031 ); 3032 3033 $query_params['modified_after'] = array( 3034 'description' => __( 'Limit response to posts modified after a given ISO8601 compliant date.' ), 3035 'type' => 'string', 3036 'format' => 'date-time', 3037 ); 3038 3039 if ( post_type_supports( $this->post_type, 'author' ) ) { 3040 $query_params['author'] = array( 3041 'description' => __( 'Limit result set to posts assigned to specific authors.' ), 3042 'type' => 'array', 3043 'items' => array( 3044 'type' => 'integer', 3045 ), 3046 'default' => array(), 3047 ); 3048 $query_params['author_exclude'] = array( 3049 'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ), 3050 'type' => 'array', 3051 'items' => array( 3052 'type' => 'integer', 3053 ), 3054 'default' => array(), 3055 ); 3056 } 3057 3058 $query_params['before'] = array( 3059 'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ), 3060 'type' => 'string', 3061 'format' => 'date-time', 3062 ); 3063 3064 $query_params['modified_before'] = array( 3065 'description' => __( 'Limit response to posts modified before a given ISO8601 compliant date.' ), 3066 'type' => 'string', 3067 'format' => 'date-time', 3068 ); 3069 3070 $query_params['exclude'] = array( 3071 'description' => __( 'Ensure result set excludes specific IDs.' ), 3072 'type' => 'array', 3073 'items' => array( 3074 'type' => 'integer', 3075 ), 3076 'default' => array(), 3077 ); 3078 3079 $query_params['include'] = array( 3080 'description' => __( 'Limit result set to specific IDs.' ), 3081 'type' => 'array', 3082 'items' => array( 3083 'type' => 'integer', 3084 ), 3085 'default' => array(), 3086 ); 3087 3088 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) { 3089 $query_params['menu_order'] = array( 3090 'description' => __( 'Limit result set to posts with a specific menu_order value.' ), 3091 'type' => 'integer', 3092 ); 3093 } 3094 3095 $query_params['search_semantics'] = array( 3096 'description' => __( 'How to interpret the search input.' ), 3097 'type' => 'string', 3098 'enum' => array( 'exact' ), 3099 ); 3100 3101 $query_params['offset'] = array( 3102 'description' => __( 'Offset the result set by a specific number of items.' ), 3103 'type' => 'integer', 3104 ); 3105 3106 $query_params['order'] = array( 3107 'description' => __( 'Order sort attribute ascending or descending.' ), 3108 'type' => 'string', 3109 'default' => 'desc', 3110 'enum' => array( 'asc', 'desc' ), 3111 ); 3112 3113 $query_params['orderby'] = array( 3114 'description' => __( 'Sort collection by post attribute.' ), 3115 'type' => 'string', 3116 'default' => 'date', 3117 'enum' => array( 3118 'author', 3119 'date', 3120 'id', 3121 'include', 3122 'modified', 3123 'parent', 3124 'relevance', 3125 'slug', 3126 'include_slugs', 3127 'title', 3128 ), 3129 ); 3130 3131 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) { 3132 $query_params['orderby']['enum'][] = 'menu_order'; 3133 } 3134 3135 $post_type = get_post_type_object( $this->post_type ); 3136 3137 if ( $post_type->hierarchical || 'attachment' === $this->post_type ) { 3138 $query_params['parent'] = array( 3139 'description' => __( 'Limit result set to items with particular parent IDs.' ), 3140 'type' => 'array', 3141 'items' => array( 3142 'type' => 'integer', 3143 ), 3144 'default' => array(), 3145 ); 3146 $query_params['parent_exclude'] = array( 3147 'description' => __( 'Limit result set to all items except those of a particular parent ID.' ), 3148 'type' => 'array', 3149 'items' => array( 3150 'type' => 'integer', 3151 ), 3152 'default' => array(), 3153 ); 3154 } 3155 3156 $query_params['search_columns'] = array( 3157 'default' => array(), 3158 'description' => __( 'Array of column names to be searched.' ), 3159 'type' => 'array', 3160 'items' => array( 3161 'enum' => array( 'post_title', 'post_content', 'post_excerpt' ), 3162 'type' => 'string', 3163 ), 3164 ); 3165 3166 $query_params['slug'] = array( 3167 'description' => __( 'Limit result set to posts with one or more specific slugs.' ), 3168 'type' => 'array', 3169 'items' => array( 3170 'type' => 'string', 3171 ), 3172 ); 3173 3174 $query_params['status'] = array( 3175 'default' => 'publish', 3176 'description' => __( 'Limit result set to posts assigned one or more statuses.' ), 3177 'type' => 'array', 3178 'items' => array( 3179 'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ), 3180 'type' => 'string', 3181 ), 3182 'sanitize_callback' => array( $this, 'sanitize_post_statuses' ), 3183 ); 3184 3185 $query_params = $this->prepare_taxonomy_limit_schema( $query_params ); 3186 3187 if ( 'post' === $this->post_type ) { 3188 $query_params['sticky'] = array( 3189 'description' => __( 'Limit result set to items that are sticky.' ), 3190 'type' => 'boolean', 3191 ); 3192 3193 $query_params['ignore_sticky'] = array( 3194 'description' => __( 'Whether to ignore sticky posts or not.' ), 3195 'type' => 'boolean', 3196 'default' => true, 3197 ); 3198 } 3199 3200 if ( post_type_supports( $this->post_type, 'post-formats' ) ) { 3201 $query_params['format'] = array( 3202 'description' => __( 'Limit result set to items assigned one or more given formats.' ), 3203 'type' => 'array', 3204 'uniqueItems' => true, 3205 'items' => array( 3206 'enum' => array_values( get_post_format_slugs() ), 3207 'type' => 'string', 3208 ), 3209 ); 3210 } 3211 3212 /** 3213 * Filters collection parameters for the posts controller. 3214 * 3215 * The dynamic part of the filter `$this->post_type` refers to the post 3216 * type slug for the controller. 3217 * 3218 * This filter registers the collection parameter, but does not map the 3219 * collection parameter to an internal WP_Query parameter. Use the 3220 * `rest_{$this->post_type}_query` filter to set WP_Query parameters. 3221 * 3222 * @since 4.7.0 3223 * 3224 * @param array $query_params JSON Schema-formatted collection parameters. 3225 * @param WP_Post_Type $post_type Post type object. 3226 */ 3227 return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type ); 3228 } 3229 3230 /** 3231 * Sanitizes and validates the list of post statuses, including whether the 3232 * user can query private statuses. 3233 * 3234 * @since 4.7.0 3235 * 3236 * @param string|array $statuses One or more post statuses. 3237 * @param WP_REST_Request $request Full details about the request. 3238 * @param string $parameter Additional parameter to pass to validation. 3239 * @return array|WP_Error A list of valid statuses, otherwise WP_Error object. 3240 */ 3241 public function sanitize_post_statuses( $statuses, $request, $parameter ) { 3242 $statuses = wp_parse_slug_list( $statuses ); 3243 3244 // The default status is different in WP_REST_Attachments_Controller. 3245 $attributes = $request->get_attributes(); 3246 $default_status = $attributes['args']['status']['default']; 3247 3248 foreach ( $statuses as $status ) { 3249 if ( $status === $default_status ) { 3250 continue; 3251 } 3252 3253 $post_type_obj = get_post_type_object( $this->post_type ); 3254 3255 if ( current_user_can( $post_type_obj->cap->edit_posts ) || 'private' === $status && current_user_can( $post_type_obj->cap->read_private_posts ) ) { 3256 $result = rest_validate_request_arg( $status, $request, $parameter ); 3257 if ( is_wp_error( $result ) ) { 3258 return $result; 3259 } 3260 } else { 3261 return new WP_Error( 3262 'rest_forbidden_status', 3263 __( 'Status is forbidden.' ), 3264 array( 'status' => rest_authorization_required_code() ) 3265 ); 3266 } 3267 } 3268 3269 return $statuses; 3270 } 3271 3272 /** 3273 * Prepares the 'tax_query' for a collection of posts. 3274 * 3275 * @since 5.7.0 3276 * 3277 * @param array $args WP_Query arguments. 3278 * @param WP_REST_Request $request Full details about the request. 3279 * @return array Updated query arguments. 3280 */ 3281 private function prepare_tax_query( array $args, WP_REST_Request $request ) { 3282 $relation = $request['tax_relation']; 3283 3284 if ( $relation ) { 3285 $args['tax_query'] = array( 'relation' => $relation ); 3286 } 3287 3288 $taxonomies = wp_list_filter( 3289 get_object_taxonomies( $this->post_type, 'objects' ), 3290 array( 'show_in_rest' => true ) 3291 ); 3292 3293 foreach ( $taxonomies as $taxonomy ) { 3294 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 3295 3296 $tax_include = $request[ $base ]; 3297 $tax_exclude = $request[ $base . '_exclude' ]; 3298 3299 if ( $tax_include ) { 3300 $terms = array(); 3301 $include_children = false; 3302 $operator = 'IN'; 3303 3304 if ( rest_is_array( $tax_include ) ) { 3305 $terms = $tax_include; 3306 } elseif ( rest_is_object( $tax_include ) ) { 3307 $terms = empty( $tax_include['terms'] ) ? array() : $tax_include['terms']; 3308 $include_children = ! empty( $tax_include['include_children'] ); 3309 3310 if ( isset( $tax_include['operator'] ) && 'AND' === $tax_include['operator'] ) { 3311 $operator = 'AND'; 3312 } 3313 } 3314 3315 if ( $terms ) { 3316 $args['tax_query'][] = array( 3317 'taxonomy' => $taxonomy->name, 3318 'field' => 'term_id', 3319 'terms' => $terms, 3320 'include_children' => $include_children, 3321 'operator' => $operator, 3322 ); 3323 } 3324 } 3325 3326 if ( $tax_exclude ) { 3327 $terms = array(); 3328 $include_children = false; 3329 3330 if ( rest_is_array( $tax_exclude ) ) { 3331 $terms = $tax_exclude; 3332 } elseif ( rest_is_object( $tax_exclude ) ) { 3333 $terms = empty( $tax_exclude['terms'] ) ? array() : $tax_exclude['terms']; 3334 $include_children = ! empty( $tax_exclude['include_children'] ); 3335 } 3336 3337 if ( $terms ) { 3338 $args['tax_query'][] = array( 3339 'taxonomy' => $taxonomy->name, 3340 'field' => 'term_id', 3341 'terms' => $terms, 3342 'include_children' => $include_children, 3343 'operator' => 'NOT IN', 3344 ); 3345 } 3346 } 3347 } 3348 3349 return $args; 3350 } 3351 3352 /** 3353 * Prepares the collection schema for including and excluding items by terms. 3354 * 3355 * @since 5.7.0 3356 * 3357 * @param array $query_params Collection schema. 3358 * @return array Updated schema. 3359 */ 3360 private function prepare_taxonomy_limit_schema( array $query_params ) { 3361 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); 3362 3363 if ( ! $taxonomies ) { 3364 return $query_params; 3365 } 3366 3367 $query_params['tax_relation'] = array( 3368 'description' => __( 'Limit result set based on relationship between multiple taxonomies.' ), 3369 'type' => 'string', 3370 'enum' => array( 'AND', 'OR' ), 3371 ); 3372 3373 $limit_schema = array( 3374 'type' => array( 'object', 'array' ), 3375 'oneOf' => array( 3376 array( 3377 'title' => __( 'Term ID List' ), 3378 'description' => __( 'Match terms with the listed IDs.' ), 3379 'type' => 'array', 3380 'items' => array( 3381 'type' => 'integer', 3382 ), 3383 ), 3384 array( 3385 'title' => __( 'Term ID Taxonomy Query' ), 3386 'description' => __( 'Perform an advanced term query.' ), 3387 'type' => 'object', 3388 'properties' => array( 3389 'terms' => array( 3390 'description' => __( 'Term IDs.' ), 3391 'type' => 'array', 3392 'items' => array( 3393 'type' => 'integer', 3394 ), 3395 'default' => array(), 3396 ), 3397 'include_children' => array( 3398 'description' => __( 'Whether to include child terms in the terms limiting the result set.' ), 3399 'type' => 'boolean', 3400 'default' => false, 3401 ), 3402 ), 3403 'additionalProperties' => false, 3404 ), 3405 ), 3406 ); 3407 3408 $include_schema = array_merge( 3409 array( 3410 /* translators: %s: Taxonomy name. */ 3411 'description' => __( 'Limit result set to items with specific terms assigned in the %s taxonomy.' ), 3412 ), 3413 $limit_schema 3414 ); 3415 // 'operator' is supported only for 'include' queries. 3416 $include_schema['oneOf'][1]['properties']['operator'] = array( 3417 'description' => __( 'Whether items must be assigned all or any of the specified terms.' ), 3418 'type' => 'string', 3419 'enum' => array( 'AND', 'OR' ), 3420 'default' => 'OR', 3421 ); 3422 3423 $exclude_schema = array_merge( 3424 array( 3425 /* translators: %s: Taxonomy name. */ 3426 'description' => __( 'Limit result set to items except those with specific terms assigned in the %s taxonomy.' ), 3427 ), 3428 $limit_schema 3429 ); 3430 3431 foreach ( $taxonomies as $taxonomy ) { 3432 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 3433 $base_exclude = $base . '_exclude'; 3434 3435 $query_params[ $base ] = $include_schema; 3436 $query_params[ $base ]['description'] = sprintf( $query_params[ $base ]['description'], $base ); 3437 3438 $query_params[ $base_exclude ] = $exclude_schema; 3439 $query_params[ $base_exclude ]['description'] = sprintf( $query_params[ $base_exclude ]['description'], $base ); 3440 3441 if ( ! $taxonomy->hierarchical ) { 3442 unset( $query_params[ $base ]['oneOf'][1]['properties']['include_children'] ); 3443 unset( $query_params[ $base_exclude ]['oneOf'][1]['properties']['include_children'] ); 3444 } 3445 } 3446 3447 return $query_params; 3448 } 3449 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Thu Dec 3 08:20:02 2026 | Cross-referenced by PHPXref |