Search code examples
phpwordpresswordpress-rest-api

Why can't I access the query params from WP_REST_Request?


On my blog, I'm trying to create an endpoint in order to load more articles using ajax. However, the query string parameters don't seem to be passed down to my function. Here's my code, all of it is in the function.php file:

add_action( 'rest_api_init', function () {
  register_rest_route( 'blog', '/articles', array(
    'methods' => WP_REST_Server::READABLE,
    'callback' => 'load_more'
  ));
});

function load_more(WP_REST_Request $request) {
  var_dump($request->has_valid_params());
  var_dump($request->get_params());
  var_dump($request);
}

And here is what this returns when I call /wp-json/blog/articles/?lang=en&tag=test :

bool(true)

array(0) {}

object(WP_REST_Request)#2259 (8) {
  ["method":protected]=>
  string(3) "GET"
  ["params":protected]=>
  array(6) {
    ["URL"]=>
    array(0) {
    }
    ["GET"]=>
    array(0) {
    }
    ["POST"]=>
    array(0) {
    }
    ["FILES"]=>
    array(0) {
    }
    ["JSON"]=>
    NULL
    ["defaults"]=>
    array(0) {
    }
  }
  ["body":protected]=>
  string(0) ""
  ["route":protected]=>
  string(14) "/blog/articles"
  ["attributes":protected]=>
  array(6) {
    ["methods"]=>
    array(1) {
      ["GET"]=>
      bool(true)
    }
    ["accept_json"]=>
    bool(false)
    ["accept_raw"]=>
    bool(false)
    ["show_in_index"]=>
    bool(true)
    ["args"]=>
    array(0) {
    }
    ["callback"]=>
    string(9) "load_more"
  }
  ["parsed_json":protected]=>
  bool(true)
  ["parsed_body":protected]=>
  bool(false)
}

It's almost like the parameters were deleted from the request object before reaching my function.


Solution

  • You can access query parameters via WP_REST_Request::get_query_params():

    $queryParams = $request->get_query_params();
    $tag = $queryParams['tag'];
    

    Alternatively you can use

    $tag = $request->get_param('tag');
    

    but that merges $_POST, $_GET and path parameters in that order