16

I am looking for a way to run a global search query across all or multiple post types using WP REST API.

I am able to search posts using:

http://example.com/wp-json/wp/v2/posts?search=test

In turn I am able to search pages using:

http://example.com/wp-json/wp/v2/pages?search=test

How do I search across both posts and pages? I was able to do this in WP REST API V1 by specifying multiple type[] variables in the query?

Marc
  • 4,661
  • 3
  • 40
  • 62

2 Answers2

16

This might be a bit late but there is an endpoint for that in the v2-api: /wp-json/wp/v2/search.

You can search for any specific post_type by supplying it via subtype or leave it to the default (any) to search in all post_types.

 

Edit: Of course you can also specifiy multiple with an array as you did before.

Consti P
  • 445
  • 5
  • 11
  • Can you give an example of this? – John Dee Sep 03 '20 at 13:21
  • 1
    @JohnDee `/wp-json/wp/v2/search/?subtype=page&subtype=post` Arrays in query strings are done by redefining the key. Cleaner `/wp-json/wp/v2/search/?subtype[]=page&subtype[]=post` (brackets to show it's an array. This needs to be added to work in forms). Reference: https://developer.wordpress.org/rest-api/reference/search-results/. `subtype` can be any post type (try sending an invalid one for more info) – Consti P Sep 03 '20 at 17:27
  • 1
    How do we include a search term with this? – Akhilesh Kumar Aug 31 '21 at 05:59
  • 1
    @AkhileshKumar See the documentation I posted (https://developer.wordpress.org/rest-api/reference/search-results/#arguments), add a `search` parameter. – Consti P Aug 31 '21 at 07:27
3

Here are some examples using the REST API search endpoint for searching all content or specific content type(s).

Search For a Term in All Site Content

/wp-json/wp/v2/search/?search=searchterm

Search For a Term and Limit Results to a Custom Post Type

/wp-json/wp/v2/search/?subtype=book&search=searchterm

Search For a Term and Limit Results to multiple Custom Post Types

/wp-json/wp/v2/search/?subtype[]=book&subtype[]=movie&search=searchterm

REST API Search Result Documentation

Marc
  • 4,661
  • 3
  • 40
  • 62