Exclude Products or Categories From Related Products
Stops chosen products or whole categories, such as gift cards, samples or spare parts, from appearing in the related products section.
Opens WPIDE on
Code
$wpide_related_exclude = array(
'products' => array(), // Product IDs.
'categories' => array( 'gift-cards', 'parts' ), // Category slugs.
);
add_filter( 'woocommerce_related_products', function ( $ids ) use ( $wpide_related_exclude ) {
return array_values( array_filter( (array) $ids, function ( $id ) use ( $wpide_related_exclude ) {
if ( in_array( (int) $id, array_map( 'intval', $wpide_related_exclude['products'] ), true ) ) {
return false;
}
return ! ( $wpide_related_exclude['categories'] && has_term( $wpide_related_exclude['categories'], 'product_cat', $id ) );
} ) );
}, 20 );
Notes
WooCommerce caches related products, so changes can take a little while to show everywhere.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.