How to Detect a Visitor’s Browser in WordPress

There are times when you may need to deliver specific content or adjustments based on the web browser your site visitors are using. Various methods can help you achieve this. For instance, you can use the JavaScript BrowserDetect.browser function or comment tags targeting Internet Explorer.

Modernizr is another useful tool for browser feature detection. Although CSS3 media queries aren’t designed to identify browser types, they can be helpful for optimizing website presentation on mobile devices.

60+ Most Wanted WordPress Tricks and Hacks (Updated)

60+ Most Wanted WordPress Tricks and Hacks (Updated)

Have you ever came across a WordPress blog, saw something you liked, and thought; how they did that,... Read more

Using PHP for Browser Detection

While the above methods modify the front-end, the actual HTML markup remains the same. For example, if you have two <div> elements—one for Internet Explorer and another for other browsers—both will exist in the HTML document, regardless of the browser used.

In cases where front-end methods aren’t sufficient, server-side languages like PHP offer a more robust solution. For WordPress users, the PHP Browser Detection plugin makes this task easier.

Conditional Functions in PHP

Upon activation, this plugin doesn’t show anything in the WordPress Dashboard. Instead, it offers conditional functions that you can use in your theme files like page.php or index.php. These functions can detect various desktop and mobile devices, including iPads and iPhones.

Basic Implementation

For example, if you want to display a notification only to Chrome users, you can add the following code in your header.php file, within the <body> tag:

<?php if ( is_Chrome() ) {  
$browserInfo = php_browser_info();
$browser = $browserInfo['browser'];
$version = $browserInfo['version'];

echo '<div class="browser-notification">You are using ' . $browser . ' ' . $version . '. Please update your browser for a better experience.</div>';
} ?>

In contrast, users of other browsers like Firefox, Opera and Safari will not see this notification.

No Markup for Other Browsers

Similarly, you can target mobile devices to optimize your WordPress site’s performance. For instance, you can serve lower-resolution images on mobile devices and higher-resolution images on desktop browsers by adding the following function to your index.php file:

<?php if ( is_mobile() ) { 
	the_post_thumbnail( 'small' );
} else {
	the_post_thumbnail( 'large' );
} ?>

For more details and examples, visit the WordPress.org plugin page.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail