WordPress: How to deploy a theme file from your plugin

WordPress is great. We love it. It keeps evolving way faster than Drupal ever did. Well, in the beginning Drupal was great. But for some reason, Drupal died. Anyway. As a South Florida WordPress Development Agency, we get to dig into WordPress pretty deeply. One thing that might not be too obvious to most people, is how do we create a plugin and use a theme file that can be overwritten as needed?

Here’s how:

add_filter('single_template', 'my_plugin_single_template');
function my_plugin_single_template($single) {
global $wp_query, $post;
$filename = 'single-'.$post->post_type.'.php';
if(!locate_template($filename)) {
$filepath = MY_PlUGIN_PATH . '/templates/' . $filename;
if(file_exists($filepath)) {
$single = $filepath;
}
}
return $single;
}

This function does the following:

  • checks that the template file does not exist in the theme
  • checks to make sure the files exists in the plugin directory
  • if those 2 conditions are met, it uses the plugin file.

This is great because it lets you create a plugin, use the template file from the plugin, and then let the theme developer override the file as needed.

MY_PLUGING_PATH – is the plugin path to your plugin. You should set it like so:

<?php
/** Plugin File **/
define('MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ));

Of course, you would call your plugin whatever your heart desires.

Leave a comment

Find the Best SEO in Fort Lauderdale, Florida (Plantation SEO) | Drupal & Worpress Develpment