Pass multiple tags slug to rest API

The question:

I can pass a single tag slug to WP REST API. But, cannot pass multiple tags slug. It gives an error – the request was made to wp-json/w1/unica/posts/unica-12-1&interact and the error message is:

No route was found matching the URL and request method.

My code:

register_rest_route( 'w1/page_name/', 'posts/(?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*)', array(
  'methods' => 'GET',
  'callback' => 'page_name_get_posts_by_tag',
  'args' => array(
      'slug' => array (
          'required' => true

) );

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You’re getting the error because the URL format is invalid — that & there is invalid because there’s no ? in the URL: wp-json/w1/unica/posts/unica-12-1&interact, but even if you actually added the ?, that’s not how to pass multiple slugs to the API.

So how can you pass multiple slugs to your custom endpoint?

register_rest_route( 'w1/page_name/', 'posts/(?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*)', ... );

So that is your code, which means the route is using a path variable which is in the form of /(?P<parameter name><regular expression pattern>) and in your case, the parameter name is slug which accepts a single slug value consisting of alphanumeric and dash (-) characters only, therefore you are supposed to pass just one slug.

But it’s actually possible to send multiple slugs, e.g. /wp-json/w1/page_name/posts/some-string?slug[]=unica-12-1&slug[]=interact or /wp-json/w1/page_name/posts/some-string?slug=unica-12-1,interact, whereby the first one is using the array format (i.e. slug[]).

But then, the some-string has to be there because of the path variable which needs to be in the form of posts/<slug here>, so you could either just remove the path variable, or change the RegEx pattern so that it allows comma to be used for separating multiple slugs, then in your main callback (the page_name_get_posts_by_tag() function), you could use explode() to convert the slug string into an array of slugs.

So for example, instead of (?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*), you could try with (?P<slug>([w-],?)+) and then make a request to /wp-json/w1/page_name/posts/unica-12-1,interact, then see if you’re still getting the same error (“No route was found matching the URL and request method.“).

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment