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
相关产品推荐
相关产品推荐

