限制要添加到购物车的子类别产品

问题描述 投票:0回答:0

请帮我解决这个问题

我有一个“类别-a”,然后是“子类别-b”,如果没有来自主要“类别-”的产品,我希望“子类别-b”下的所有产品都受到限制或无法添加到购物车a" 然后无论是否存在“category-a”,其余产品都可以添加到购物车。

我试过这个代码,但是即使主“类别-a”不存在,“子类别-b”的产品仍然可以添加到购物车。

// Define the specific main category and sub-category slugs
$specific_main_cat_slug = 'category-a';
$specific_sub_cat_slug = 'sub-category-b';

// Add a filter to check if specific sub-category products can be added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'restrict_specific_sub_category_add_to_cart', 10, 3 );
function restrict_specific_sub_category_add_to_cart( $passed, $product_id, $quantity ) {
    // Get the product's category terms
    $terms = get_the_terms( $product_id, 'product_cat' );

    // Check if the product belongs to the specific sub-category
    $specific_sub_cat_found = false;
    if ( $terms && ! is_wp_error( $terms ) ) {
        foreach ( $terms as $term ) {
            if ( $term->slug === $specific_sub_cat_slug ) {
                $specific_sub_cat_found = true;
                break;
            }
        }
    }

    // Check if the specific sub-category is in the cart
    $specific_main_cat_found = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $cart_product_id = $cart_item['product_id'];
        $cart_terms = get_the_terms( $cart_product_id, 'product_cat' );

        // Check if the product in the cart belongs to the specific main category
        if ( $cart_terms && ! is_wp_error( $cart_terms ) ) {
            foreach ( $cart_terms as $cart_term ) {
                if ( $cart_term->slug === $specific_main_cat_slug ) {
                    $specific_main_cat_found = true;
                    break;
                }
            }
        }
    }

    // If the specific main category is not found in the cart but the product being added is a specific sub-category product
    // prevent the add to cart action
    if ( ! $specific_main_cat_found && $specific_sub_cat_found ) {
        wc_add_notice( 'You must add a product from the specific main category before adding a product from the specific sub-category.', 'error' );
        return false;
    }

    // Allow the add to cart action for all other cases
    return $passed;
}

woocommerce product hook-woocommerce restriction
© www.soinside.com 2019 - 2024. All rights reserved.