WordPress Redirect from Custom Template

5.8k Views Asked by At

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).

  1. I tried to catch that in functions.php with add_action('wp_redirect','function');, but it is too early as global $template; is still empty / the customtemplate.php is not loaded yet
  2. When I do it in customtemplate.php it is too late to use wp_redirect(); as the headers are already out there

It'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.

2

There are 2 best solutions below

1
On BEST ANSWER

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?

4
On

you should do it with the hook 'template_redirect' here is an example:

add_action( 'template_redirect', function () {
    if ( ! is_page() ) {
        return;
    }
    $page_id = [
        1 ,3 ,4 //add page ids you want to redirect 
    ];
    if (is_page($page_id) && empty($_GET['whatever'])){
        wp_redirect(home_url());
    }
});

i suggest you to search and read wordpress documentation about is_page function and template_redirect hook