wp query – WP_Query: how to search tags in addition to a custom post type?

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');

0
soultrust 2 years 2021-03-27T00:33:37-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse