Easy mobile site redirection with WordPress

Using WordPress and cookies, we are going to build a redirection script that will give the visitor the ability to view the full site or the mobile site with ease. A common problem when adding a redirection is that when visitors click back to the full site, they’re redirect back to the mobile site in an infinite loop.

The Theory:

When a visitor loads the website we will use WordPress to set a cookie, that last 10 mins. Then when loading the site we will check if the cookie is set and redirect only if the Cookie is not set (ie. When first loading the site or revisiting after 10 min).

That way if the visitor chooses to go back to the full site, the cookie will still be set and the redirect script will not be activated.

The Code:

To set a cookie in WordPress we can add a new function to the themes function file (functions.php) and add an action to run the new function when a visitor loads the site.

function set_new_visitor_cookie() {
	if (!isset($_COOKIE['sitename_newvisitor'])) {
		setcookie('sitename_newvisitor', 1, time()+600, COOKIEPATH, COOKIE_DOMAIN, false);
	}
}
add_action( 'init', 'set_new_visitor_cookie');

This will now add a cookie ‘sitename_newvisitor’ that lasts 10 min (you can adjust the time()+600 to how many seconds you need) and can be checked for when loading the site. Next we will add the following code to the header section of the theme (header.php) and this will only execute if the cookie is not set.

<? if (!isset($_COOKIE['sitename_newvisitor'])) {
     echo '<script type="text/javascript">
<!--
if (screen.width <= 740) {
document.location = "http://m.sitename.com.au/";
}
//-->
</script>';
} ?>

The Javascript above is a basic redirect script that is checking if the device screen width is less than 740 pixels and changes the document location if it returns true. the method will still work if you have your own redirection script that checks the visitors useragent, but with so many devices available I only check screen width to redirect smartphone devices.

You need to change the redirection url in the code above to point to your mobile site and on your mobile site have a link back to your site url and it will not loop. If the visitor loads the site again they will get the full site. If they visit again after 10 minutes they will get redirected to the mobile site again.