如何在兼容HPOS的WooCommerce中正确获取订单币种?
修复HPOS环境下WooCommerce订单币种获取问题
问题根源分析
你的代码无法获取订单实际币种,核心问题有三个:
- HPOS兼容性判断失效:启用HPOS后,订单不再是
shop_order类型的文章(Post),原代码中get_post_type($_GET['post']) === 'shop_order'的条件永远不成立,导致逻辑直接跳转到默认币种。 - 参数传递错误:
getAdminOrderCurrency方法声明了接收$order参数,但调用时未传入,内部重复获取订单的逻辑冗余且易出错。 - 订单ID获取不可靠:依赖
get_the_ID()或全局$post对象在HPOS环境下无法正确定位订单,因为HPOS使用独立的订单数据表,不再依赖文章系统。
修复后的代码
use Automattic\WooCommerce\Utilities\OrderUtil; public static function getDefaultLabels(): array { $defaultCurrency = self::shouldUseAdminOrderCurrency() ? self::getAdminOrderCurrency() : get_woocommerce_currency(); $currencyInfo = self::getCurrencyInfo($defaultCurrency); $dollarLabel = $currencyInfo['dollar_label'] ?? 'Dollar'; $centLabel = $currencyInfo['cent_label'] ?? 'Cent'; return [$dollarLabel, $centLabel]; } private static function shouldUseAdminOrderCurrency(): bool { if ( ! is_admin() ) { return false; } // 传统模式:检查是否为shop_order编辑页 if ( isset($_GET['post']) && get_post_type($_GET['post']) === 'shop_order' ) { return true; } // HPOS模式:检查是否为WooCommerce订单编辑页 if ( isset($_GET['page'], $_GET['action'], $_GET['id']) && $_GET['page'] === 'wc-orders' && $_GET['action'] === 'edit' ) { return true; } return false; } private static function getAdminOrderCurrency(): string { $order_id = 0; // 从URL参数获取订单ID,兼容两种存储模式 if ( isset($_GET['post']) ) { $order_id = absint($_GET['post']); } elseif ( isset($_GET['id']) ) { $order_id = absint($_GET['id']); } if ( $order_id ) { // wc_get_order已原生兼容HPOS和传统存储,无需分开处理 $order = wc_get_order($order_id); if ( $order ) { return $order->get_currency(); } } // 兜底返回默认币种 return get_woocommerce_currency(); } private static function getCurrencyInfo(string $currencyCode): array { $currencyData = self::getCurrencyData(); return $currencyData[$currencyCode] ?? []; } private static function getCurrencyData(): array { return [ 'USD' => ['dollar_label' => 'Dollar', 'cent_label' => 'Cent'], // 可按需添加更多币种配置 ]; }
关键修改说明
- 兼容HPOS的页面判断:新增HPOS订单编辑页的URL参数判断,确保两种存储模式下都能识别订单编辑场景。
- 统一订单ID获取逻辑:从URL参数中直接提取订单ID,不再依赖全局
$post或get_the_ID(),避免HPOS环境下的ID获取失败。 - 简化订单获取逻辑:
wc_get_order()函数已原生支持HPOS和传统存储模式,无需单独做分支判断,减少冗余代码。 - 修复参数传递问题:移除
getAdminOrderCurrency方法的无用参数,直接内部获取订单ID,避免调用时的参数缺失问题。
内容的提问来源于stack exchange,提问作者Ahmed Imran
相关产品推荐
相关产品推荐

