php - 更新 WooCommerce 中的购物车小计

标签 php wordpress woocommerce cart hook-woocommerce

我想更新 WooCommerce 中的购物车小计。

如何在 WooCommerce 中添加修改小计的操作?

我尝试过这段代码,但不起作用。我想将购物车小计乘以 12 并在购物车页面上显示此计算结果。

这是我的代码:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $total) {

    foreach ( $total->cart_contents as $key => $value ) {

        $modifiedtotal = $total->subtotal * 12; 
        // --------------------------------
        //how can get subtotal with multiply by 12 and it should be show on cart page.
    }
}

最佳答案

您使用的是正确的钩子(Hook),这里是 Woocommerce 版本 2.6x 到 3.0+ 的功能和测试代码,这将解决问题(相反,您可以对购物车项目进行计算,您将得到同样的东西):

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    foreach ( $cart_object->get_cart() as $cart_item ) {
        ## Price calculation ##
        $price = $cart_item['data']->price * 12;

        ## Set the price with WooCommerce 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 文件中或任何插件文件中。


Explanations:

Using a calculation based on the cart subtotal, will only display the calculation on subtotal cart line row, without updating the cart items, the cart items line subtotals, and the cart total.

您可以看到它正在尝试 WooCommerce 版本 2.6.x 和 3.0+ 的工作代码:

add_action( 'woocommerce_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    $cart_object->subtotal *= 12;
}

代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。

关于php - 更新 WooCommerce 中的购物车小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43915159/

相关文章:

php - 通过自定义前端表单设置 Woocommerce 产品标签和类别

php - woocommerce 小部件 "filter products by attribute"显示不可用的产品

php - 检查 mysqli_query 是否为空

javascript - HTML5 音频的最大套接字

html - 为什么我的 Accordion 有间隙并且有间隔,即使我把边距和填充 0px

html - 删除 Wordpress 中特色 svg img 的默认大小属性

php - 已验证的电子邮件查询

php - ajax 功能和点击功能在点击时不起作用

php - 永久链接不适用于自定义帖子和类别

php - 在结帐 WooCommerce 页面上获取购物车产品 ID,以显示产品图片