WP Custom Route API


You can serve only the stuff you need with a custom WordPress API endpoint.

add_action('rest_api_init', 'joshcoastRegisterSearch');

function joshcoastRegisterSearch() {
    register_rest_route('joshcoast/v1', 'search', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'joshcoastSearchResults'
    ));
}
// "$data" is our Parameter from the url in the API, you can name it whatever you like.
function joshcoastSearchResults($data) {
    $portfolios = new WP_Query(array(
        'post_type' => 'portfolio',
        // 's' stands for search, $data is an array from the parameter of the api url.
        // The key 'term' can be anything, it just needs to match the key we use in the url.
        // Example http://joshcoast.local/wp-json/joshcoast/v1/search?term=audinate&color=yellow 
        // So, The search will find "audinate" but if you put in $data['color'], this would return 'yellow'
        // The sanitize_text_field() is just a security precaution.
        's' => sanitize_text_field($data['term'])
    ));
    
    $portfolioResults = array();

    while($portfolios->have_posts()) {
        $portfolios->the_post();
        array_push($portfolioResults, array(
            'title' => get_the_title(),
            'permalink' => get_the_permalink()
        ));
    }

    return $portfolioResults;
}