Add WordPress Plugin Template Files

Creating a WordPress plugin where you need to create templates that can be overridden by the theme? Learn how to build a template loading system similar to WooCommerce allowing you to do just that!

WordPress

If you’ve ever worked with WooCommerce theming, you’ve probably had to copy some of their templates files to your own theme in order to override the HTML. It’s a great system that allows frontenders the ability to change the output to match designs. In this article, I’ll walk you through how to do just that — easily add WordPress plugin template files.

Just wanna get straight to the code? Click here.


Let’s get started!

In this tutorial, we’ll create a templates folder within the plugin where we’ll add our… you guessed it, templates. Here we’ll place the templates that can be overridden in themes. These templates will be loaded via a custom plugin template function that will be called in place of WordPress’ get_template_part function.

Step 1: Locating the right template

In order for this to work, WordPress needs to be able to find the correct template file to load — the plugin or theme template. With the code below, WordPress will first look in the theme’s templates folder, if not found then will search in the main theme’s folder and then if still not found will fallback to the plugin’s templates folder.

Step 2: Loading the template file

Now that WordPress can find the right template, we need a function to load it. This is what will be used in place of get_template_part.

Step 3: Override the WordPress template file

Lastly, we’ll override the default WordPress template file with the code below.

Putting It All Together

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

Leave a Reply

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