WP_REST_Search_Controller::get_items() – Retrieves a collection of search results.

You appear to be a bot. Output may be restricted

Description

Retrieves a collection of search results.

Usage

$WP_REST_Response|WP_Error = WP_REST_Search_Controller::get_items( $request );

Parameters

$request
( WP_REST_Request ) required – Full details about the request.

Returns

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

Source

File name: wordpress/wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php
Lines:

1 to 56 of 56
  public function get_items( $request ) {
    $handler = $this->WP_REST_Search_Controller::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->WP_REST_Search_Controller::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 = 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;
  }
 

 View on GitHub View on Trac