Press "Enter" to skip to content

Templating out chunks of reusable front end code in WordPress

No matter what you are engineering, there are a number of principles that stay the same. D.R.Y (don’t repeat yourself) is one of those principles. While building out your WordPress theme, you’ll likely notice that there are a few different chunks that are the same across the site. Let’s make them D.R.Y!

WordPress offers the get_template_part() function which allows you to split that chunk off into it’s own file rather than repeating the same code over and over again. One drawback to get_template_part(), however, is that you can’t pass variables through to it. I ran into an instance recently where I had a chunk of html that needed to wrap around the title of the page. At first I used get_template_part() and inside of the template I called the_title() to dynamically populate the header title. That worked great! That is.. until I needed to use the same style header on the search, archive, and 404 pages.

The Solution

After some searching around, I found that this wasn’t an uncommon issue. The popular way around this is by setting up your variable on the page you want to include the chunk of code on and using the following method to pull in that template: include( locate_template( ‘template-name-here.php’ ) ); By using the code above, you have access to any variables you define in the parent template. I like to store my layout templates in a folder in my theme called ‘layouts’. For templates that require variables to be passed into them, I store them in a subfolder of layouts called ‘vars’. Here is my example folder structure: layouts/var/title.php This might seem a little confusing, so here is an example of how I implemented this solution:

 $vars = array(
    'title' => 'Search Results for: '. get_search_query()
);
include( locate_template( 'layouts/vars/title.php' ) );
<div class="[ section ] [ mast mast__callout ]">
  <div class="container">
    <div class="row">
      <div class="[ col-sm-12 ] [ mast__callout-text ]">
        <h1><?php echo $vars['title']; ?></h1>
      </div>
    </div><!-- .row -->
  </div><!-- .container -->
</div><!-- .section -->

Conclusion

That’s it! I’ll update this post if I end up finding a better way to template out your theme files (and pass variables through to them).

One Comment

Leave a Reply

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