WordPress Helper Functions for Detecting IE
The other day I was working on a problem where I wanted to check if a website was using a specific browser (in this case IE) and version (in this case 9 or below). I came up with 2 functions that would serve an a nice, reusable check for both. These can also be extended to check for other browsers or versions, or even accept custom regular expressions.
Before I get started, it’s worth noting that WordPress actually has built-in checks for these already: WordPress Browser Detection Booleans. I used these in conjuction with a function I wrote to detect “old” versions of IE:
function jlc_is_old_ie() { global $is_IE; return ( $is_IE && jlc_get_ie_version() <= 9 ); }
This function uses a combination of WordPress' built-in $is_IE
and use of another function that I wrote to grab the version from the user agent, with help from this WPBeginner tutorial.
function jlc_get_ie_version() { preg_match( '/MSIE ([0-9]+)([a-zA-Z0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $version_no ); return $version_no[1]; }
This looks for MSIE
before a number or letter and numbers and returns the number/letters and numbers found. It's worth noting that this only works for older versions (pre-11) IE. That uses the term Trident
in it as well as "Mozilla," but as this blog post points out, User Agent (UA) isn't always the best method. I use it here for 2 reasons: I wanted to specifically target older versions of IE and I'm not changing any specific features; I'm added classes to the body and displaying a message to older browsers that, "Hey, things will definitely look weird for you."