How to Use Query Parameters in Your WordPress REST API Route/Endpoint ⚡️

Tunnel on road with forest on other side.

When building a custom WordPress API endpoint to pull data from your WordPress site, you can pass query parameters into your URL or at the end of your slug to act as variables in your PHP API functions (in the format “?parameter-key=parameter-value”).

(Query parameters may be referred to as arguments, or could be confused to be called a slug.)

This can be useful if you want to have a dynamic API route that points to a function which returns different results based on the variable you input in the URL. For example, you may want to use a single API route to return posts of a particular “category_name”. It’s a route you will reuse multiple times but needing different “category_name”s.

The Function That Interprets Query Variables

I will show the full code that I used for retrieval below so you can try and reproduce, but the point of this blog post is simply in the function query_posts_and_pages_with_params, shown here:

Lynchpin function that gets query parameters / arguments

function query_posts_and_pages_with_params(WP_REST_Request $request) {
  $arg = $request->get_param( 'category_name' );
  return query_posts_and_pages($arg);
}

The URL we will pass that will make this function usable looks like:

https://your-site-name.com/wp-json/your-api-slug/v2/pages?category_name=desired-category-name

Note that in the part in the URL containing “/your-api-slug/v2/pages”, the slug “/pages” is a name chosen by us. “pages” can be chosen to be anything.

The key here is we are using WP_REST_Request $request for the function’s arguments. The query parameter(s) / variable(s) are stored in $request. There are multiple ways of formatting the function to interpret the WP REST API query parameter which you can read about in the WordPress docs here. In the format above, the $request variable holds our parameters. We can assign the parameter we wish to pick out by using the PHP object arrow / aka object operator / aka dart operator ( -> ).

The fact that we passed ‘category_name’ as our query variable key allows us to use the function get_param() to retrieve the value attached to this key. ‘category_name’ is a chosen key name. The name could be any name, but ‘category_name’ is easy to remember and makes sense because it is identical to the name of the actual WordPress key that is called ‘category_name’.

In a JavaScript Axios call, the dynamic format may look like below:

function getPages(apiQueryParam){
  const pages = (await axios.get(`https://your-site-name.com/wp-json/your-api-slug/v2/pages?category_name=${apiQueryParam}`)).data
  return pages
}

Full Code:

Here is the full code with 3 functions used to retrieve pages by their “category_name” using the dynamic API route and query variables:

register_rest_route( 'your-sites-api-route-name/v2', '/pages[or your chosen slug for api]', array(
  'methods' => 'GET', 
  'callback' => 'query_posts_and_pages_with_params' 
) );

function query_posts_and_pages_with_params(WP_REST_Request $request) {
  $arg = $request->get_param( 'category_name' );
  return query_posts_and_pages($arg);
}

function query_posts_and_pages($category_name){
  $args = array(
      'post_type' => array('post', 'page'),
      'showposts' => '100',
      'category_name' => $category_name,
      'order' => 'DESC',
      'orderby' => 'date',
  );
  return fetchByPostTypeAndTax($args);
}

function fetchByPostTypeAndTax($args) {
  // Run a custom query
  $meta_query = new WP_Query($args);
  if($meta_query->have_posts()) {
      //Define an empty array
      $data = array();
      // Store each post's data in the array
      while($meta_query->have_posts()) {
          $meta_query->the_post();
          $id = get_the_ID();
          $post = get_post($id);
          $link = get_permalink($id);
          $featured_image = get_the_post_thumbnail_url($id);
          $post_object = (object) [
              'id' => $post->ID,
              'title' => (object) ['rendered' => $post->post_title],
              'date' => $post->post_date,
              'slug' => $post->post_name,
              'link' => $link,
              'featured_img_url' => $featured_image,
              'image' => get_the_post_thumbnail_url($post->ID),
              'excerpt' => (object) ['rendered' => get_the_excerpt()]
          ];
          $data[] = $post_object;
      }
      // Return the data
      return $data;
  } else {
      // If there is no post
      return 'No post to show';
  }
}

That’s It!

Good luck with your own API calls. It took me a bit to figure out how to use query variables. I hope this blog helps you succeed! 🪐

Sources

WordPress Docs: Using WordPress Arguments from URL: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments

WordPress Docs: How to use WordPress REST Parameters / Query Parameters: https://developer.wordpress.org/rest-api/requests/#parameters

Featured Image: Road Tunnel by Aaron Burden on Unsplash