wordpress 限制Woocommerce购物车中免费产品的最大数量

91zkwejq  于 11个月前  发布在  WordPress
关注(0)|答案(2)|浏览(170)

我的客户要求能够在他们的Woocommerce在线商店提供他们的可变产品的免费样品,每个独特的产品样品最多1个,他们订单上的任何样品5个。
我已经实现了这一点的一部分,通过添加一个额外的“免费样品”的变化,每个产品,然后使用一个免费的最小/最大数量插件,以限制每个人的免费样品的数量为1个订单,请参阅以下截图:
https://ibb.co/f0Wd7XChttps://ibb.co/8DrsZZj的数据库
到目前为止,我还没有建立一个方法来限制最大数量的任何组合的“免费样品”的变化,虽然5。唯一的办法,我可以看到的是限制免费产品的总数(即价格= 0英镑)每一个订单减为5,或者可替换地,通过将特定的装运类别分配给每个变化,(即“免费样品”),然后以某种方式将每个订单中分配给此装运类别的产品数量限制为5。这可能吗?
干杯,
M.

lnvxswe2

lnvxswe21#

Woocommerce有验证钩子,你可以使用。
第一个是当我们添加到我们的购物车

function add_to_cart_free_samples($valid, $product_id, $quantity) {
    $max_allowed = 5;
    $current_cart_count = WC()->cart->get_cart_contents_count();
    foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
        // Here change attribute group if needed - currently assigned to default size attribute
        $variation = $cart_item['variation']['attribute_pa_size'];
    }
    if( ( $current_cart_count > $max_allowed || $current_cart_count + $quantity > $max_allowed ) && $variation === 'free-sample' && $valid ){
        wc_add_notice( sprintf( __( 'Whoa hold up. You can only have %d items in your cart', 'your-textdomain' ), $max_allowed ), 'error' );
        $valid = false;
    }

    return $valid;
}

add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_free_samples', 10, 3 );

字符串
第二个是当我们在购物车页面上更新购物车时。

function update_add_to_cart_free_samples( $passed, $cart_item_key, $values, $updated_quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $original_quantity = $values['quantity'];
    $max_allowed = 5;
    $total_count = $cart_items_count - $original_quantity + $updated_quantity;
    foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
        // Here change attribute group if needed - currently assigned to default size attribute
        $variation = $cart_item['variation']['attribute_pa_size'];
    }
    if( $cart_items_count > $max_allowed && $variation === 'free-sample' ){
        $passed = false;
        wc_add_notice( sprintf( __( 'Whoa hold up. You can only have %d items in your cart', 'your-textdomain' ), $max_allowed ), 'error' );
    }
    return $passed;
}
add_filter( 'woocommerce_update_cart_validation', 'update_add_to_cart_free_samples', 10, 4 );


在$cart_item中,您可以调试并查看购物车中当前产品的所有信息。从那里,您可以根据您想要的运输或属性或价格或w/e添加条件。

1mrurvl1

1mrurvl12#

这是你正在寻找的(不需要插件):
在主题的function.php中添加以下内容:

/*----------------------------------------------------------
 * Adds custom field to the inventory tab in the product data meta box
 * ---------------------------------------------------------- */
function action_woocommerce_product_options_stock_status() {        
    woocommerce_wp_text_input(
        array(
            'id'                => '_max_qty',
            'placeholder'       => __( 'Set the bundle maximum to at least 2 items or leave blank', 'woocommerce' ),
            'label'             => __( 'Maximum Bundle', 'woocommerce' ),
            'desc_tip'          => true,
            'description'       => __( 'Limits the maximum amount of product bundles your customer can order', 'woocommerce' ),
            'type'              => 'number',
            'custom_attributes' => array(
                'step' => 'any',
            ),
        )
    );
}
add_action( 'woocommerce_product_options_stock_status', 'action_woocommerce_product_options_stock_status', 10, 0 );

/* ----------------------------------------------------------
 * Save custom field to the inventory tab in the product data meta box
 * ---------------------------------------------------------- */
function action_woocommerce_admin_process_product_object( $product ) {
    // Isset
    if ( isset( $_POST['_max_qty'] ) ) {        
        // Update
        $product->update_meta_data( '_max_qty', sanitize_text_field( $_POST['_max_qty'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );

function get_cart_quantity_variable_product( $child_ids ) { 
    // Get cart items quantities
    $cart_item_quantities = WC()->cart->get_cart_item_quantities();
    
    // Counter
    $qty = 0;
    
    // Loop through the childIDs
    foreach ( $child_ids as $child_id ) {
        // Checks if the given key or index exists in the array
        if ( array_key_exists( $child_id, $cart_item_quantities ) ) {
            // Addition
            $qty += $cart_item_quantities[$child_id];
        }
    }
    
    return $qty;
}

function action_woocommerce_check_cart_items() {    
    // Will increment
    $i = 0;
    
    // Will hold information about products that have not met the minimum order quantity
    $bad_products = array();
    
    // Will hold information about which product ID has already been checked so that this does not happen twice (especially applies to products with variants)
    $already_checked = array();
    
    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // Get IDs
        $product_id = $cart_item['product_id'];
        $variation_id = $cart_item['variation_id'];
        
        // NOT in array, already checked? Continue
        if ( ! in_array( $product_id, $already_checked ) ) {            
            // Push to array
            $already_checked[] = $product_id;
            
            // Get the parent variable product for product variation items
            $product = $variation_id > 0 ? wc_get_product( $product_id ) : $cart_item['data'];
            
            // Get meta
            $max_qty = $product->get_meta( '_max_qty', true );
            
            // NOT empty & minimum quantity is lesser than or equal to 5 (1 never needs to be checked)
            if ( ! empty( $max_qty ) && $max_qty <= 5 ) {               
                // Get current quantity in cart
                $cart_qty = $cart_item['quantity'];
                
                // Product type = variable & cart quantity is less than the maximum quantity
                if ( $product->get_type() == 'variable' && ( $cart_qty < $max_qty ) ) {                 
                    // Get childIDs in an array
                    $child_ids = $product->get_children();

                    // Call function, get total quantity in cart for a variable product
                    $cart_qty = get_cart_quantity_variable_product( $child_ids );               
                }
                
                // Cart quantity is less than the maximum quantity
                if ( $cart_qty > $max_qty ) {
                    // The product ID
                    $bad_products[$i]['product_id'] = $product_id;
                    
                    // The variation ID (optional)
                    //$bad_products[$i]['variation_id'] = $variation_id;                    
                    
                    // The Product quantity already in the cart for this product
                    $bad_products[$i]['in_cart'] = $cart_qty;
                    
                    // Get the maximum required for this product
                    $bad_products[$i]['max_req'] = $max_qty;
                    
                    // Increment $i
                    $i++;
                }
            }
        }
    }
    
    // Time to build our error message to inform the customer, about the maximum quantity per order.
    if ( is_array( $bad_products) && count( $bad_products ) < 5 ) { 
        // Clear all other notices          
        wc_clear_notices();
        
        foreach( $bad_products as $bad_product ) {
            // Displaying an error notice
            wc_add_notice( sprintf(
                __( '%s has a maximum quantity of %d. You currently have %d in cart', 'woocommerce' ),
                get_the_title( $bad_product['product_id'] ),
                $bad_product['max_req'],
                $bad_product['in_cart'],
            ), 'error' );
        }
        
        // Optional: remove proceed to checkout button
        remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
    }
}   
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );

字符串
感谢7uc1f3r在Force minimum order quantity for specific products including variations on WooCommerce cart page上提供的解决方案
我只是添加和更改了一些代码,以适应最大的捆绑包。这适用于免费样品的东西,你也可以使用它的任何产品的店主想要限制到一定数量的捆绑包,因为这不是硬编码的限制,以某种产品。
下面是一个工作的例子:


的数据


相关问题