One of the easiest mistakes to make as an early WordPress developer is understanding the difference in PHP’s include
and require
functions and WordPress’ built-in functions – such as get_template_part
– for working with templates.
In my latest article on WPTuts+, I take a look at each of these functions.
Specifically, I take a look at the following:
- include
- include_once
- require
- require_once
- get_template_part
I cover the definitions of each, the advantages and disadvantages of each, and how to properly include files with WordPress using get_template_part
.
I also provide a few guidelines as to when it’s appropriate to use each function and my personal rules of thumb when working with each. I end the article with links to a few articles for further reading.
If this is a new topic to you, or you’ve always been curious about each, then be sure to read it and leave a comment!
The theme appears to use include or require. If these are being used to include separate sections of a template from independent files, then get_template_part() should be used instead.
Line 12: require_once(MAIN_PATH.’includes/shortcode/shortcodes.php’);
How can i fix
I’m not sure what theme you’re talking about..
Great article and a good comparison between features. It answered a few questions that I had.
Recently, I was building a site which I decided to use template parts as that just made sense. The whole idea of the variable scope not working with get_tempate_part thus having to declare the variables and loops in the files seems a bit repetitive but I can see the benefit. hmmmmm. Thanks again. Appreciate you taking the time to go through the variations.
Thanks for the comment!
Since this has been written, I’ve got a bit of a different take on the whole process which has mainly come from experience and newer things I’ve learned.
Including template parts and having variables declared outside the template (with their scope still accessible within the template) can save time but it also makes for the code harder to read since it’s not always apparently where they were created).
Adding loops and what not within a template is something I try to get away from. There are a few ways to do it (which are outside the scope of this particular comment but looking at protected methods up to templating engines are things that can help.
Maybe that’ll prove useful in what you’re working on!