Skip to content

Instantly share code, notes, and snippets.

@jameskoster
Forked from mikejolley/functions.php
Last active August 31, 2021 14:18
Show Gist options
  • Save jameskoster/4160591 to your computer and use it in GitHub Desktop.
Save jameskoster/4160591 to your computer and use it in GitHub Desktop.
WooCommerce - Exclude products from a particular category on the shop page
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'knives' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
@nocbmi
Copy link

nocbmi commented Apr 20, 2017

Hi, thanks for this post, but i have a doubt and maybe is not for this post but is so close of what i need, i don´t have any experience working with woocommerce so… my products are related by tags and i have in my file function.php this code (
add_filter(‘woocommerce_product_related_posts_relate_by_category’, function() {return false;}); ) and show up 4 products that have the same tag but... i want to try is this... don´t show up the products of the same category, i don´t know if exist a filter or a function that exclud products of the same category from related products, thanks for your help and attention. Example: i have 10 products with the tag "art" and of those 10 products, 5 belong the category "paper", 2 belong the category "machine" and 3 belong the category "pencil"... when i enter in a product like a "paper" show up in related products, (paper + machine + paper + pencil) and this is random, but i don't want to in related products show any of this products that have the same category i mean i don't want to show products of the category "paper", and have to do the same when you enter in a product like a machine, don't show in related products any product with the same category.

@interiorhacker
Copy link

Hey all, I'm looking to use something sort of like this. Does anyone know of a way to exclude a product from a shortcodes results? Like with exclude_category="" but instead exclude_sku=""?

@Joyen12
Copy link

Joyen12 commented Jul 15, 2019

@interiorhacker Did you find an answer to your problem ?
I have the exact same problem and I've been looking at this for days...:(

I am desperate to find a solution so I write here hoping someone get a solution for this.

Thanks a lot

@kelvinramirez
Copy link

It works good, but I cant see the products of the excluded category in the back end in the list of all products, is there a way to fix it? thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment