·

photo credit: _DSC3496 via photopin (license)

get_template_part in WordPress with variables

As some of you might know, the get_template_part() -function of WordPress doesn’t allow you to pass variables. This can be quite annoying sometimes when you want to include a template several times, but each time with different parameters.
Imagine a situation for example where you want to show 3 category blocks next to each other, that each contain a link to the category, as well as the latest article in that specific category. If you don’t want to make your templates all too complex with all kind of PHP functions (like most of the solutions for this problem on the Internet do), how would you do this?
Well, I ran into the same situation and here’s how I fixed it:

The method

I hope you already learned how to keep your WordPress themes tidy and organised. If not, I suggest you read this article about before you continue reading.
In your theme class, we create a method called getTemplatePart()  which works the same as the default get_template_part() -function of WordPress, but with one addition: it can accept parameters:

Notice the little trick I did here by creating dynamic variables in PHP by writing $$key = $value . No, it’s not a typo: the double dollar signs allows us to create variables whose name is defined by our template. For example, if the value of $key  is ‘foo’ and the value of $value  is ‘bar’, our included template part will have a variable called $_foo  with the value ‘bar’ (the underscore is added one line before, but you can omit that if that’s your thing). It’s that simple!

The implementation

You can use this implementation in your template like this:

The template file (located in partials/category.php ) can look something like this:

Note the loading of the proper category according to $_slug : a variable assigned with a value in our main template. Also the variable $_last  is used to determine whether or not we should add an additional class to our wrapper.

Visitors give this article an average rating of 4.4 out of 5.

How would you rate this article?

Leave a Reply