【问题标题】:Change original price in cart for WooCommerce product variation更改购物车中 WooCommerce 产品变体的原始价格
【发布时间】:2017-10-12 02:31:23
【问题描述】:

我尝试使用它来更改购物车中的原始价格,但没有骰子。我认为它不起作用,因为我使用的产品是可变产品。产品 ID 为 141,变体 ID 为 142。

function sv_change_product_price_cart( $price, $cart_item, $cart_item_key ) {
    if ( 142 === $cart_item['product_id'] ) {
        $price = '$50.00 per Unit<br>(7-8 skewers per Unit)';
    }
    return $price;
}
add_filter( 'woocommerce_cart_item_price', 'sv_change_product_price_cart', 10, 3 );

如何让它发挥作用

谢谢

【问题讨论】:

    标签: php wordpress woocommerce cart product


    【解决方案1】:

    您应该需要将 $cart_item['product_id'] 替换为 $cart_item['variation_id'] 以使其适用于您条件下的产品变化。

    这个函数只会改变显示,不会改变计算:

    // Changing the displayed price (with custom label)
    add_filter( 'woocommerce_cart_item_price', 'sv_display_product_price_cart', 10, 3 );
    function sv_display_product_price_cart( $price, $cart_item, $cart_item_key ) {
        if ( 142 == $cart_item['variation_id'] ) {
            // Displaying price with label
            $price = '$50.00 per Unit<br>(7-8 skewers per Unit)';
        }
        return $price;
    }
    

    这是一个钩子函数,它将根据您的价格更改购物车计算:

    // Changing the price (for cart calculation)
    add_action( 'woocommerce_before_calculate_totals', 'sv_change_product_price_cart', 10, 1 );
    function sv_change_product_price_cart( $cart ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        foreach ( $cart->get_cart() as $cart_item ) {
            if ( 142 == $cart_item['variation_id'] ){
                // Set your price
                $price = 50;
    
                // WooCommerce versions compatibility
                if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
                    $cart_item['data']->price = $price; // Before WC 3.0
                } else {
                    $cart_item['data']->set_price( $price ); // WC 3.0+
                }
            }
        }
    }
    

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

    所以你会得到:

    此代码在 Woocommerce 版本 2.6.x 和 3.0+ 上经过测试广告作品

    【讨论】:

      猜你喜欢
      • 2017-04-06
      • 2017-08-07
      • 2021-07-25
      • 2017-12-10
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2018-02-17
      • 2023-03-31
      相关资源
      最近更新 更多