Over a million developers have joined DZone.

Override Theme Template In Plugin

· Web Dev Zone

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

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

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.


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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}