phpwordpresscustom-theme

WordPress Redirect from Custom Template


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.


Solution

  • 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?