Reputation: 6991
I would like to restructure the template files in a Wordpress theme that I am creating. Right now, files such as single.php
and archive.php
are on the root level of my theme. I would like to move them into their own folder -- say a folder called pages
. So that it would look something like this:
mytheme
-- pages
-- archive.php
-- single.php
-- functions.php
-- index.php
-- style.css
Is this possible? If so, how?
Thanks.
Upvotes: 5
Views: 1144
Reputation: 21
(type)_template_hierarchy
hook.Docs: https://developer.wordpress.org/reference/hooks/type_template_hierarchy/
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:
replace_index_location
receives all candidates. Try to var_dump($templates)
variable to see what is inside.But if you need to move all files, not just index.php
?
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!
Upvotes: 2
Reputation: 811
You can use the single_template
filter and {$type}_template
filter for the archive, category etc.
I thing that something like this is what you look for:
function get_new_single_template( $single_template ) {
global $post;
$single_template = get_stylesheet_directory() . '/pages/single.php';
return $single_template;
}
add_filter( 'single_template', 'get_new_single_template' );
function get_new_archive_template( $archive_template ) {
global $post;
$archive_template = get_stylesheet_directory() . '/pages/archive.php';
return $archive_template;
}
add_filter( 'archive_template', 'get_new_archive_template' );
This goes to your functions.php
Upvotes: 4