...

/

Keyword Searching with WP_Query

Keyword Searching with WP_Query

Learn to replace the hard coded search term with a user input.

We will now modify the custom query arguments to add a search string that filters out results returned by our custom REST API. The WP_Query object has a search parameter which shows posts based on a search keyword. The parameter is called s and it takes the keyword as a string.

Search parameter

If we want to search for a teacher post which has the word jane in it, we will use the following array of arguments.

<?php
$args = array(
'post_type' => array('post', 'page', 'course', 'teacher', 'event'),
'posts_per_page' => -1,
's' => 'jane'
);
Using a search parameter

With this additional argument, now the WP_Query object contains only the posts which have the search term in them. If we visit the custom search route (by adding /wp-json/excellence/v1/search to the root URL), it shows only one post in the teachers subarray with the word jane in it.

Press + to interact
Keyword based results
Keyword based results

In the same way if we change the search keyword to career, we get three results back where the posts sub array contains one result and the events sub array contains two results.

Use dynamic value for search parameter

To make the search term dynamic, we need to fetch the value that the user enters in the input field on the search overlay panel. We will pass this data to the school_search_results function to be used as the value of the s parameter.

As a reminder, in the search-route.php file the school_rest_api function registers the search route and lists a callback function school_search_results. WordPress passes along data from the request to the callback function. This data is an object of the WP_REST_request class. We can access this object if we change our function definition to accept an argument $request.

<?php
function school_search_results($request){
}
Accessing an object of the WP_REST_request class

If we search for the word career, our URL will look something like this: /wp-json/excellence/v1/search?term=career. This URL contains the attribute term and its value career. This means we need an ...