php - Uncaught Error : Call to a member function get_shipping_packages()

标签 php wordpress woocommerce hook-woocommerce woocommerce-bookings

我正在尝试获取用户当前的送货区域,但每次尝试获取时都会收到错误

// The package. 

// Get cart shipping packages
$shipping_packages = $woocommerce->cart->get_shipping_packages();

// Get the WC_Shipping_Zones instance object for the first package
$shipping_zone = $woocommerce->wc_get_shipping_zone( reset( $shipping_packages ) );

$zone_id   = $shipping_zone->get_id(); // Get the zone ID
$zone_name = $shipping_zone->get_zone_name(); // Get the zone name

// Testing output
echo '<p>Zone id: ' . $zone_id . ' | Zone name: ' . $zone_name . '</p>';

错误信息

Error info

最佳答案

有 2 个问题:

  • $woocommerce 全局变量未定义(可以用 WC() 替换)
  • wc_get_shipping_zone() 不是 Woocommerce 方法,而是一个函数。

尝试以下方法(插件见下文):

// Get cart shipping packages
$shipping_packages = WC()->cart->get_shipping_packages();

// Get the WC_Shipping_Zones instance object for the first package
$shipping_zone = wc_get_shipping_zone( reset( $shipping_packages ) );

$zone_id       = $shipping_zone->get_id(); // Get the zone ID
$zone_name     = $shipping_zone->get_zone_name(); // Get the zone name

// Testing output
echo '<p>Zone id: ' . $zone_id . ' | Zone name: ' . $zone_name . '</p>';

应该有效


对于插件,请尝试

global $woocommerce;

// Get cart shipping packages
$shipping_packages = $woocommerce->cart->get_shipping_packages();

// Get the WC_Shipping_Zones instance object for the first package
$shipping_zone = wc_get_shipping_zone( reset( $shipping_packages ) );

$zone_id       = $shipping_zone->get_id(); // Get the zone ID
$zone_name     = $shipping_zone->get_zone_name(); // Get the zone name

关于php - Uncaught Error : Call to a member function get_shipping_packages(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66024005/

相关文章:

php - WooCommerce 通过属性查询获取产品

php - 这在 SQL 注入(inject)方面安全吗?

php - 我想将文本文件导入到 mySQL 中的表中并在 php 中显示

javascript - mailchimp 弹出表单未显示

javascript - WordPress:一页滚动 JQuery 脚本不起作用?

php - 在 Woocommerce 购物车和结帐项目中显示自定义字段的值

php - 哈希密码功能无法正常工作

php - PDO MySQL 查询独立于数据库结构

php - 使用wordpress下载文件(图片)

wordpress - 在特定时间过后自动更改 WooCommerce 订单状态?