php - 在 Woocommerce 3 中更改购物车商品价格

标签 php wordpress woocommerce cart product

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

    add_action( 'woocommerce_before_shipping_calculator', 'add_custom_price' 
     );
      function add_custom_price( $cart_object ) {
         foreach ( $cart_object->cart_contents as $key => $value ) {
         $value['data']->price = 400;
        } 
     }

它在 WooCommerce 2.6.x 版中工作正常,但在 3.0+ 版中不再工作

如何让它在 WooCommerce 版本 3.0+ 中工作?

谢谢。

最佳答案

2021 年更新(处理迷你购物车定制商品价格)

对于 WooCommerce 3.0+ 版,您需要:

代码如下:

// Set custom cart item price
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
function add_custom_price( $cart ) {
    // This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example | optional)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $cart_item['data']->set_price( 40 );
    }
}

对于迷你购物车(更新):

// Mini cart: Display custom price 
add_filter( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 3 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {

    if( isset( $cart_item['custom_price'] ) ) {
        $args = array( 'price' => 40 );

        if ( WC()->cart->display_prices_including_tax() ) {
            $product_price = wc_get_price_including_tax( $cart_item['data'], $args );
        } else {
            $product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
        }
        return wc_price( $product_price );
    }
    return $price_html;
}

代码位于您的事件子主题(或事件主题)的 functions.php 文件中。

此代码已经过测试并有效(仍然适用于 WooCommerce 5.1.x)

Note: you can increase the hook priority from 20 to 1000 (or even 2000) when using some few specific plugins or others customizations.

相关:

关于php - 在 Woocommerce 3 中更改购物车商品价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43324605/

相关文章:

apache - 如何在 ubuntu 上跟踪 php5-fpm umask 设置的来源

php - 在开源 php 照片库和-或 cms 之间进行选择

php - get_user_by() 在 wordpress 中未定义

php - 将完整的 wordpress 站点转换为 HTTPS

php - 是否可以在不使用 WooCommerce 重定向到 PayPal 网站的情况下进行 PayPal 付款?

php - 将具有匹配 ID 的表中的数据获取到 Laravel 中的数据透视表

php - 多次插入后更新特定记录 - 可能使用last_insert_id()

PHP和MySQL使用SPATIAL扩展获取n个最近点

css - Woocommerce 产品页面空白?

php - 如何从它的 Slug 中获取 WooCommerce 产品 ID?