WordPress provides a function called get_template_part to developers, so that individual pieces of code can be split into individual components and reused. However, there is one drawback: you can’t pass data to the template part directly, which hampers the reusability of such template parts.

The solution I implement is to use my own alternative function to use locate_template and pass it the data I require. I call my function and pass it the array (or string) to the required template part/s in the same way as the core function. However, my function optionally accepts a second parameter: an array called $data. The function then uses require and locate_template to get the template part.

Because $data is inside a function, the scope means that it only applies within the function itself and within the template part called within the require call. This means that the global scope remains clean, and there’s no need to use cumbersome solutions with set_query_var and the like.

Updated 24th October: the amended code now uses the PHP 5.6 spread operator to allow you to either pass one or two additional attributes to the function, as well as the primary path. If you pass an array, that will be available as $data in the included file. If you pass a string as the first of the additional attributes, this will be used as a post type and the list of possible file paths will be extended. (e.g. ['partials/excerpt.php', 'partials/excerpt-customposttype.php'] ).

The function (which is part of a package-based Theme class structure) looks like this:

…and the call looks like this:

In this example, the array $my_authors is pre-filled using a project-specific logic and the author_card template part is reused for each of the authors in turn.

Leave a Reply

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

For security, use of Google’s reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

This site uses Akismet to reduce spam. Learn how your comment data is processed.