WP_REST_Post_Search_Handler::search_items()publicWP 5.0.0

Searches posts for a given search request.

Method of the class: WP_REST_Post_Search_Handler{}

Hooks from the method

Return

Array. Associative array containing found IDs and total count for the matching search results.

Usage

$WP_REST_Post_Search_Handler = new WP_REST_Post_Search_Handler();
$WP_REST_Post_Search_Handler->search_items( $request );
$request(WP_REST_Request) (required)
Full REST request.

Changelog

Since 5.0.0 Introduced.

WP_REST_Post_Search_Handler::search_items() code WP 6.5.2

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,
	);
}