photo credit: jenny downing via photopin cc

WordPress: Templates in plugins

When you are creating a WordPress plugin, you might encounter the situation where you have to include a template in your theme. But you also want to give the users of your plugin the ability to make changes to this template, without overwriting the core template. The most intuitive way to provide this is by using the get_template_part() -function to provide a way to override your themes’ template files. But WordPress doesn’t work like this out of the box. So how can we make this happen?

Use get_template_part with your plugin

Let us first look at what get_template_part()  really does. If you look at the code of the actual function itself, you’ll notice that the first thing it does is fire an action like this:

Now this is interesting, since it gives us something to work with. For example, if your template does something like get_template_part(‘cool/stuff’) , it triggers the action get_template_part_cool/stuff . So let’s just work from there. Say we want to do something with this action, we need to register it. Now there are various ways to do this, but I’ll use object oriented approach here:

Now, the constructor seems pretty straight forward, but let me explain the getTemplatePart() -method: The first thing it does is check if the file exists in your theme’s directory. And here’s where it gets interesting: if it does find a theme, this method does absolutely nothing. Because of this, the get_template_part() -function just does what it’s supposed to do and loads the template part. This is the desired result, because if we have a template in our themes’ directory, that means that file needs to be loaded and not the one shipped with the plugin.
If it doesn’t find a template file in the themes’ directory, we know that the get_template_part() -function also isn’t going to do anything. In that case we invoke the load_template() -function to load the template part (the load_template() -function is the same function that is eventually used by get_template_part()  so in that case we also get all the globals).
Also note the definition of the absolute path (dirname(__FILE__) ) to make sure we load the template part from the plugin’s directory and the str_replace() -function to replace the first part of our slug. This last part is done because it’s very likely that you have your template parts shipped with your plugin placed in a directory like templates  or something and that you allow overriding these template files in a subdirectory in the theme folder that resembles the name of your plugin.

Multiple templates

Unfortunately, this approach doesn’t allow for a wildcard, so if you have multiple template files, you also need to register multiple actions:

But then again, you could also automate this by using a glob()  or something, but that’s another story…

Visitors give this article an average rating of 3.0 out of 5.

How would you rate this article?

Leave a Reply