3

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.

ssstofff
  • 638
  • 1
  • 10
  • 19

2 Answers2

3

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?

vdwijngaert
  • 1,515
  • 11
  • 24
  • this is it! works perfectly set in functions.php. The use is with IoT application where we need the querystring value ... otherwise back to hp. the IoT is applied on pages only being that template. – ssstofff Nov 30 '19 at 21:17
2

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

Shalior
  • 418
  • 5
  • 9
  • i tried to use the template_redirect, but it's not possible to hard code the page id's as the future page id's that will use the customtemplate.php are not known ... – ssstofff Nov 30 '19 at 10:23
  • you can use is_page_template() function to check if page is using that template https://developer.wordpress.org/reference/functions/is_page_template/ – Shalior Nov 30 '19 at 10:32
  • I tried that in functions.php, the value is always empty – ssstofff Nov 30 '19 at 11:04
  • note that is_page_template() returns true or false not a value. use function like this : if(is_page_template('customtemplate'))... – Shalior Nov 30 '19 at 14:04