Mobile Device Detection & Redirection

October 14, 2010 - By

It’s hard to believe, but is over eight years old, and on its ninth iteration. Since using this CMS I haven’t actually worked on the site itself until recently when I decided to make my foray into mobile web.

Mobile web surfing is on the rise, even my analytics show that 5 – 10% of my site traffic is on itty bitty screens! My job as a web designer and my trusty Android phone have thrust me deep into mobile web consciousness. Naturally I was soon in a quest to make a mobile friendly version of my own site.

WordPress has a lot of plugins to help you switch your theme with mobile detection, but I wanted to give the user a completely different experience with different content than my “desktop” site. I imagined networking with someone in person; and exchanging URLs. When someone looks up my site on a device, I would think it would often be to complete a simple task: to jog their memory, to network or find my contact info. It just seems less likely that the majority of my mobile audience are going to dig deep into my seemingly endless blog. I wanted to give that mobile user the succinct user experience that would be most convenient. A lot of this inspiration about the context of my traffic came from Cameron Moll’s book Mobile Web Design.

As with anything I’m sure device detection can be done in several different ways. After doing some research and some trial and error with other scripts and plugins I found Andy Moore’s Detect Mobile Browsers PHP script. It will detect the device type and can do some simple redirect and cookies. It wasn’t perfect though.

The site said the script can handle the “View Desktop” logic and overwrite the cookie, but it wasn’t working for me! I wanted redirected users on mobile to be able to still visit my desktop site; but the detection and redirection was too good! Using a little PHP before my doctype in the header.php include I was able to add this functionality myself. I never write code off the top of my head, so this is a rare moment indeed:

[cci lang=”php”]


The only thing to add now to make it work is adding the link to the mobile site. On I added the “View Desktop” link and I appended a ?switch=0 to the end of the href. When the link is followed the above code looks at the URL; if “switch” has a value it sets a cookie, otherwise if there’s no cookie and no switch value, it runs the device detection and redirects if applicable. Cinchy!

This is just one of many ways to deal with this. I hope my little code finagling helps someone out there.

Categorized in:

This post was written by ArleyM