Passing a variable through to the template

Hello - just started using roots. Very cool. Am working on a plugin that has it’s own template_include call based on a custom rewrite_url and and query variable to display content.

I want to be able to pass my content variables through to the resulting template for formatting. The method I have been employing works in other themes, but it breaks in roots (because of the Theme Wrapper, I would assume).

What’s the best way I can either fix my plugin to work or fix my roots to work ?

Here is what I mean:

function content_template( $template ) {
        global $wp_query;

        if (isset($wp_query->query_vars['contentid'])) {
            $testvariable = 'this is a test variable';

            $new_template = locate_template( array( 'template-custom.php' ) );

            if ( '' != $new_template ) {
                // if I use include here, other themes work fine and I can
                // access the $testvariable
                include(locate_template( array( 'template-custom.php' ) ) );

                // however, with roots, I have to use:
                return $new_template;
                // which means the $testvariable is missing

            } else {
                // display a bioler plate if the user hasn't set a themed
                // template file yet
                include(dirname(__FILE__) . '/template.php');


        return $template;

Appreciate your help. I could use a global $myclass; $myclass = new MyClass(); but I keep reading globals are bad. Then again, Wordpress uses them a lot.

1 Like

By calling exit, you are killing the script and preventing the wrapper from being being initiated. That’s fine with the template_redirect, an action, but template_include is a filter, so it really should have a return value.

I would attach the data you’re looking to pass as page/post meta, use a singleton class or just use a global.

Thanks for getting back to me and excellent point about calling exit. I removed the exit and move the return $template up into the final else statement … so it returns one or the other.

I think I’ll just use a global for now. Appreciate your help!

Is there a way to pass variables between templates?
It seems that when I use


It won’t let me use variables that were declared in the parent file, so to speak. Is there a better way than using global variables?

You can always use classes instead of globals.