首页 文章

如何覆盖WooCommerce购物车中的可变价格?

提问于
浏览
0

我试图找到改变/覆盖变化产品的购物车价格的解决方案 . 例如,我有一个可变产品作为颜色与不同的变体,如红色衬衫,绿色衬衫和蓝色衬衫 . Variant Red Shirt现在购物车中所以我想改变购物车中的红色衬衫变种价格 . 但我不知道如何覆盖变种价格 .

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value['data']->price = $custom_price;
    }
}

我尝试了上面的代码,它只适用于简单的产品,不适用于变体产品 . 任何人都可以给我一个改变WooCommerce购物车页面变种价格的建议吗?

3 回答

  • 0
    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    
    function add_custom_price( $cart_object ) {
        $custom_price = 10; // This will be your custome price  
        $target_product_id = 598;
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if ( $value['product_id'] == $target_product_id ) {
                $value['data']->price = $custom_price;
            }
            /*
            // If your target product is a variation
            if ( $value['variation_id'] == $target_product_id ) {
                $value['data']->price = $custom_price;
            }
            */
        }
    }
    

    在任何地方添加此代码,并确保此代码始终可执行 .

    添加此代码后,您将致电:

    global $woocommerce; 
    $woocommerce->cart->add_to_cart(598);
    
  • 1

    一个老问题,但我一直在看自己,所以以为我会添加我的发现,万一其他人正在努力:

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    
    function add_custom_price( $cart_object ) {
    
        $custom_price = 199;
        $target_product_id = 123;
    
        foreach ( $cart_object->cart_contents as $key => $value ) {
    
            if ( ($value['data']->is_type('simple') && $value['product_id'] == $target_product_id) 
              || ($value['data']->is_type('variable') && $value['variation_id'] == $target_product_id) ) {
    
                $value['data']->set_price( $custom_price );
    
            }
    
        }
    
    }
    
  • 1

    您可能需要为其添加费用; https://gist.github.com/kloon/7906768

相关问题