在WooCommerce中更改购物车总价

DEV*_*OCB 5 php wordpress cart woocommerce hook-woocommerce

我遇到的问题是购物车总数只显示0

基本上我想要做的只是在将所有购物车商品添加到购物车小计后才接受一定金额的存款.

因此,例如,如果客户增加价值100美元的物品,他们最初只需支付10美元或小计的(10%)作为总价值.

我从这里获取代码:更改total和tax_total Woocommerce并以这种方式自定义:

add_action('woocommerce_cart_total', 'calculate_totals', 10, 1);

function calculate_totals($wc_price){
$new_total = ($wc_price*0.10);

return wc_price($new_total);
} 
Run Code Online (Sandbox Code Playgroud)

但是当启用该代码时,总金额显示为0.00.如果删除了代码,我会得到标准总数.

我也找不到列出完整api的woocommerce网站,只有与如何创建插件有关的通用文章.

任何帮助或正确方向上的一点都会很棒.

Chr*_*ina 14

这不回答这个问题.Loic的确如此.这是另一种方式来显示10%的订单项:

function prefix_add_discount_line( $cart ) {

  $discount = $cart->subtotal * 0.1;

  $cart->add_fee( __( 'Down Payment', 'yourtext-domain' ) , -$discount );

}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line' );
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 是的,收费可以是一个好的解决方案。好球 :) (2认同)
  • Cristina,带有“$woocommerce->cart”的“global $woocommerce”已经过时了。你必须直接使用 `$cart` 参数对象或 `WC()->cart`。 (2认同)

Loi*_*tec 9

自从Woocommerce 3.2+以来 它不再适用于新的Class WC_Cart_Totals...

新答案:使用Woocommerce 3.2+中的Hooks更改购物车总数


第一个woocommerce_cart_total钩子是过滤钩子,而不是动作钩子.另外,作为wc_price参数woocommerce_cart_total格式化价格,您将无法将其增加10%.这就是它返回零的原因.

在Woocommerce v3.2之前,可以直接访问某些WC_Cart属性

你最好这样使用挂钩woocommerce_calculate_totals动作钩子的自定义函数
:

// Tested and works for WooCommerce versions 2.6.x, 3.0.x and 3.1.x
add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );
function action_cart_calculate_totals( $cart_object ) {

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

    if ( !WC()->cart->is_empty() ):
        ## Displayed subtotal (+10%)
        // $cart_object->subtotal *= 1.1;

        ## Displayed TOTAL (+10%)
        // $cart_object->total *= 1.1;

        ## Displayed TOTAL CART CONTENT (+10%)
        $cart_object->cart_contents_total *= 1.1;

    endif;
}
Run Code Online (Sandbox Code Playgroud)

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

也可以在这个钩子中使用WC_cart add_fee()方法,或者像在Cristina中一样单独使用它.

  • @DEVPROCB - 每次您接受答案(并且 Loic 写出最佳答案)时,您的排名都会上升,其他人也会得到帮助。 (2认同)