SearchWP Results In WooCommerce Product & Variation REST API Search

There’s a super nifty extension out there to give SearchWP it’s own REST API endpoint and it’s super useful! It’s made by my good friends at Caldera Forms and it may just solve your needs.  But it wasn’t helping me solve a problem I had.  On a project I have a very customized hooked into and filtered situation going on with the WooCommerce products endpoint on the API.  I didn’t want to refactor to work with that plugin so I needed to get results going into the primary products endpoint we are already using.

?search=keyword

To use the default WordPress search functionality in an API endpoint you tack on ?search=keyword.  This is cool and all but we are implementing SearchWP.  SearchWP works by intercepting WP_Query when it’s got the ‘is_search’ set.  It then does it’s own thing and returns the results.

The issue is, it doesn’t intercept when doing a search through the REST API.  Why? I forgot, I dug through code for hours and figured it out but I can’t remember or sum up the reason so I’m just going to give my solution.

Pass Along IDs From SWP_Query

First thing you will want to do is hook into pre_get_posts and inject SWP_Query search results into the query’s ‘post__in’ parameter.  You need to also tell the query it’s not a search and be sure you are even in the right place to be doing this.  Here’s a quick gist

https://gist.github.com/ChrisFlannagan/7c0ae5510482a9cea9fb488c7f088fca

Order By Post__In

We can’t just let this go and it will work.  The query may still try to order by something other than the result of IDs we got from SearchWP.  So we need to hook into rest_{post_type}_query.  Here’s the gist of that.

https://gist.github.com/ChrisFlannagan/42488c578c3a9167ee2a7290f937d358

Leave a Reply

Your email address will not be published.