WordPress

Override Theme Template In Plugin

In this tutorial we are going to look at how you can override a theme template file from within a plugin.

When WordPress displays a piece of content it selects the theme template by using a hierarchy of files, for example if you want to view the content of the a single post the WordPress hierarchy is:

  • single-{post_type}.php
  • single.php
  • index.php

This works by searching for the single-{post_type}.php file in the theme, if it's not there then it will search of the single.php file, if that isn't there then it will just use the index.php file to display the content.

By default WordPress will search for these files inside the selected theme, but what if you have created a new post type and want to take over the theme HTML with a template inside the plugin.

There is a filter in WordPress that you can use to change the template file to display instead of the default WordPress template hierarchy. The WordPress filter we are going to use is single_template, the return of this filter is the template that will be displayed.

Below is code you can use to get a template file from within a plugin, simply add the following to your plugin and change the location of the template.

function change_post_type_template($single_template) 
{
     global $post;

     if ($post->post_type == 'custom-post-type') 
     {
          $single_template = plugin_dir_path( __FILE__ ) . 'templates/custom-post-type-template.php';
     }

     return $single_template;
}
add_filter( 'single_template', 'change_post_type_template' );
Back to top