Switch WP template from functions.php without changing base.php

Hi everybody,
I’m Giulio Andreini from Italy, I’m looking for some help.

I need to load a different template for a CPT when there’s a GET variable passed in the URL.

The CPT is mix and I normally use the template single-mix.php.
Then when the variable ?expanded=true is added to the URL i want to use the template single-mix-alt.php.

This is the snippet of code I use in functions.php

function mix_template_redirect( $template )
{
  if ( get_post_type() == 'mix') {
    if (isset($_GET['expanded'])) {
      $expanded = $_GET['expanded'];
      if($expanded == "true") {
        // Here I try to swicth template
        $template = dirname( __FILE__ ) . '/single_mix_alt.php';
      }
    }
  }
  return $template;
}
add_action( 'template_include', 'mix_template_redirect' );

I use the WP hook template_include and then I check if the GET variable is there.
I finally try to tell WP to use the other template… but here it fails.

I got these two warnings on the frontend page:

Warning: include(/Applications/MAMP/htdocs/tracks/wp-content/themes/mixovery/single_mix_alt.php): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/tracks/wp-content/themes/mixovery/base.php on line 46

Warning: include(): Failed opening '/Applications/MAMP/htdocs/tracks/wp-content/themes/mixovery/single_mix_alt.php' for inclusion (include_path='/Applications/MAMP/htdocs/tracks/wp-content/plugins/wordpress-seo/vendor/yoast/api-libs/google:.:/Applications/MAMP/bin/php/php5.4.10/lib/php') in /Applications/MAMP/htdocs/tracks/wp-content/themes/mixovery/base.php on line 46

Something wrong happens in the base.php at this line:

<?php include Wrapper\template_path(); ?>

I looked at the Sage documentation but I found resources on how to change the base.php which is not my case.

Anyone has an idea where I’m wrong or how I should implement this?

Thanks in advance for any help :slight_smile:
Giulio

Is your template in the /templates/ folder, because if so you need to modify.

$template = dirname( __FILE__ ) . '/single_mix_alt.php';
to
$template = dirname( __FILE__ ) . '/templates/single_mix_alt.php';

Also you may want to try get_template_directory instead of what your using to get the path to your file. I’m assuming no child theme because it’s sage.

Correct me if I’m wrong but I believe the best way to get your path is.

$template = get_template_directory . '/templates/single_mix_alt.php';

Thank u for yr support RiFi2k. That fixed the problem :slight_smile:

1 Like