skip to Main Content

I just had a realisation that in my backend I can search everything in every search field. IE. I have a custom post type called Recipe, which is searchable in the normal Post search area (purely in the back-end). Is there any way to make sure you can only search for the given taxonomy within the post type, custom or not? And also being able to do this, but still search on the front-end, and get results for everything at once?

My function for the search is as follows:

function ScanWPostFilter($query) {
  if ($query->is_search) {
      $query->set('post_type', array('post','product','recipe', 'page'));
      $query->set('orderby', array('relevance' => 'DESC', 'type' => 'ASC'));
  }
  return $query;
}
add_filter('pre_get_posts','ScanWPostFilter');

2

Answers


  1. To restrict the search to a specific taxonomy within the post type in the backend, you can modify the ScanWPostFilter function as follows:

    function ScanWPostFilter($query) {
        if ($query->is_search && !is_admin()) {
            $tax_query = array(
                array(
                    'taxonomy' => 'your_taxonomy', // Replace with your actual taxonomy slug
                    'field' => 'slug',
                    'terms' => $query->query_vars['s']
                )
            );
            $query->set('tax_query', $tax_query);
        }
        return $query;
    }
    add_filter('pre_get_posts','ScanWPostFilter');
    

    Replace 'your_taxonomy' with the actual taxonomy slug you want to search within.

    Login or Signup to reply.
  2. You could do something like this

    function ScanWPostFilter($query) {
      if ($query->is_search) {
          $query->set('post_type', array('post','product','recipe', 'page'));
          $query->set('orderby', array('relevance' => 'DESC', 'type' => 'ASC'));
          $taxquery = array(
             'relation' => 'OR',
              array(
                   'taxonomy' => 'product_cat',
                   'field' => 'term_id',
                   'terms' => array( 1, 2, 3 ),
                   'operator'=> 'IN'
              ),
              array(
                   'taxonomy' => 'category',
                   'field' => 'term_id',
                   'terms' => array( 1, 2, 3 ),
                   'operator'=> 'IN'
              )
         );
         $query->set( 'tax_query', $taxquery );
      }
      return $query;
    }
    add_filter('pre_get_posts','ScanWPostFilter');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search