Sami Sami - 17 days ago 4
PHP Question

Woocommerce custom category search

I'm using the code below to search in woocommerce products and i want to be able to search by category in woocommerce.
if i disable the category section, everything is ok but if enable it, nothing will be found.
Could you help me find my mistake ?

<?php
$params = array(
'posts_per_page' => 12,
'post_type' => 'product',
'category_name' => $_GET['category'],
);

$wc_query = new WP_Query($params);
?>
<?php if ( $wc_query->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( $wc_query->have_posts() ) : $wc_query->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php elseif ( ! woocommerce_product_subcategories( array( 'before' => woocommerce_product_loop_start( false ), 'after' => woocommerce_product_loop_end( false ) ) ) ) : ?>
<?php wc_get_template( 'loop/no-products-found.php' ); ?>
<?php endif; ?>

Answer

Change 'category_name' => $_GET['category'], to 'product_cat' => $_GET['category'],

<?php
   $params = array(
          'posts_per_page' => 12,
          'post_type' => 'product',
          'product_cat' => $_GET['category'],
          's' => $_GET['s_query'] // search text
       );
      // and so on...
     ?>

Try it... It should work !