根据 Woocommerce 中的特定产品属性值更改购物车商品价格

Change cart item prices based on specific product attribute value in Woocommerce

我正在尝试使用以下功能更改购物车中的产品价格:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10);
function add_custom_price( $cart_obj ) {
    foreach ( $cart_obj->get_cart() as $key => $value ) {
        $item_data = $value['data'];
        $price0 = $item_data->get_attributes('per_one_price');
        $price  = (int) $price0;
        $value['data']->set_price( $num_int );
    }
}

但是对于我设置为 per_one_price 属性的产品属性值的任何数字,我得到购物车价格中的数字 1。

Update - There is 2 little mistakes:

  • Replace get_attributes() by get_attribute() (singular).
  • Replace 'per_one_price' by 'Per one price' (or 'per-one-price' as blank spaces are replaced by dashes)

所以请尝试以下操作:

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

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

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // get attibute value
        $new_price = $cart_item['data']->get_attribute('per-one-price');

        if( ! empty( $new_price ) ){
            // Set the new price
            $cart_item['data']->set_price( $new_price );
        }
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。经过测试并有效。


创建"Per one price"产品属性:

商品价格设置查看:

产品中设置的产品属性及其值:

此产品的购物车页面视图: