This is a simple function that will allow you to set a cookie when a visitor first lands on a specific page. Any subsequent visits before the cookie’s expiration will then redirect the user from the original page to an alternate url.

There are two parts to understand about this gist. The first if statement determines the qualifying factors for setting the cookie.

if ( !is_admin() && !isset($_COOKIE['sitename_newvisitor']) && is_page(106) && !current_user_can('manage_options'))

There are four separate statement that all need to be true in order for the entire statement to be true. The user must not be on the admin dashboard (!is_admin()), the user must not already have the cookie (!isset($_COOKIE[‘sitename_newvisitor’])), and the user must be on the specific page ( is_page(106)), and the user must not be an administrator on the site (!current_user_can(‘manage_options’))).

If all four of these conditions are true, the cookie will be issued.

setcookie('sitename_newvisitor', 1, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);

The cookie’s name is “sitename_newvisitor”, value is 1, and the expiration is set for the current time + 100 days. The time() function measures the current time in seconds, and we’ve added 100 days worth of seconds: 3600 (the number of seconds in one hour) * 24 (the number of hours in a day) * 100 (the number of days we want the cookie to be valid for).

You can edit the name and expiration of the cookie to anything you like.

The second conditional statement checks if the cookie we created earlier exists.

if (isset($_COOKIE['sitename_newvisitor']))

If it returns true (the visitor has the cookie), it will redirect the user to a url.

wp_redirect( 'https://google.com' );

You can change the url to anything you would like.

Hope this is a helpful gist for WordPress users out there. It’s useful in landing pages, member’s pages, and a bunch of other situations. Comment if you’ve been able to use it or have a suggestion to update it.

Start talking about it!