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

PHPUnit环境下get_template_directory()返回子主题路径的问题及解决

问题描述
  • 使用WP-CLI的wp scaffold theme-tests命令为WordPress子主题搭建测试环境
  • 子主题functions.php中通过require_once get_template_directory() . '/lib/init.php';加载父主题函数,浏览器运行主题时此代码能正常加载父主题的init.php,但PHPUnit测试时get_template_directory()返回的是子主题路径
  • 已通过输出wp_get_theme()->parent()->name确认测试环境能识别并加载父主题,该语句在PHPUnit中可正确返回父主题名称
解决方法

修改测试框架生成的bootstrap.php文件,具体操作如下:

  • 在_register_theme()函数内添加过滤钩子:
add_filter( 'template_directory', 'fix_phpunit_get_template_directory', 10, 3 );
  • 添加对应的回调函数:
function fix_phpunit_get_template_directory( $template_dir, $template, $theme_root ) {
    return wp_get_theme()->parent()->get_stylesheet_directory();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 12:12:07