A
A
Andrey2016-03-06 13:23:29
WordPress
Andrey, 2016-03-06 13:23:29

Search only within a given Wordpress taxonomy?

The site has two custom taxonomies: movies and books. Now I use the standard wordpress search form with the Ajax search plugin (like a live search):

<form method="get" class="searchform" action="<?php bloginfo('url'); ?>" >
  <input type="text" class="place s" name="s" id='my-s' autocomplete="off" placeholder="Поиск" />
  <input type="image" src="search.png" class="submit-s" name="submit" value="<?php _e('Найти'); ?>" />
</form>

I want to make two search forms: one searches only on the Movies taxonomy and is shown only where Movies are displayed, the other searches on the Books taxonomy and is shown only where Books are displayed.
Tell me, please:
1. How to attach a restriction to the above form - search only for a given taxonomy: taxonomy=films or taxonomy=books
2. How to make an exception for a certain taxonomy in the above form. For example, search everywhere except taxonomy=films

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor Vorotnev, 2016-03-06
@HeadOnFire

The form proposed by Roman Crabbs only passes the required parameter through the hidden field. You also need to modify the query itself:

function search_filter( $query ) {
  // Берем название таксономии из скрытого поля
  $taxonomy = sanitize_text_field( $_GET['taxonomy'] );
  // Получаем ID всех терминов в заданной таксономи
  $terms = get_terms( $taxonomy, array(
    'fields' => 'ids'
  ) );
  // Изолируем нужный запрос
  if ( !is_admin() && $query->is_main_query() && $query->is_search ) {
      // Формируем массив параметров подзапроса по таксономии
      $tax_query = array(
        array(
          'taxonomy' => $taxonomy,
          'field' => 'id',
          'terms' => $terms,
          'operator'  => 'IN'
        ),
      );
      // Передаем параметры подзапроса в основной запрос
      $query->set( 'tax_query', $tax_query );
  }
}
add_action( 'pre_get_posts', 'search_filter' );

If I understand correctly, you want the word entered in the search to be regarded as a taxonomy term, and as a result, posts with this term in this taxonomy are displayed? Then you need to pass tax_query to the parameters in the code above .

M
Mr Crabbz, 2016-03-06
@Punkie

<form method="get" class="searchform" action="<?php bloginfo('url'); ?>" >
  <input type="text" class="place s" name="s" id='my-s' autocomplete="off" placeholder="Поиск" />
  <input type="image" src="search.png" class="submit-s" name="submit" value="<?php _e('Найти'); ?>" />
  <input type="hidden" name="taxonomy" value="films" />
</form>

Try like this.

L
lakegull, 2016-03-06
@lakegull

I don’t know how you feel about installing plugins, but I can advise one that will 100% solve your problem.
codecanyon.net/item/filter-custom-fields-taxonomie...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question