I’m developing a new WordPress theme, and all of the pages are going to share some of the “outer” markup (head, body, header, footer).
Rather than duplicating some of this code (e.g. calling get\_header();) in every template (e.g. home.php, page.php, 404.php, etc), I’d like to route everything through index.php, and **then** route it to the relevant template file. Is this possible, or mimic-able in some way?
For instance, my folder structure could be this:
theme-folder/
– style.css
– functions.php
– index.php <– this would get run first
– templates/ <– then the WP hierarchy would run one of the files in this folder
– – index.php
– – home.php
– – page.php
– – 404.php
And my index.php might look like this:
<!DOCTYPE html>
<html>
<head>…</head>
<body>
<?php
// this would execute the normal WP heirarchy, but search within the /templates folder for matches
use_wordpress_hierarchy_within_folder(‘templates’);
?>
</body>
</html>
It seems like this would allow me to follow the principle of DRY better than I would be able to if I use the normal WP method of having separate – but somewhat duplicative – home.php, page.php, and other template files.
Any thoughts on how to do this, or reasons why I shouldn’t do it from a technical perspective?
[ad_2]
You should read up on template parts, and the template hierarchy. If you really want, you CAN have everything go to index.php BUT it’s just one bad thing (get header in all files) for another (endless conditionals (if page= then get_this_part)).
It’s about the middle path Daniel San… there’s really no bloat in a get_header call in several templates (e.g. post, page, front, archive) and then some if’s within those templates to get the parts (e.g. post – if cat=X get part_content_X).
*Rather than duplicating some of this code (e.g. calling get_header();) in every template*
That’s not duplication – that’s how you call a code fragment. It’s the cleanest, most efficient way of doing things. Routing it through some other file would make it unnecessarily complicated, and non-standard – you’d have a mess of SWITCH/IF/IFELSE statements, that would not be manageable over time.
There’s a reason WP is setup the way it is – because it’s the standard way of doing templates. Don’t do something completely different when there are perfectly standard ways of doing things.
It sounds like you’re looking to pull off template inheritance within WordPress which is definitely possible.
Take a look at this [theme wrappers]) post from scribu, which we used in the Sage starter theme prior to switching to Laravel Blade.