For me works (type)_template_hierarchy
hook.
Docs: https://developer.wordpress.org/reference/hooks/type_template_hierarchy/
Long story
What it does? WordPress is looking for all template filenames that can match requested URL. Then it selects the best of them, by priority. But you can change this array of filenames before.
There are a lot of template names in WordPress, all of them listed here.
To replace single e.g. just index.php
file location you can use this code
// functions.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);
}
Take a look:
- First of all we add hook to replace index file location.
- Function
replace_index_location
receives all candidates. Try to var_dump($templates)
variable to see what is inside.
- And then simple map this array to another one, adding to each filename the "pages" folder or any other. All this paths are relative to theme folder.
But if you need to move all files, not just index.php
?
Solution
Here we go:
// functions.php
function relocate() {
// All available templates from
// https://developer.wordpress.org/reference/hooks/type_template_hierarchy/#description
$predefined_names = [
'404', 'archive', 'attachment', 'author', 'category',
'date', 'embed', 'frontpage', 'home', 'index', 'page',
'paged', 'privacypolicy', 'search', 'single', 'singular',
'tag', 'taxonomy',
];
// Iteration over names
foreach ($predefined_names as $type) {
// For each name we add filter, using anonymus function
add_filter("{$type}_template_hierarchy", function ($templates) {
return array_map(function ($template_name) {
return "pages/$template_name";
}, $templates);
});
}
}
// Now simply call our function
relocate();
This code makes our file tree looks like:
mytheme
-- pages
-- index.php // index also here
-- archive.php
-- single.php
-- functions.php
-- style.css
If you don't need index.php
to be in pages
folder simply remove index
from $predefined_names
.
Lucky hacking!