WordPress Redirect to other page if cookie is set

What this code do? – In this example the PHP code is checking is certain WordPress page loaded by a visitor of your WordPress website and setup a cookie with expiry time (1 year in example). If the visitor reload the page or try to load the page again in the future (before the cookie expire), will be redirected to other page.

Use cases:

  • limit access to page and it’s content for certain page views
  • redirect to other page if views limit is reached

How to setup the code?

  1. Paste this code snippet in functions.php in your active theme;
  2. Replace YOUR_PAGE_ID with the id of the landing page;
  3. Replace YOUR_REDIRECT_PAGE_ID with the id of the page where you want to redirect the user if cookie is detected;
  4. Set expire time of your cookie by changing the numbers in $lockdown_time;
  5. Redefine cookie options by changing data in array $cookie_options. (How to setup cookie options);
  6. Save and Go.
<?php

/**
 * WP redirect to other page if cookie is set on certain page
 */

global $page_to_access, $page_to_redirect, $view_limits;

/// SETUP PAGE by setting page ID
$page_to_access = (int) 7432; // page to trigger cookie set
$page_to_redirect = (int) 7537; // page to redirect if cookie is set
$view_limits = 5; // number of page views before redirect

add_action('wp', 'smpl_cookie_set');
function smpl_cookie_set() {
    global $page_to_access;
    $view_count = 0;
    $lockdown_time = 60 * 60 * 24 * 365; // set your desired expiry time
    $cookie_options = array(
        'expires' => time() + $lockdown_time,
        'path' => '/',
        'domain' => $_SERVER['SERVER_NAME'],
        'secure' => true,     // or false
        'httponly' => true,    // or false
        'samesite' => 'Strict' // None || Lax  || Strict
    );

    // set cookie if page is visited
    if( !isset($_COOKIE['smpl_visit_time']) && is_page($page_to_access) ) {
        $view_count++;
        setcookie('smpl_visit_time', $view_count, $cookie_options);
   
   // cookie is set, but update view count
   if(isset($_COOKIE['smpl_visit_time']) && is_page($page_to_access) ) {
        $view_count++;
        setcookie('smpl_visit_time', $view_count, $cookie_options);
   }

}

// Check the page and if cookie exist and redirect to other page
add_action('template_redirect', 'smpl_check_cookie', 10);
function smpl_check_cookie() {
    global $page_to_access, $page_to_redirect, $view_limits;

    // Check if cookie is already set
    if(is_page($page_to_access) && isset($_COOKIE['smpl_visit_time']) && $_COOKIE['smpl_visit_time'] == $view_limits ) {
        wp_redirect( get_permalink($page_to_redirect) );
        die();
       
    }
}
Share: Facebook, Twitter, Google Plus

Leave a Comment: