Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Override Theme Template In Plugin

DZone's Guide to

Override Theme Template In Plugin

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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' );

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}