更改woocommerce中特定产品的购物车项目数量 [英] Change the cart item quantity for specific products in woocommerce

查看:243
本文介绍了更改woocommerce中特定产品的购物车项目数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以更改某些特定产品的WooCommerce数量吗?

Can I change WooCommerce quantity in some specific product?

我尝试过:

global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    foreach($items as $item => $values) { 
        $_product = $values['data']->post; 
        echo "<b>".$_product->post_title.'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
        $price = get_post_meta($values['product_id'] , '_price', true);
        echo "  Price: ".$price."<br>";
    } 

如何在购物车中获取特定产品ID?

How to get specific product Id in cart?

推荐答案

要更改数量,请参阅该代码后面的内容。这里是您重新访问的代码:

To change quantities, see after that code. Here your revisited code:

foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { 
    $product = $cart_item['data']; // Get an instance of the WC_Product object
    echo "<b>".$product->get_title().'</b>  <br> Quantity: '.$cart_item['quantity'].'<br>'; 
    echo "  Price: ".$product->get_price()."<br>";
} 






已更新:现在要更改特定产品上的数量,您将需要使用挂在 woocommerce_before_calculate_totals 操作挂钩中的此自定义函数:


Updated: Now to change the quantity on specific products, you will need to use this custom function hooked in woocommerce_before_calculate_totals action hook:

add_action('woocommerce_before_calculate_totals', 'change_cart_item_quantities', 20, 1 );
function change_cart_item_quantities ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE below define your specific products IDs
    $specific_ids = array(37, 51);
    $new_qty = 1; // New quantity

    // Checking cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product_id = $cart_item['data']->get_id();
        // Check for specific product IDs and change quantity
        if( in_array( $product_id, $specific_ids ) && $cart_item['quantity'] != $new_qty ){
            $cart->set_quantity( $cart_item_key, $new_qty ); // Change quantity
        }
    }
}

代码进入在活动子主题(或活动主题)的function.php文件中。

Code goes in function.php file of the active child theme (or active theme).

经过测试并有效

这篇关于更改woocommerce中特定产品的购物车项目数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆