Passing variables through get_template_part()

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 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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

See if Cinch is right for you.

Ask us anything. Seriously. Like, what is the air speed velocity of an unladen swallow?

Start a chat right now

Or go ahead and Sign up now