When developing a WordPress theme I like to organize code into manageable, reusable pieces when ever possible. One great way of doing this is to add an inc
directory to the theme and fetch files from it using:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php get_template_part('inc/my', 'snippet'); ?> |
This works great most of the time to load your snippets. What if you need to pass a variable through to the snippet? I ran into trouble recently trying to add a $count++ variable through to create a unique ID
on an element. As you know by now it didn’t work. Thankfully as Tommus Rhodus pointed out in a post, we can use locate_template();
.
Here’s how it’s implemented on the same file as above:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php include(locate_template('inc/my-snippet.php')); ?> |
So why variables don’t get passed through get_template_part();
? Turns out to be a scoping issue. locate_template();
simply finds the file for inclusion, and include
copies the entire file where requested. get_template_part();
is a function which means your variables aren’t available without explicitly being declared or using global variables.