1

I tried the following to redirect one page on the first visit:

function check_for_redirect() {
    if( is_page( 8219 ) )
    $days_to_expire = 30;

    if (!is_admin() && !isset($_COOKIE['already_visited'])) {
        setcookie('already_visited', true, time() + 86400 * $days_to_expire);
        wp_redirect('/welkom', 302); //change the URL and status to whatever you want
        exit;
    }
}
add_action('init', 'check_for_redirect');

I get a Redirect loop if i use this one. How to make this work?

1 Answer 1

1

I would always hook it to template_redirect. Something like this:

add_action( 'template_redirect', 'custom_check_for_redirect' );

function custom_check_for_redirect(){
  global $wp_query; # It could work without this too!
  
  if( is_page( 8219 ) )
    $days_to_expire = 30;

    if (!is_admin() && !isset($_COOKIE['already_visited'])) {
        setcookie('already_visited', true, time() + 86400 * $days_to_expire);
        wp_redirect(home_url('/welkom'), 302);
        exit;
    };

};
2
  • I'd add the recommendation that instead of hardcoding the ID you'd set up an option in your theme where you could assign a page in case you ever change which page you want it to be. As a dev it's easy for you but it's good practice to try and build things so non-development users can work with as many aspects as possible. You could even set the days to expire as an option, etc. Jan 29, 2021 at 19:25
  • 1
    @TonyDjukic Yes that's right! Absolutely.
    – Ruvee
    Jan 29, 2021 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.