Switching between two WordPress themes for mobile sites and Batcache
Fellow WordPress developer James Collins blogged about the wp_is_mobile() function which is a handy core function you can use for mobile detection (betcha you’d never have guessed that!).
I actually don’t think I’ve ever used it, but I have used a home grown function that was done with Mark Jaquith on a project. I thought I’d share what I did to have the mobile detection work and how we toggle between the two themes, and batcache doesn’t go nuts and cache the wrong stuff for the wrong people.
The entire use case is to show one theme for desktops, and if mobile, show a different theme, and also throw in a toggle link to switch between the two sites. This works with batcache, and you’ll see how below.
This little bit of code sits in wp-config.php
The reason it gets defined here is because we’ll reference it within batcache, and that runs before plugins and such.
Within batcache, around line 175, you want to add this in, so Batcache knows to create two extra cache ‘groups’. One for mobile, one for mobile users that actually want the desktop version, and the default being the desktop version.
Finally, you need to run this (I run it as a must-use plugin) so it can swap the theme if it’s a mobile user, or show the desktop theme if it a mobile user, and they want to see the desktop version.
This all works well on a number of sites where we have an m-site and a normal site (Yes, I’m aware responsive is an option, but not suitable for what I did this on).
If you run nginx caching over the top, that’s not too big of a deal either.
Where you set your caching stuff in your sites nginx config files, you’ll need something like this.
This tells php-fpm / nginx not to serve cached (desktop) pages and display them to mobile users. The mobile users will get a nicely cached batcache page!