I need to redirect a custom template page to Homepage when a querystring key has an empty value.
for ex: https://example.com/customtemplatepage/?value=1 the Customtemplatepage is a page set with a custom template customtemplate.php in the root of the theme.
Whenever the querystring key "value" is empty it needs to be redirected to the root ("/" or homepage).
add_action('wp_redirect','function');
, but it is too early as global $template;
is still empty / the customtemplate.php is not loaded yetwp_redirect();
as the headers are already out thereIt's possible to use JS with window.location
in the customtemplate.php, but that's not an option as we have to do it server side.
The template_include
filter should do the trick.
add_filter('template_include', function ($template) {
// Get template file.
$file = basename($template);
if ($file === 'my-template.php') {
// Your logic goes here.
wp_redirect(home_url());
exit;
}
return $template;
});
Out of curiosity, why redirect to the homepage? Is a 404 not meant for handling non-existent content?