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.

3

3 Answers

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

If you pass some value via POST REQUEST you can access them by using get_body_params() method

add_action( 'rest_api_init', function () { register_rest_route( "nh", "v2/slug", array( 'methods' => 'POST', 'callback' => 'my_awesome_func', ) ); } ); function my_awesome_func( $request ) { $queryParams = $request->get_body_params(); return $queryParams; } 


The object properties are protected therefore it is not possible to get them using the standard method, even if you want to access you will confront a Fatal Error.

I however tried to access values by first converting the object to array then loop through each item and get what is needed.

WP_REST_Request $request; $request2 = (array)$request; foreach($request2 as $req2) { if (is_array($req2)) { foreach($req2 as $req2_k => $req2_v) { if ($req2_k == 'cpt') { echo $req2_v; } } } } 

As you can see I wanted to obtain cpt value from attributes array index, you need to adjust the loop to your liking.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.