When building custom WordPress themes or websites, one important function you'll almost certainly use is get_template_part()
. Let's explore and investigate this function.
The primary reason why this function is so useful is the DRY principle (Don't Repeat Yourself). It helps you write cleaner code, eliminating code duplication.
Typically, you will put your template files inside a directory called "template-parts". So if you have a file there called "event.php", here's how you would use that file in, for example, front-page.php.
get_template_part()
takes in 2 arguments. (The 2nd argument is optional).
get_template_part('template-parts/event');
If you want to create and reuse even more modular, smaller-sized components throughout your website, but limit the scope to just "events", you can use multiple files that begin with "event-" in the file name. For example, "event-header.php" and "event-footer.php". To use those template files, you would need to use the 2nd argument in get_template_part()
. For example:
get_template_part('template-parts/event', 'header');
get_template_part('template-parts/event', 'footer');
Conclusion
If you want to keep your WordPress code DRY, build reusable components with component-driven design patterns, you'll want to use get_template_parts()
to make those abstractions.
Top comments (0)