WP_REST_Search_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error

In this article

Retrieves a collection of search results.

Parameters

$requestWP_REST_Requestrequired
Full details about the request.

Return

WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.

Source

public function get_items( $request ) {
	$handler = $this->get_search_handler( $request );
	if ( is_wp_error( $handler ) ) {
		return $handler;
	}

	$result = $handler->search_items( $request );

	if ( ! isset( $result[ WP_REST_Search_Handler::RESULT_IDS ] ) || ! is_array( $result[ WP_REST_Search_Handler::RESULT_IDS ] ) || ! isset( $result[ WP_REST_Search_Handler::RESULT_TOTAL ] ) ) {
		return new WP_Error(
			'rest_search_handler_error',
			__( 'Internal search handler error.' ),
			array( 'status' => 500 )
		);
	}

	$ids = $result[ WP_REST_Search_Handler::RESULT_IDS ];

	$results = array();

	foreach ( $ids as $id ) {
		$data      = $this->prepare_item_for_response( $id, $request );
		$results[] = $this->prepare_response_for_collection( $data );
	}

	$total     = (int) $result[ WP_REST_Search_Handler::RESULT_TOTAL ];
	$page      = (int) $request['page'];
	$per_page  = (int) $request['per_page'];
	$max_pages = (int) ceil( $total / $per_page );

	if ( $page > $max_pages && $total > 0 ) {
		return new WP_Error(
			'rest_search_invalid_page_number',
			__( 'The page number requested is larger than the number of pages available.' ),
			array( 'status' => 400 )
		);
	}

	$response = rest_ensure_response( $results );
	$response->header( 'X-WP-Total', $total );
	$response->header( 'X-WP-TotalPages', $max_pages );

	$request_params = $request->get_query_params();
	$base           = add_query_arg( urlencode_deep( $request_params ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );

	if ( $page > 1 ) {
		$prev_link = add_query_arg( 'page', $page - 1, $base );
		$response->link_header( 'prev', $prev_link );
	}
	if ( $page < $max_pages ) {
		$next_link = add_query_arg( 'page', $page + 1, $base );
		$response->link_header( 'next', $next_link );
	}

	return $response;
}

Changelog

VersionDescription
5.0.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.