Template_include from plugin with Blade

I wrote a plugin which creates an endpoint to output some data it retrieves from an API. In order to output my HTML, I am filtering template_include like so:

The endpoint is /calendars/*

public function change_template($template)
    {
      $calendars = get_query_var('calendars', false);

        if ($calendars !== false) {
            $new_template = plugin_dir_path(__FILE__).'templates/template-calendars.php';
            if (file_exists($new_template)) {
                return $new_template;
            }
        }

        return $template;
    }

add_filter('template_include', 'change_template');

So this has been working with the theme wrapper and Sage 8. My template gets output and is wrapped properly. With Sage 9 however, I do not get any header/footer/etc.

I know I could move this plugin template into my theme and get it loading, but I do not want my plugin and theme that tightly coupled. Any ideas on how I can accomplish this?

I’ll throw out that my method for a while is that a plugin I write that fetches data from an API only communicates with the API, and the theme is responsible for taking that data and displaying it.

I prefer that amount of separation of concerns, but I do understand the desire to keep the theme separate from the plugin.

There is most likely a better way, but with Sage 9 you could perhaps filter the data variable that is passed to Blade, and in that filter, buffer the output of the plugin’s template and output that in a Blade template.

For anyone else who may run into this problem. I do the same thing, using custom rewrites in my plugins to display information that is not reliant on the loop.

The header / footer and base page structure is included through inheritance in sage 9 (the @extends(…) at the top of your theme files). My solution to this problem was to create a separate template file in my plugin that uses blade specific markup, including the @extends at the top.

Since this plugin Is shared between non sage sites, sites with sage 8 and now sites based on sage 9, in my template_include filter, I added a check that looks for the theme name and version. if they match it loads the blade template file, if not it loads the standard template file that is compatible with sage 8 and all non sage wordpress sites.

Example:

$theme = wp_get_theme();
if($theme->version >= 9) {
return ‘custom_template.blade.php’;
}
return custom_template.php;

It’s noteworthy that this only works if you don’t change your theme’s version number when you create it. I always change it to version 1.0.

Good point! A better option if you don’t maintain the sage version may be to check for theme author, or mark your theme names with a prefix/suffix and then check for that.