WooCommerce购物车-动态价格变量传递到自定义价格挂钩 [英] WooCommerce Cart - Dynamic Price variable pass into custom price hook

查看:85
本文介绍了WooCommerce购物车-动态价格变量传递到自定义价格挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某个变量中获取动态自定义价格,该变量要传递给购物车中 woocommerce_before_calculate_totals 钩子中的钩子函数。

I am getting the dynamic custom price in a variable that I want to pass to the hooked function in woocommerce_before_calculate_totals hook in cart. But it isn't working.

这是我的代码:

  $add=200; //I want to pass this variable in add_action hook
  add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price');
  function add_custom_total_price($cart_object) {
     global $woocommerce;
     $custom_price =$add; // This is my custom price
    foreach ( $cart_object->cart_contents as $key => $value ) {
       $value['data']->price = $custom_price;
    }
 } 

如何实现?

谢谢

推荐答案

要使其正常运行,您只需要定义 $ custom_price 变量在您的函数中是全局变量,这种方式是:

To make it work you just need to define $custom_price variables as global in your function, this way:

$custom_price = 200; 

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

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

    global $custom_price;

    foreach (  $cart_object->get_cart() as $item_values ) {
        $item_values['data']->price = $custom_price;
    }
} 

此代码已经过测试并且可以正常工作 (适用于woocommerce 2.5+和2.6+版本)

自然,此代码会在活动目录的function.php文件中显示子主题或主题。

这篇关于WooCommerce购物车-动态价格变量传递到自定义价格挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆