WP_Query: how to search tags in addition to a custom post type?
-
26-04-2021 - |
Question
Below is what I have so far for a custom rest endpoint ('placesdb/v1/search?term=') for a custom post type (place). This successfully returns all the places that have the search term in the title or content. However, I also want to return all the tags (tag archive pages) that match the search term (the same result as calling the non-custom '/wp/v2/tags?search='). Is it possible to somehow add the tag results to the place results? I already successfully did the front-end approach of calling the places and tags endpoints separately via ajax, but I would rather get all the data in one swoop. Hence my attempt at making this custom endpoint.
function placesSearch() {
register_rest_route('placesdb/v1', 'search', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'placesSearchResults'
));
}
function placesSearchResults($data) {
$places = new WP_Query(array(
'post_type' => array('place'),
's' => sanitize_text_field($data['term'])
));
$placesResults = array();
while($places->have_posts()) {
$places->the_post();
array_push($placesResults, array(
'title' => get_the_title(),
'permalink' => get_the_permalink()
));
}
return $placesResults;
}
add_action('rest_api_init', 'placesSearch');
Solution
Seems that WP_Query does not have the ability to query tags or categories. I ended up using the get_tags
WordPress function and passed in the search term then merged the result with the WP_Query of the "places" endpoint.
function placesSearch() {
register_rest_route('placesdb/v1', 'search', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'placesSearchResults'
));
}
function placesSearchResults($data) {
$places = new WP_Query(array(
'post_type' => array('place'),
's' => sanitize_text_field($data['term'])
));
wp_reset_postdata();
$placesResults = array();
while($places->have_posts()) {
$places->the_post();
array_push($placesResults, array(
'title' => get_the_title(),
'permalink' => get_the_permalink()
));
}
$tags = get_tags(array(
'search' => sanitize_text_field($data['term'])
));
$tagsResults = array();
foreach ($tags as &$tag) {
array_push($tagsResults, array(
'title' => $tag->name,
'permalink' => get_tag_link($tag->term_id)
));
}
return array_merge($placesResults, $tagsResults);
}
add_action('rest_api_init', 'placesSearch');