In an ideal world, every web page would be built to respond effortlessly to the different devices on which it’s viewed. But sometimes, a design is difficult to wrangle into a format that works well for all devices. In other cases, you are creating mobile versions of pages for an existing site that was not built responsively. In both of the latter situations, WordPress’s “template_include” filter makes it very easy to swap out a custom mobile template for the template WordPress would ordinarily serve for a post or a page. Here’s one way to set it up.

Determine whether the page is being requested by the mobile device you are targeting.

Since version 3.4, WordPress has provided a “wp_is_mobile()” function to help you determine whether the device requesting the page is something other than a desktop computer. However, it returns true for iPads and other tablets that often display pages pretty well without any special treatment.  You may want to turn to the PHP Browser Detection plugin for a set of handy functions that allow you to pinpoint the devices you are targeting for your custom template. Or you may want to build a function yourself. In any case, your first step is to set up the logic to filter for your template’s target devices.

Set up the template_include filter.

In your functions.php file, add the following:

That’s all it takes to load a custom template. WordPress passes the full path to the template for the current page or post to the callback. I’ve used the built-in WordPress function in this example to determine whether to return my custom template or the default template. In all likelihood, you’ll probably use something more specific.


There are lots of ways you can automate this for your particular situation.

  • You may want to set up a naming convention for your mobile templates by prefixing mobile template file names with ‘mobile-‘, for example. In that case, the mobile version of the single post template file (single.php) would be ‘mobile-single.php’. Then, if the logic that checks for your target device returns true, you can add a check to determine whether the mobile version of the default template file exists. If it does, return it. Otherwise, return the default template. Just be careful to parse the template name that is passed to the callback. It’s the full path name, so you can’t just tack the mobile prefix on to the beginning of the string.
  • You may want to use your mobile detection logic to do other things, so it’s a good idea to extract it into its own function. You could use it, for example, in your header.php file to determine which navigation menu to display. Or you could use it in functions.php to determine which stylesheets or javascript files to enqueue.

Let us know how you are using custom mobile templates and the “template_include” filter in your WordPress theme.