: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
* REST API: WP_REST_Posts_Controller class
* Core class to access posts via the REST API.
* @see WP_REST_Controller
class WP_REST_Posts_Controller extends WP_REST_Controller {
* Instance of a post meta fields object.
* @var WP_REST_Post_Meta_Fields
* Passwordless post access permitted.
protected $password_check_passed = array();
* Whether the controller supports batching.
protected $allow_batch = array( 'v1' => true );
* @param string $post_type Post type.
public function __construct( $post_type ) {
$this->post_type = $post_type;
$obj = get_post_type_object( $post_type );
$this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
$this->namespace = ! empty( $obj->rest_namespace ) ? $obj->rest_namespace : 'wp/v2';
$this->meta = new WP_REST_Post_Meta_Fields( $this->post_type );
* Registers the routes for posts.
* @see register_rest_route()
public function register_routes() {
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
$schema = $this->get_item_schema();
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
if ( isset( $schema['properties']['excerpt'] ) ) {
$get_item_args['excerpt_length'] = array(
'description' => __( 'Override the default excerpt length.' ),
if ( isset( $schema['properties']['password'] ) ) {
$get_item_args['password'] = array(
'description' => __( 'The password for the post if it is password protected.' ),
'/' . $this->rest_base . '/(?P<id>[\d]+)',
'description' => __( 'Unique identifier for the post.' ),
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => $get_item_args,
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'description' => __( 'Whether to bypass Trash and force deletion.' ),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
* Checks if a given request has access to read posts.
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has read access, WP_Error object otherwise.
public function get_items_permissions_check( $request ) {
$post_type = get_post_type_object( $this->post_type );
if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit posts in this post type.' ),
array( 'status' => rest_authorization_required_code() )
* Overrides the result of the post password check for REST requested posts.
* Allow users to read the content of password protected posts if they have
* previously passed a permission check or if they have the `edit_post` capability
* for the post being checked.
* @param bool $required Whether the post requires a password check.
* @param WP_Post $post The post been password checked.
* @return bool Result of password check taking in to account REST API considerations.
public function check_password_required( $required, $post ) {
$post = get_post( $post );
if ( ! empty( $this->password_check_passed[ $post->ID ] ) ) {
// Password previously checked and approved.
return ! current_user_can( 'edit_post', $post->ID );
* Retrieves a collection of posts.
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
public function get_items( $request ) {
// Ensure a search string is set in case the orderby is set to 'relevance'.
if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
'rest_no_search_term_defined',
__( 'You need to define a search term to order by relevance.' ),
// Ensure an include parameter is set in case the orderby is set to 'include'.
if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
'rest_orderby_include_missing_include',
__( 'You need to define an include parameter to order by include.' ),
// Retrieve the list of registered collection query parameters.
$registered = $this->get_collection_params();
* This array defines mappings between public API query parameters whose
* values are accepted as-passed, and their internal WP_Query parameter
* name equivalents (some are the same). Only values which are also
* present in $registered will be set.
$parameter_mappings = array(
'author' => 'author__in',
'author_exclude' => 'author__not_in',
'exclude' => 'post__not_in',
'menu_order' => 'menu_order',
'parent' => 'post_parent__in',
'parent_exclude' => 'post_parent__not_in',
'search_columns' => 'search_columns',
'slug' => 'post_name__in',
'status' => 'post_status',
* For each known parameter which is both registered and present in the request,
* set the parameter's value on the query $args.
foreach ( $parameter_mappings as $api_param => $wp_param ) {
if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
$args[ $wp_param ] = $request[ $api_param ];
// Check for & assign any parameters which require special handling or setting.
$args['date_query'] = array();
if ( isset( $registered['before'], $request['before'] ) ) {
$args['date_query'][] = array(
'before' => $request['before'],
if ( isset( $registered['modified_before'], $request['modified_before'] ) ) {
$args['date_query'][] = array(
'before' => $request['modified_before'],
'column' => 'post_modified',
if ( isset( $registered['after'], $request['after'] ) ) {
$args['date_query'][] = array(
'after' => $request['after'],
if ( isset( $registered['modified_after'], $request['modified_after'] ) ) {
$args['date_query'][] = array(
'after' => $request['modified_after'],
'column' => 'post_modified',
// Ensure our per_page parameter overrides any provided posts_per_page filter.
if ( isset( $registered['per_page'] ) ) {
$args['posts_per_page'] = $request['per_page'];
if ( isset( $registered['sticky'], $request['sticky'] ) ) {
$sticky_posts = get_option( 'sticky_posts', array() );
if ( ! is_array( $sticky_posts ) ) {
if ( $request['sticky'] ) {
* As post__in will be used to only get sticky posts,
* we have to support the case where post__in was already
$args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
* If we intersected, but there are no post IDs in common,
* WP_Query won't return "no posts" for post__in = array()
* so we have to fake it a bit.
if ( ! $args['post__in'] ) {
$args['post__in'] = array( 0 );
} elseif ( $sticky_posts ) {
* As post___not_in will be used to only get posts that
* are not sticky, we have to support the case where post__not_in
$args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
$args = $this->prepare_tax_query( $args, $request );
// Force the post_type argument, since it's not a user input variable.
$args['post_type'] = $this->post_type;
* Filters WP_Query arguments when querying posts via the REST API.
* The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
* Possible hook names include:
* - `rest_attachment_query`
* Enables adding extra arguments or setting defaults for a post collection request.
* @since 5.7.0 Moved after the `tax_query` query arg is generated.
* @link https://developer.wordpress.org/reference/classes/wp_query/
* @param array $args Array of arguments for WP_Query.
* @param WP_REST_Request $request The REST API request.
$args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
$query_args = $this->prepare_items_query( $args, $request );
$posts_query = new WP_Query();
$query_result = $posts_query->query( $query_args );
// Allow access to all password protected posts if the context is edit.
if ( 'edit' === $request['context'] ) {
add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 );
update_post_author_caches( $query_result );
update_post_parent_caches( $query_result );
if ( post_type_supports( $this->post_type, 'thumbnail' ) ) {
update_post_thumbnail_cache( $posts_query );
foreach ( $query_result as $post ) {
if ( 'edit' === $request['context'] ) {
$permission = $this->check_update_permission( $post );
$permission = $this->check_read_permission( $post );
$data = $this->prepare_item_for_response( $post, $request );
$posts[] = $this->prepare_response_for_collection( $data );
if ( 'edit' === $request['context'] ) {
remove_filter( 'post_password_required', array( $this, 'check_password_required' ) );
$page = (int) $query_args['paged'];
$total_posts = $posts_query->found_posts;
if ( $total_posts < 1 && $page > 1 ) {
// Out-of-bounds, run the query again without LIMIT for total count.
unset( $query_args['paged'] );
$count_query = new WP_Query();
$count_query->query( $query_args );
$total_posts = $count_query->found_posts;
$max_pages = (int) ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
if ( $page > $max_pages && $total_posts > 0 ) {
'rest_post_invalid_page_number',
__( 'The page number requested is larger than the number of pages available.' ),
$response = rest_ensure_response( $posts );
$response->header( 'X-WP-Total', (int) $total_posts );
$response->header( 'X-WP-TotalPages', (int) $max_pages );
$request_params = $request->get_query_params();
$collection_url = rest_url( rest_get_route_for_post_type_items( $this->post_type ) );
$base = add_query_arg( urlencode_deep( $request_params ), $collection_url );
if ( $prev_page > $max_pages ) {
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
if ( $max_pages > $page ) {
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
* Gets the post, if the ID is valid.
* @param int $id Supplied ID.
* @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
protected function get_post( $id ) {
__( 'Invalid post ID.' ),
$post = get_post( (int) $id );
if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
* Checks if a given request has access to read a post.
* @param WP_REST_Request $request Full details about the request.
* @return bool|WP_Error True if the request has read access for the item, WP_Error object or false otherwise.
public function get_item_permissions_check( $request ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
'rest_forbidden_context',