S
S
SmartBalance2016-02-04 18:34:02
PHP
SmartBalance, 2016-02-04 18:34:02

Searching for products in the current WooCommerce category?

It is necessary that the search for goods takes place exactly according to the category in which the person is located. example:
All categories(to search for all categories) -> Honda(search only by category) -> CBR1000RR 08-11(search only by category)

Has anyone encountered this problem or can help figure it out?
Created an additional field in the WooCommerce search form:

<input type="hidden" name="product_cat" value="???" />

But I don’t know how to determine the current category in order to pass this parameter to value.
Not strong in php, but this code doesn't work for me:
<?php global $product; //Если не объявлен ранее. Не уверен в необходимости.
global $post;
$categories = get_the_terms( $post->ID, 'product_cat' );
foreach ($categories as $category) {
    echo $category->slug; //Может быть в нескольких категориях
} ?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mr Crabbz, 2016-02-04
@Punkie

<?php
global $wp_query;
$current_cat_id = $wp_query->get_queried_object()->term_id;
?>
<input type="hidden" name="product_cat" value="<?=$current_cat_id?>" />

S
SmartBalance, 2016-02-04
@SmartBalance

Thanks, but your solution only displays the category name on the category pages, and I also need it on the product page. I don't understand why. How to fix it, dear experts?

<?php
global $wp_query;
$current_cat_name = $wp_query->get_queried_object()->slug;
if (is_product()) {
  echo '<input type="hidden" name="product_cat" value="'. $current_cat_name .'" />';
} elseif (is_product_category()) {
  echo '<input type="hidden" name="product_cat" value="'. $current_cat_name .'" />';
} else {
  echo '';
}
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question