Home / eCommerce / Exclude Specific Products from Parent Category
Duplicate Snippet

Embed Snippet on Your Site

Exclude Specific Products from Parent Category

Code Preview
php
<?php
/**
 * Exclude specific products from appearing in their parent category.
 */
add_action('woocommerce_product_query', 'exclude_specific_products_from_parent_category');
function exclude_specific_products_from_parent_category($q) {
    // Only apply this on the parent category archive page
    if (!is_product_category('telt-og-pavilloner')) { // Replace with your parent category slug
        return;
    }
    // Define the product IDs or slugs to exclude
    $excluded_product_slugs = array(
        'lyskaede-10-meter-varmhvid',
        'lyskaede-20-meter-varmhvid'
    );
    // Convert slugs to post IDs for the query
    $excluded_product_ids = array();
    foreach ($excluded_product_slugs as $slug) {
        $product = get_page_by_path($slug, OBJECT, 'product');
        if ($product) {
            $excluded_product_ids[] = $product->ID;
        }
    }
    // Exclude the products from the query
    if (!empty($excluded_product_ids)) {
        $q->set('post__not_in', $excluded_product_ids);
    }
}

Comments

Add a Comment