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