Loading WordPress template files in plugins
I’ve been working on a project where I wanted to include a template file to handle the display of a particular WordPress custom post type. However, I wanted this template to be included in the plugin that created the custom post type and not in the theme. The plugin adds the post type to one site, and one site only, within a multisite network, so I didn’t want to clutter up the folder of the theme which is used on other sites that don’t require the plugin.
So I looked for a way to do this and discovered the role of template loaders within plugins. Including a template loader in your plugin allows you to associate a template file in your plugins folder with a filter hook or a shortcode. But the great advantage is that it replicates the behaviour of the get_template_part()
function — which means you can override the default plugin template file with a custom file in a child or parent theme. (Obviously I didn’t need this in this case but it is an example of the good practice of ensuring that plugins and themes are not dependent on each other.)
For a better explanation of this see Template File Loaders in Plugins.
As suggested in the above post I made use of the Gamajo Template Loader which is:
A class to copy into your WordPress plugin, to allow loading template parts with fallback through the child theme > parent theme > plugin
I found this class really easy to implement and you can download it from GitHub.
Thanks to Gary Jones the developer who made it available.
This content was originally posted on my company website Grit & Oyster Limited.