Create 2 Wordpress Post Type Templates

107 views Asked by At

I have made a template for my post type, this works great. However I want similar duplication with certain parts of the original.

I have an ajax call using jQuery $.get, I want to target the second post type template to pull the html only into my current page.

At the moment the ajax call loads the entire page including the scripts. Modernizr gets loaded as does the entire content.

I have tried use a query var, like so:

// http://scratch99.com/wordpress/development/how-to-change-post-template-via-url-parameter/

function sjc_add_query_vars($vars) {
    return array('template') + $vars;
}
add_filter('query_vars', 'sjc_add_query_vars');

function sjc_template($template) {
  global $wp;
  if ($wp->query_vars['template'] === 'test') {
    return dirname( __FILE__ ) . '/single-test.php';
  }
  else {
    return $template;
  }
}
add_filter('single_template', 'sjc_template');

The code works well however I get this error

Notice: Undefined index: template in /wp-content/themes/custom--theme/functions.php on line 262

262 is: f ($wp->query_vars):

When the project single is loaded normally I believe this to be an issue when the the code hits the else statement.

Any help would be great.

1

There are 1 answers

0
vaso123 On BEST ANSWER

You've get this error, because your $wp->query_vars is not exists, or if it exists, (than it is actually an array) the template key does not exist. What i did is to check, is the whole $wp->query_vars['template'] thing is exists with the PHP isset() function:

From PHP documentation:
isset — Determine if a variable is set and is not NULL

Read my comments. This is the best explanation from me.

function sjc_template($template) {
    //Now we have a $template variable with a value.

    //Get the $wp as a global variable
    global $wp;

    //This condition is check, is there an existing key in $wp->query_vars 
    //called template. If $wp->query_vars or $wp->query_vars['template'] not 
    //extists (the second can not exists if the first is not exists), 
    //then it will not check, what is the value is, instead of that just jump
    //to the second case to return $template;
    if (isset($wp->query_vars['template']) && $wp->query_vars['template'] === 'test') {
        //So at here, we have this: $wp->query_vars['template'] and the value of it is test
        return dirname(__FILE__) . '/single-test.php';
    } else {
        //In all other cases we return with the given parameter of function
        return $template;
    }
}