仅限制 WooCommerce 中某些产品的购买

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

我需要类似于下面的东西,但我不需要仓库选项。 我只需要阻止少数产品被多次购买,其他产品可以被多次购买。 如何仅包含那些产品 ID?

add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 4 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null ) {
    $product    = wc_get_product( $product_id );
    $warehouse  = $product->get_attribute('pa_warehouse');
    $cart_items = WC()->cart->get_cart();

    if ( WC()->cart->is_empty() ) {
        return $passed;
    }
    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $values ) {
        // Check if the warehouse is different
        if ( $warehouse !== $values['data']->get_attribute('pa_warehouse') ) {
            wc_add_notice( __( 'This product cannot be purchased because...', 'woocommerce' ), 'error' );
            return false;
        }
    }
    return $passed;
}

该代码有效,但我只需要它用于一些产品 ID,但我不知道如何

php wordpress woocommerce product cart
2个回答
0
投票

据我了解,你可以试试这个

add_filter( 'woocommerce_add_to_cart_validation', 
'filter_add_to_cart_validation', 10, 4 );

function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null ) {
// Define an array of product IDs that should be restricted
$restricted_product_ids = array( 1, 2, 3 );

// Check if the current product ID is in the restricted list
if ( in_array( $product_id, $restricted_product_ids ) ) {
    $cart_items = WC()->cart->get_cart();

    foreach ( $cart_items as $cart_item_key => $cart_item ) {
        // Check if the product ID matches one of the restricted products
        if ( in_array( $cart_item['product_id'], $restricted_product_ids ) ) {
            wc_add_notice( __( 'This product cannot be purchased more than once.', 'woocommerce' ), 'error' );
            return false; // Block the addition
        }
    }
}

return $passed; // Allow the addition to cart for other products
}

`


0
投票
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 4 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null ) {
// Array of product IDs that should be limited to one purchase
$restricted_product_ids = array( 123, 456, 789 );

// Check if the product is in the restricted list
if ( in_array( $product_id, $restricted_product_ids ) ) {
    // Check if the product is already in the cart
    if ( wc_customer_bought_product( '', get_current_user_id(), $product_id ) ) {
        wc_add_notice( __( 'This product can only be purchased once.', 'woocommerce' ), 'error' );
        return false;
    }
}
return $passed;
}
© www.soinside.com 2019 - 2024. All rights reserved.