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:
https://gist.github.com/spigotdesign/18d0206e3a3d458c7149
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:
https://gist.github.com/spigotdesign/fc624929ceb2c567aa95
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.