php - 如何覆盖locate_template函数?
问题描述
我正在尝试将 Wordpress 的模板文件重新映射到我的主题中的子目录(类似于views
文件夹)。我尝试了一些在 Wordpress 文档中找到的钩子,但没有按预期工作。
分析“包含”主题模板文件的核心功能,我在wp-includes/template.phplocate_template
文件中找到了该功能。我想覆盖该功能以达到我想要的效果。
所以,原来的函数体是:
function locate_template( $template_names, $load = false, $require_once = true, $args = array() ) {
$located = '';
foreach ( (array) $template_names as $template_name ) {
if ( ! $template_name ) {
continue;
}
if ( file_exists( STYLESHEETPATH . '/' . $template_name ) ) {
$located = STYLESHEETPATH . '/' . $template_name;
break;
} elseif ( file_exists( TEMPLATEPATH . '/' . $template_name ) ) {
$located = TEMPLATEPATH . '/' . $template_name;
break;
} elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {
$located = ABSPATH . WPINC . '/theme-compat/' . $template_name;
break;
}
}
if ( $load && '' !== $located ) {
load_template( $located, $require_once, $args );
}
return $located;
}
而覆盖只是将一个附加views/
到 Wordpress 搜索模板文件的路径,如下所示:
function locate_template( $template_names, $load = false, $require_once = true, $args = array() ) {
$located = '';
foreach ( (array) $template_names as $template_name ) {
if ( ! $template_name ) {
continue;
}
if ( file_exists( STYLESHEETPATH . '/views/' . $template_name ) ) {
$located = STYLESHEETPATH . '/views/' . $template_name;
break;
} elseif ( file_exists( TEMPLATEPATH . '/views/' . $template_name ) ) {
$located = TEMPLATEPATH . '/views/' . $template_name;
break;
} elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {
$located = ABSPATH . WPINC . '/theme-compat/' . $template_name;
break;
}
}
if ( $load && '' !== $located ) {
load_template( $located, $require_once, $args );
}
return $located;
}
我知道修改核心函数是一个(大)错误,所以我想要的是从我的主题的functions.php文件中覆盖这个函数。我想我只需要在一些初始化钩子上重新声明这个函数,但我找不到要使用的钩子(如果这是正确的方法)。
有人可以帮我弄这个吗?
解决方案
"I'm trying to remap Wordpress' template files to a subdirectory in my theme"
Why? Use a child theme. Anything else would be brittle and error prone.
Consider using an htaccess file for the remap.
推荐阅读
- c++ - 正则表达式代码无故停止工作
- isabelle - 在 Isabelle 中定义带参数的子类
- mysql - 1256 列数据被截断
- php - 如果在 CodeIgniter 中不为空,如何更新可选字段?
- https - ratpack:实现自定义 PublicAddress 以强制 https
- react-native - 有没有办法将 Android Material Components 与 React Native 一起使用?
- html - 首页菜单隐藏在某处
- php - 语言 laravel 设置
- javascript - Forge Viewer API:特定元素的边界框
- php - Laravel 验证:输入的列必须与登录用户的电子邮件相同