WC()->购物车和functions.php [英] WC()->cart and functions.php

查看:29
本文介绍了WC()->购物车和functions.php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将此代码添加到functions.php时出现此错误

I get this error when adding this code to functions.php

致命错误:在非对象上调用成员函数 calculate_totals()

这是产生错误的代码

WC()->cart->calculate_totals();
WC()->cart->calculate_shipping();
$packages = WC()->shipping->get_packages();

但是,当我将此代码放入 header.php &footer.php 没有错误并返回 $packages 数组.

However when i put this code in header.php & footer.php no error and $packages array is returned.

我该如何解决这个问题,我需要在functions.php中使用这段代码?

How do i solve this, i need this code in functions.php?

推荐答案

你可以通过简单地使用 functions.php 中的 init 钩子来做到这一点:

You can do this by simply using init hook in functions.php:

add_action( 'init', 'get_packages_custom' );

function get_packages_custom() {
   WC()->cart->calculate_totals();
   WC()->cart->calculate_shipping();
   $packages = WC()->shipping->get_packages();
}

这篇关于WC()->购物车和functions.php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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