For anyone who has worked with WordPress on some level, you’re likely familiar with the concept of templates.
In the context of WordPress, templates are the files in which information retrieved from the database is rendered. In other frameworks or platforms, they may also be called templates, but are also often referred to as views.
But for anyone who has done enough work with building web applications, you know that as much as we like to build reusable components on the server-side – be it functions, classes, or whatever else – that we also like to do so with client-side related code, too.
When it comes to creating reusable components for WordPress templates, one of the most useful functions and features that we have at our disposable is the `get_template_part` function.
The thing is, after seeing enough code, I’m not sold on the idea that we’re taking advantage of it as much as we should in order to create more reusable code on the front end of WordPress themes (or views or WordPress plugins).
According to the Codex, the function should be used when we need to:
Load a template part into a template (other than header, sidebar, footer).
But there are additional ways to use the function to help create more modularized templates. Here’ my rule of thumb as it relates to WordPress partials:
If a piece of code is going to be reused across multiple templates, then abstract it into a partial.
Essentially, if I’m going to be using a set of code more than once throughout my theme or application, then I move it to a partial.
Sometimes, though, we don’t know if we’re going to need to do that until we’re further along in development, but that’s okay.
That’s why we have refactoring.
A Practical Example
Anyway, I also take this one step further such that I organize my project directory to include a `partials` directory:
From there, I can then easily include any of these partials in any of my primary templates used throughout my profile.
Then, say, I wanted to use `pagination.php` in a number of different templates, I simply call:
`get_template_part( ‘partials/pagination’ );`
And we’re good to go.
But That’s Easy
I know – and it makes front end development cleaner, and it makes our code more reusable, but this is something that I still don’t see being used as much as it should be.
So if you’re in the process of working on something in WordPress, and it affords the opportunity to create more reusable components, take advantage of this.
Leave a Reply
You must be logged in to post a comment.