如何在自定义插件中覆盖WooCommerce及全类型分类法术语归档模板
问题原因
- 你当前用的
woocommerce_locate_template钩子仅作用于WooCommerce内部的模板调用,普通文章分类、第三方插件自定义分类法(比如LearnDash的分类)走的是WordPress核心模板加载逻辑,无法被这个钩子覆盖。 - 你没有限制模板替换的触发场景,不管当前加载的是页面主模板还是内部嵌套的子模板,都会被替换成你的自定义归档模板,才会出现页脚后重复输出内容的问题。
完整适配代码
// 覆盖WordPress核心所有分类法归档模板(适配普通分类、标签、第三方插件自定义分类法) add_filter( 'template_include', 'override_all_taxonomy_template', 99 ); function override_all_taxonomy_template( $template ) { // 判断是否为任意分类法的归档页 if ( is_tax() || is_category() || is_tag() ) { $custom_template = plugin_dir_path( __FILE__ ) . 'templates/cust-taxonomy.php'; // 确认自定义模板存在再替换 if ( file_exists( $custom_template ) ) { return $custom_template; } } return $template; } // 兼容处理WooCommerce分类法模板,避免重复加载 add_filter( 'woocommerce_locate_template', 'override_woocommerce_tax_template', 10, 3 ); function override_woocommerce_tax_template( $template, $template_name, $template_path ) { // 仅替换WooCommerce的主归档模板,排除子模板(比如商品循环模板、分页模板等) $allowed_templates = [ 'taxonomy-product_cat.php', 'taxonomy-product_tag.php', 'archive-product.php' ]; if ( in_array( $template_name, $allowed_templates ) && ( is_tax() || is_product_category() || is_product_tag() ) ) { $custom_template = plugin_dir_path( __FILE__ ) . 'templates/cust-taxonomy.php'; if ( file_exists( $custom_template ) ) { return $custom_template; } } return $template; }
注意事项
- 你需要确保自定义的
cust-taxonomy.php模板是完整的独立页面模板,包含完整的页眉、内容、页脚结构,不要遗漏wp_head()和wp_footer()调用。 - 如果需要对不同分类法做差异化展示,可以在模板内通过
get_queried_object()->taxonomy获取当前分类法标识,做分支逻辑判断即可。
内容的提问来源于stack exchange,提问作者Parthavi Patel
相关产品推荐
相关产品推荐

