0

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
      ),
      
  )

) );

2
  • What error? How are you passing the slugs? Jun 11, 2021 at 6:59
  • This is API: wp-json/w1/unica/posts/unica-12-1&interact and error is No route was found matching the URL and request method.
    – user205932
    Jun 11, 2021 at 7:18

1 Answer 1

0

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.").

Your Answer

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.