Sometimes you want to detect new users on your site versus returning visitors and display different sorts of information to them. An easy way to do this is to set a cookie.
If you’re doing this via a theme, add this line to your functions.php file:
<?php
/**
* Sets a cookie sitename_new_visitor if it doesn't exist already.
*/
function example_set_new_user_cookie() {
if ( ! is_admin() && ! isset( $_COOKIE['sitename_new_visitor'] ) ) {
setcookie( 'sitename_new_visitor', 1, time() + 3600 * 24 * 100, COOKIEPATH, COOKIE_DOMAIN, false );
}
}
add_action( 'init', 'example_set_new_user_cookie');
You can read more about the setcookie function at PHP.net. This will set a new cookie named “sitename_newvisitor” with a value of 1 which is set to expire in two weeks.
To display different information to a returning user vs a new user, you could do something like this:
/**
* Displays a different message based on whether the sitename_new_visitor cookie is set or not
*/
if ( isset( $_COOKIE['sitename_new_visitor'] ) ) {
echo 'Welcome back!';
}
else {
echo 'Hello new visitor!';
}
Also, be aware, if your site has heavy caching, reading and setting the cookies may not work.