Detecting Mobile Phone Browsers in WordPress

Better Detection

Today I’m going to share a neat little function with you that will help detect mobile browsers. More specifically, mobile phones. You may be saying to yourself, there’s already a function built into core to detect when a user is browsing your site on mobile devices, and you are correct. There is a function. That function is:

But wp_is_mobile(); detects all mobile browsers, and sometimes we need to target phones. This happens more often than you think, especially now that mobile browsing is taking over. Just the other day at work we wanted some content on the page to be accessible through a fly down modal only on mobile devices. On tablets and desktops we wanted it to remain in a content container in the sidebar. Using wp_is_mobile(); worked, but it targeted tablets which we didn’t want.

Using the function provided below, we were able to only target mobile phones while leaving tablets and desktop browsers unchanged.

Detecting Mobile Phone Browsers in WordPress

I’m just going to provide the code here and explain how to use it further down, for anyone who needs some direction. Here is the function:

So what you want to do with this function is drop it directly into your themes (or child themes!) function.php file. After it’s in there, save the file and you can begin using it any where. You can use the function by doing the following:

And that’s all! Now you can target only mobile devices at ease! Comment if this was helpful and, as always, Enjoy!

About the Author

Evan Herman

Evan is a full time WordPress developer at Yikes Inc. where he makes all sorts of cool things with WordPress. When he's not there you can find him developing awesome plugins, blogging about WordPress or hanging out with his three cats and amazing girlfriend in Philadelphia, PA.