Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.