这是我的搜索表单。我使用woocommerce。并且需要按关键字和类别搜索产品。
<form role="search" method="get" action="<?php echo get_permalink( woocommerce_get_page_id( 'shop' ) ); ?>">
<div class="search-bar-select hidden-sm hidden-xs">
<span></span>
<i></i>
<select name="category">
<option value="" class="search-bar-select-text"><?php _e('[:ru]Все категории[:ro]Toate categoriile') ?></option>
<?php foreach(woo_category_list(FALSE) as $category) { ?>
<option value="<?php echo $category->slug; ?>"><?php echo $category->cat_name; ?></option>
<?php } ?>
</select>
</div>
<div class="search-bar-input">
<input type="text" name="s" value="<?php echo get_search_query(); ?>" placeholder="<?php _e('[:ru]Поиск по сайту ...[:ro]Căutare pe site') ?>" />
</div>
<input type="hidden" name="post_type" value="product" />
<div class="search-bar-btn">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
这是我的过滤器代码
function advanced_search_query($query)
{
if($query->is_search()) {
// category terms search.
if (isset($_GET['category']) && !empty($_GET['category'])) {
$query->set('tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array($_GET['category']) )
));
}
return $query;
}
}
add_action('pre_get_posts', 'advanced_search_query', 1000);
但wordpress按关键字显示所有类别的所有产品。 什么是错的?
答案 0 :(得分:0)
你可以用<挂钩来做。
只需将类别输入的“名称”属性更改为“ product_cat ”。
所以删除钩子并改变你的代码:
<form role="search" method="get" action="<?php echo get_permalink( woocommerce_get_page_id( 'shop' ) ); ?>">
<div class="search-bar-select hidden-sm hidden-xs">
<strong textspan></span>
<i></i>
<select name="product_cat">
<option value="" class="search-bar-select-text"><?php _e('[:ru]Все категории[:ro]Toate categoriile') ?></option>
<?php foreach(woo_category_list(FALSE) as $category) { ?>
<option value="<?php echo $category->slug; ?>"><?php echo $category->cat_name; ?></option>
<?php } ?>
</select>
</div>
<div class="search-bar-input">
<input type="text" name="s" value="<?php echo get_search_query(); ?>" placeholder="<?php _e('[:ru]Поиск по сайту ...[:ro]Căutare pe site') ?>" />
</div>
<input type="hidden" name="post_type" value="product" />
<div class="search-bar-btn">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
列出下拉列表中的所有产品猫,使用此方法:
(而不是 foreach(woo_category_list(FALSE)为$ category))
<?php
$args = array(
'taxonomy' => 'product_cat',
'name' => 'product_cat',
'value_field' => 'slug',
'class' => 'something'
);
wp_dropdown_categories( $args );
?>