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

为何include(locate_template)生效但get_template_part()在子主题中失效?

解决子主题用get_template_part调用父主题导航组件失效的问题

遇到这种情况,大概率是两个核心原因导致的,咱们一步步排查解决:

1. 先检查子主题是否存在同名模板文件

get_template_part的规则是优先加载子主题中的对应文件,如果子主题目录里已经有components/navigation.php,它就不会去加载父主题的版本了。如果这个子主题里的文件没写全(比如缺少父主题模板依赖的变量),就会触发你看到的「Undefined variable」错误。

解决办法:

  • 如果你不需要子主题自定义导航,直接删除子主题里的components/navigation.php,让get_template_part自动加载父主题的文件;
  • 如果需要自定义,就补全子主题模板里缺失的变量或逻辑。

2. 变量作用域的差异(最可能的元凶)

这是include(locate_template(...))和get_template_part最关键的区别:

  • include是在当前代码的作用域内执行,调用处的局部变量能直接被导航模板文件访问;
  • get_template_part是在WordPress的函数内部执行include,属于独立的函数作用域,调用处的局部变量无法直接传递到模板里,这就导致父主题的navigation.php找不到依赖的变量,出现Undefined提示。

针对这个问题,有两种规范的解决方式:

方式一:用全局变量传递(简单直接)

在调用get_template_part之前,把需要的变量声明为全局变量:

// 调用处的代码
global $nav_menu_args;
$nav_menu_args = array( 'theme_location' => 'primary' ); // 示例变量,替换成你实际需要的
get_template_part( "components/navigation" );

然后在父主题的navigation.php里,也要用global声明引用这个变量:

// navigation.php里的代码
global $nav_menu_args;
wp_nav_menu( $nav_menu_args );

方式二:用set_query_var传递(更符合WordPress规范)

这种方式避免全局变量污染,是官方推荐的模板变量传递方式:

// 调用处的代码
set_query_var( 'nav_menu_args', array( 'theme_location' => 'primary' ) );
get_template_part( "components/navigation" );

在navigation.php里用get_query_var获取变量:

// navigation.php里的代码
$nav_menu_args = get_query_var( 'nav_menu_args' );
wp_nav_menu( $nav_menu_args );

最后再确认用法正确性

你写的get_template_part( "components/navigation" )是完全正确的,它会自动查找components/navigation.php文件,和locate_template( "components/navigation.php" )的路径匹配,所以用法上没问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:38:09