Skip to content

Instantly share code, notes, and snippets.

@jessepearson
Last active December 28, 2023 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessepearson/dcf49d766cd1647465655fe9a14e51f2 to your computer and use it in GitHub Desktop.
Save jessepearson/dcf49d766cd1647465655fe9a14e51f2 to your computer and use it in GitHub Desktop.
Exclude category or tag from related products in WooCommerce
<?php // do not copy this line
/**
* Both functions below work the same, they just apply to categories and tags respectively.
* They exclude the defined IDs from being included in related products in WooCommerce.
*
* Note: The results are initially cached, so add this and then clear transients before saying it doesn't work.
*
* @link https://gist.github.com/jessepearson/dcf49d766cd1647465655fe9a14e51f2
* @param [array] $categories/$tags The array of categories or tags that are being used for related products.
* @return [array] The filtered array of results.
*/
function jp_exclude_categories_from_related( $categories ) {
// Define your category IDs you'd like to have excluded.
$exclude_cats = array( 100, 101, 102 );
foreach( $categories as $index => $cat ){
if( in_array( $cat, $exclude_cats ) ){
unset( $categories[ $index ] );
}
}
return $categories;
}
add_filter( 'woocommerce_get_related_product_cat_terms', 'jp_exclude_categories_from_related' );
function jp_exclude_tags_from_related( $tags ) {
// Define your tag IDs you'd like to have excluded.
$exclude_tags = array( 100, 101, 102 );
foreach( $tags as $index => $tag ){
if( in_array( $tag, $exclude_tags ) ){
unset( $tags[ $index ] );
}
}
return $tags;
}
add_filter( 'woocommerce_get_related_product_tag_terms', 'jp_exclude_tags_from_related' );
@sknichols
Copy link

The tag ID! I found a similar snippet but it was including slugs as a string in the exclude_tags array. This worked for me on Woo 4.6. Thank you!

@braddalton
Copy link

Doesn't work for me when i exclude by cat ID and the product also has one or more tags. When i remove the tags, it works.

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