Searches posts for a given search request.
Parameters
$request
WP_REST_Requestrequired- Full REST request.
Source
public function search_items( WP_REST_Request $request ) {
// Get the post types to search for the current request.
$post_types = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ];
if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $post_types, true ) ) {
$post_types = $this->subtypes;
}
$query_args = array(
'post_type' => $post_types,
'post_status' => 'publish',
'paged' => (int) $request['page'],
'posts_per_page' => (int) $request['per_page'],
'ignore_sticky_posts' => true,
);
if ( ! empty( $request['search'] ) ) {
$query_args['s'] = $request['search'];
}
if ( ! empty( $request['exclude'] ) ) {
$query_args['post__not_in'] = $request['exclude'];
}
if ( ! empty( $request['include'] ) ) {
$query_args['post__in'] = $request['include'];
}
/**
* Filters the query arguments for a REST API post search request.
*
* Enables adding extra arguments or setting defaults for a post search request.
*
* @since 5.1.0
*
* @param array $query_args Key value array of query var to query value.
* @param WP_REST_Request $request The request used.
*/
$query_args = apply_filters( 'rest_post_search_query', $query_args, $request );
$query = new WP_Query();
$posts = $query->query( $query_args );
// Querying the whole post object will warm the object cache, avoiding an extra query per result.
$found_ids = wp_list_pluck( $posts, 'ID' );
$total = $query->found_posts;
return array(
self::RESULT_IDS => $found_ids,
self::RESULT_TOTAL => $total,
);
}
Hooks
- apply_filters( ‘rest_post_search_query’,
array $query_args ,WP_REST_Request $request ) Filters the query arguments for a REST API post search request.
Changelog
Version | Description |
---|---|
5.0.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.