Overrides Plugin Files on WordPress Themes

If you’ve written the plugin, then I’d suggest you add something like this:

    // Define these constants once in your main plugin init file
    define( 'YOUR_PLUGIN_SLUG', 'your-plugin-slug' );
    define( 'YOUR_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
    define( 'YOUR_PLUGIN_TEMPLATE_DIR', trailingslashit( YOUR_PLUGIN_DIR ) . 'templates' );
    define( 'YOUR_PLUGIN_THEME_TEMPLATE_OVERRIDE_PATH_DIR', trailingslashit( get_stylesheet_directory() . "https://wordpress.stackexchange.com/" . YOUR_PLUGIN_SLUG );

    // Define a function to locate template files
    function your_plugin_name_get_template_part_location( $part ) {
      $part = $part '.php';

      // Look in the user's theme first for the file
      if ( file_exists( YOUR_PLUGIN_THEME_TEMPLATE_OVERRIDE_PATH_DIR . $part ) ) {
        $file = YOUR_PLUGIN_THEME_TEMPLATE_OVERRIDE_PATH_DIR . $part;
      } 
      // Otherwise use the file from your plugin
      else {
        $file = YOUR_PLUGIN_TEMPLATE_DIR . $part;
      }
    }

First, you define some constants (do this once in your main plugin init file), which you might already have.

Then the function allows you to call files (in my example, template files inside /plugins/your-plugin-name/templates).

For example, you could use

get_template_part(your_plugin_name_get_template_part_location('widget'));

Your plugin will first look in the user’s theme to see if an override is in place.

If this DOESN’T exist, then it will look in your plugin.

Of course, you can modify this to fit your own directory structure and needs.

Leave a Comment