set_query_params using custom params defined in functions file?

Question

I am using the Advanced Custom Fields and ACF to REST API plugins. In my functions file I have specified custom query parameters to filter my custom post type by ACF fields in my REST request:

add_filter('rest_product_query', function($args) {
  $fields = array('size', 'color');

  foreach ($fields as $field) {
    if (isset( $_GET[ $field ]) && ! empty($_GET[$field])) {
      $args['meta_query'][] = array(
        'key'   => $field,
        'value' => esc_sql($_GET[$field]),
      );
    }
  }
  return $args; 
});

This part is working great when I go directly to the REST API url in my browser ie:

https://example.com/wp-json/acf/v3/product?per_page=100&size=large&color=blue

However, I am now trying to make a request to this URL using WP_REST_Request(), but when I pass my custom parameters into the call, they are ignored. Here is what that code looks like:

$request = new WP_REST_Request('GET', '/acf/v3/product');
$request->set_query_params(
    ['per_page' => 100],
    ['size' => 'large'],
    ['color' => 'blue']
);
$response = rest_do_request($request);
$server = rest_get_server();
$data = $server->response_to_data($response, false);
$json = wp_json_encode($data);
echo count($data); // this returns 57 instead of the expected 15

When I go directly to the URL, 15 products are returned, but when I echo the count of the WP_REST_Request() response I am getting 57 results(all of the products). If I change the per_page parameter, it correctly returns the number of results I restrict it to, so it just seems to be ignoring only the custom parameters I have defined in my functions file.

Any ideas? Thanks!

0
user13286 4 weeks 2021-08-18T21:02:09-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse