You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

functions.php中global $product为null,如何获取当前产品?

解决WooCommerce中获取当前产品为null的问题

嘿,我明白你遇到的麻烦了——直接在functions.php根级别用global $product大概率会拿到null,因为这段代码执行得太早,WooCommerce还没完成当前产品对象的初始化呢。而且你现在的代码没绑定到合适的钩子上,时机不对自然拿不到正确的产品数据。

下面是调整后的解决方案,我会一步步给你说明:

关键改进点

  • 把代码绑定到合适的WooCommerce钩子上,确保产品对象初始化后再执行
  • 用get_queried_object()可靠获取当前产品,替代直接调用全局变量
  • 增加更严谨的判断,避免非产品页面或非套装产品触发错误

修改后的完整代码

if (class_exists( 'WooCommerce' ) && class_exists('WC_Bundles')) {
    // 绑定到template_redirect钩子,确保产品对象已初始化
    add_action('template_redirect', 'adjust_bundle_display_position');
    
    function adjust_bundle_display_position() {
        // 仅在单个产品页面执行
        if (!is_product()) {
            return;
        }
        
        // 获取当前产品对象
        $product = get_queried_object();
        
        // 确保产品对象有效,且是WooCommerce产品,同时是套装产品且有捆绑项
        if (!$product || !($product instanceof WC_Product) || !method_exists($product, 'get_bundled_items') || empty($product->get_bundled_items())) {
            return;
        }
        
        // 移动产品套装到产品摘要上方
        remove_action( 'woocommerce_bundle_add_to_cart', 'wc_pb_template_add_to_cart' );
        add_action( 'woocommerce_after_single_product_summary', 'wc_pb_template_add_to_cart', 0 );
    }
}

代码说明

  1. 钩子选择:template_redirect是WordPress在确定模板后触发的钩子,此时单个产品页面的产品对象已经完全初始化,能确保我们拿到正确的产品数据。
  2. 页面判断:用is_product()确保代码只在单个产品页面运行,避免其他页面执行导致的错误。
  3. 产品有效性检查:
    • 检查$product是否存在
    • 确认它是WC_Product的实例
    • 检查产品是否有get_bundled_items方法(确保是套装产品)
    • 最后检查是否有实际的捆绑商品
  4. 动作调整:只有当所有条件都满足时,才执行移除和添加动作的操作,避免不必要的错误。

这样修改后,你就不会再遇到$product为null的问题,而且能安全地调整套装产品的显示位置啦。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:49:18