Search code examples
wordpresswordpress-rest-api

Manipulate wordpress REST API search query


I want to add a custom field to be included into my search query. That's done via meta_query, I am fully aware of that but the issue is, I don't know, where to hang into to manipulate the query args to my needs.

So I am looking for a filter, to to get into REST API search request (/wp/v2/search), any clue?


Solution

  • You can implement the following hook:

    add_filter( 'rest_post_search_query', 'rest_search_add_custom_field_cb', 10, 2 );
    function rest_search_add_custom_field_cb( $query_args, $request ) {
        // filter...
    
        return $query_args;
    }
    

    You can modify the search query and include additional params like meta query, etc.

    The return value of this filter will be used by WordPress in the following context:

    ...
    $query->query( $query_args );
    ...