对我来说,(type)_template_hierarchy
钩子很有效。
文档:https://developer.wordpress.org/reference/hooks/type_template_hierarchy/
长话短说
它是做什么的?WordPress正在寻找所有可以匹配请求URL的模板文件名。然后它按优先级选择最好的一个。但是您可以在此之前更改这些文件名的数组。
WordPress中有很多模板名称,在这里列出。
要替换单个文件位置,例如只有 index.php
,您可以使用以下代码:
add_filter('index_template_hierarchy', 'replace_index_location');
function replace_index_location($templates) {
return array_map(function ($template_name) {
return "pages/$template_name";
}, $templates);
}
看一下:
- 首先,我们添加钩子来替换索引文件位置。
- 函数
replace_index_location
接收所有候选项。尝试var_dump($templates)
变量,以查看其中的内容。
- 然后,将此数组简单映射到另一个数组中,为每个文件名添加“pages”文件夹或任何其他文件夹。所有这些路径都是相对于主题文件夹的。
但是,如果您需要移动所有文件,而不仅仅是index.php
呢?
解决方案
我们来看看:
function relocate() {
$predefined_names = [
'404', 'archive', 'attachment', 'author', 'category',
'date', 'embed', 'frontpage', 'home', 'index', 'page',
'paged', 'privacypolicy', 'search', 'single', 'singular',
'tag', 'taxonomy',
];
foreach ($predefined_names as $type) {
add_filter("{$type}_template_hierarchy", function ($templates) {
return array_map(function ($template_name) {
return "pages/$template_name";
}, $templates);
});
}
}
relocate();
这段代码使我们的文件树看起来像这样:
mytheme
-- pages
-- index.php // index also here
-- archive.php
-- single.php
-- functions.php
-- style.css
如果您不需要将
index.php
放在
pages
文件夹中,只需从
$predefined_names
中删除
index
即可。
祝您好运!