How to exclude products from a particular category in a custom WooCommerce template
  • 02 Jan, 2021
  • By Pankaj

Hey folks!

We have been working on a WooCommerce project lately and there we had to make some customised templates for the product listing page. Our client wanted to hide some products from a particular category (Let’s call that category ‘Candy Crush‘) in that custom template which is kind of an odd requirements though. After Googling for a while we found some solution from WooCommerce itself and had to make some changes to fit it into our requirements. We are publishing the codes keeping in mind that someone out there may need help regarding the same cuz I’m pretty sure we are not the first one who are facing such requirements. So here we go –

First, we need to use a custom query of course as it was a custom template. Here’s the code-


$args = array(
		'post_type' => 'product',
		'post_status' => 'publish',
		'paged' => get_query_var('paged'),
		'tax_query' => array(
			array(
				'taxonomy' => 'product_cat',
				'field' => 'slug',
				'terms' => array( 'candy-crush' ),
				'operator' => 'NOT IN'
				)
			)
);
query_posts($args);

As you can see, we are fetching all products and using get_query_var to make the default pagination work in this code. The last parameter i.e, ‘tax_query’ is helping use to exclude the Product Category ‘Candy Crush‘ within our query. Please note that we are passing the Taxonomy’s Slug not the Name. You can put multiple slugs there. Once you are done putting you query parameters, it’s time to use that old fashioned WordPress loop’s code to pull the products and display it within your custom WooCommerce template. Here’s an example –


$args = array(
		'post_type' => 'product',
		'post_status' => 'publish',
		'paged' => get_query_var('paged'),
		'tax_query' => array(
			array(
				'taxonomy' => 'product_cat',
				'field' => 'slug',
				'terms' => array( 'candy-crush' ),
				'operator' => 'NOT IN'
				)
			)
);
query_posts($args);
<?php if (have_posts()) : while(have_posts()) : the_post();?>
	<div id="wooProd">
	<a href="<?php the_permalink();?>"><h2><?php the_title();?></h2></a>
	<a href="<?php the_permalink();?>"><?php the_post_thumbnail();?></a>
	</div>
<?php include('woocommerce/loop/pagination.php');//To Include the Default WooCommerce Pagination ?>

I hope you found this post helpful. Please let us know if you have any queries, we will be happy to help! 🙂