WordPress REST API Global Search (API V2)
Asked Answered
C

2

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?

Chiang answered 28/6, 2016 at 19:30 Comment(0)
E
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.

Entomb answered 25/4, 2019 at 9:42 Comment(4)
Can you give an example of this?Korry
@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: developer.wordpress.org/rest-api/reference/search-results. subtype can be any post type (try sending an invalid one for more info)Entomb
How do we include a search term with this?Prominent
@AkhileshKumar See the documentation I posted (developer.wordpress.org/rest-api/reference/search-results/…), add a search parameter.Entomb
C
4

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

Chiang answered 20/10, 2022 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.