Sometimes we need to serve specific content or tweak to certain Web browsers. There are several ways to do so. For example, we can use the JavaScript BrowserDetect.browser function. We can also use the following comment tags to exclusively target Internet Explorer.
Modernizr is useful for feature detection of the browsers, so that we are able to patch the functionalities that are not supported. We can also use CSS3 media query, though it is not designed to retrieve browser information, it is useful to address the website presentation particularly in mobile browsers.
PHP Browser Detection
However, all of those methods are only altering the front side, while the actual content in the document’s markup remain unaffected. Say, we have two <div> elements one for Internet Explorer, and one for the other. These two elements will actually remain on the document regardless of the browsers.
In some cases, these methods might not be the ideal solution. So, the only viable option would be to use the server-side language, like PHP. If you are using WordPress, there is an easy to do so with a plugin called PHP Browser Detection.
Conditional Functions
When this plugin has been activated, it will give you nothing in the Dashboard. Instead, it provides several conditional functions to use in your theme files – such as page.php, index.php and others. It allows detection in all popular desktop and mobile devices – such as iPad and iPhone.
Basic Usage
Let’s see some usage examples. Say, we want to show notification only to Internet Explorer users. We can write something like this inside the header.php under the <body>.
With a few style adjustment in the stylesheet, Internet Explorer users will see the following.
But, when we see it in other browsers – Firefox, Opera, Safari and Chrome– the notification markup is not generated.
As mentioned, we can also target for mobile devices, which is very useful to optimize your WordPress site on the mobile platform. Assuming that you have enabled the post thumbnail support in your theme, we can add the following function to your index.php to serve lower image resolutions in mobile device, and higher resolutions for desktop browsers.
Those are only a few examples, head over to the WordPress.org page to see about this plugin in more detail.