# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, related-products, catalog
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-related-products-exclude/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Exclude Products or Categories From Related Products" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
