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

覆盖WooCommerce模板部件致无限循环,如何避免关联产品加载?

解决WooCommerce自定义模板部件无限循环问题

问题根源在于你的模板覆盖函数会在所有产品模板部件加载时触发,包括关联产品(相关产品、交叉销售、追加销售等)的循环场景。当关联产品满足元值条件时,会加载自定义模板;如果自定义模板中又包含关联产品模块,就会再次触发模板覆盖逻辑,最终导致无限循环。

解决方案1:针对关联产品循环直接排除

通过WooCommerce内置的$woocommerce_loop全局变量,可以识别当前是否处于关联产品类的循环中,直接跳过模板覆盖逻辑:

function override_woo_template_part($template, $slug, $name) {
    global $post, $woocommerce_loop;

    // 排除关联产品、交叉销售、追加销售的循环场景
    if (isset($woocommerce_loop['name']) && in_array($woocommerce_loop['name'], array('related', 'cross-sells', 'upsells'))) {
        return $template;
    }

    $product = wc_get_product($post->ID);
    $myplugin_type = $product->get_meta('_myplugin_type');
    $path = '';

    if ($name && !empty($myplugin_type) && $myplugin_type != 'default') {
        $template_directory = myplugin_directory_path() . '/woocommerce/';
        $path = $template_directory . "{$slug}-{$myplugin_type}.php";
    }

    return file_exists($path) ? $path : $template;
}
add_filter('wc_get_template_part', 'override_woo_template_part', 10, 3);

这段代码的核心是:检查$woocommerce_loop['name']是否属于关联产品类循环,若是则直接返回原模板,不执行自定义覆盖逻辑。这样关联产品会使用默认模板,不会触发循环。

解决方案2:仅在主查询的单个产品页面执行覆盖

如果你希望只在当前页面的主产品(而非次级循环中的关联产品)上应用模板覆盖,可以通过主查询判断来实现:

function override_woo_template_part($template, $slug, $name) {
    global $post, $wp_query;

    // 仅在主查询的单个产品页面中执行模板覆盖
    if (!is_singular('product') || !$wp_query->is_main_query()) {
        return $template;
    }

    $product = wc_get_product($post->ID);
    $myplugin_type = $product->get_meta('_myplugin_type');
    $path = '';

    if ($name && !empty($myplugin_type) && $myplugin_type != 'default') {
        $template_directory = myplugin_directory_path() . '/woocommerce/';
        $path = $template_directory . "{$slug}-{$myplugin_type}.php";
    }

    return file_exists($path) ? $path : $template;
}
add_filter('wc_get_template_part', 'override_woo_template_part', 10, 3);

这个方法通过is_singular('product')确认当前是单个产品页面,再通过$wp_query->is_main_query()确认是主查询(即当前页面的主产品),次级循环中的关联产品会被排除在外。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:55:15