Why I stop using the default include functions built in with WordPress
This post will be a bit more technical then the others, so be advised if you’re not much into WordPress design or programming.
So WordPress comes with many built in functions created to make life easier when you want to include a template part in other template files. The most well known are:
get_header()
get_footer()
get_sidebar()
get_template_part( ‘$slug’, ‘$name’ )
To include a file named, for example, inc-foo.php with the last function we would call it like that get_template)part( ‘inc’, ‘foo’) .
Ok, so far all looks great, so why I changed my default way of including template parts of wordpress from the ones above to
include(locate_template(‘filename.php’)); ?
The first reason is: I’m currently developing a framework for WordPress, one of the objectives of that framework is to make the integration of any theme/plugin with WordPress easier and also to centralize the code logic outside of the template files.
That way I’m able to move reusable pieces of code into models (classes) and also to centralize all information that goes from/back to the user through a main controller file.
The second reason is: To acess the methods or properties of that main controller file I decided make it a global variable that could be accessed in any part of the template, the problem is, when you use the built in wordpress methods you have to redeclare global $frontcontrollername everytime, since it change it’s in a new scope.
By using the include, instead, I only need to declare the global $frontcontrollername once, and it will be automatically available to any template file of my theme.
There are many reasons for that coding style change and the Framework, so will save all that explanation for another post.