How to add variables to a template
I am using a query argument detail
to check if a custom template should be loaded. This works fine, but I also need to add some variables that can be accessed from within the template. Here I am using add_action('template_include' array($this, 'templateInclude')
:
public function templateInclude($template)
{
if (get_query_var('detail', false) !== false) {
// Check theme directory first.
$newTemplate = locate_template(array('detail.php'));
if ($newTemplate != '')
return $newTemplate;
// Check plugin directory next.
$newTemplate = plugin_dir_path(__FILE__) . 'templates/detail.php';
if (file_exists($newTemplate)) {
return $newTemplate;
}
}
// Return default template.
return $template;
}
The above works, but of course I am not able to actually set any variables for the template.
I tried using set_query_var()
to set a variable that could be accessed using get_query_var()
, but this does not really seem to be the best solution.
I also tried using add_action('template_redirect' array($this, 'templateRedirect')
, which works but this neither seems to be a really good solution:
public function templateRedirect() {
if (get_query_var('detail')) {
$detailId = get_query_var('detail', null);
// Set a variable 'data' that can be used inside the template
$data = get_detail($detailId);
include plugin_dir_path(__FILE__) . 'templates/detail.php';
exit;
}
}
Would be really great if someone has some nice way of adding custom variables for a specific template.