WP-Mix

A fresh mix of code snippets and tutorials

WordPress enqueue user-agent stylesheets

WordPress makes it clean and easy to enqueue custom stylesheets via the functions.php file. Here’s how to do it for user-agent stylesheets.

To deliver custom stylesheets to specific user-agents, add the following code to functions.php:

// Enqueue user-agent stylesheets
// Enqueue styles @ https://wp-tao.com/608
function wpmix_enqueue_styles() {
	global $wp_styles;
	if (!is_admin()) {

		// ua vars
		global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

		// mozilla
		if ($is_gecko) {
			wp_register_style('mozilla', get_template_directory_uri() .'/mozilla.css', false, null);
			wp_enqueue_style('mozilla');
		}

		// safari
		if ($is_safari) {
			wp_register_style('safari', get_template_directory_uri() .'/safari.css', false, null);
			wp_enqueue_style('safari');
		}

		// ie
		if ($is_IE) {
			wp_register_style('ie', get_template_directory_uri() .'/ie.css', false, null);
			wp_enqueue_style('ie');
		}
	}
}
add_action('wp_print_styles', 'wpmix_enqueue_styles');

This code basically grabs the WP-generated variables for IE, Opera, and other supported browsers, and then registers and enqueues a browser-specific stylesheet accordingly. So create a custom CSS file for each of your targeted browsers and/or remove the enqueue for any that aren’t required. Similar logic may be used to enqueue user-agent JavaScript and other resources. For more infos and options, visit the WordPress Codex:

Bonus

If you need more control over specific browsers, here is a snippet of jQuery code to get you started:

// Naughty browser sniffing via jQuery
$(document).ready(function(){
	if($.browser.webkit) {
		$('html').addClass('webkit');
	} else if($.browser.mozilla) {
		if($.browser.version >= '17.0') {
			$('html').addClass('mozilla');
		} else {
			$('html').addClass('mozilla-older');
		}
	} else if($.browser.opera) {
		$('html').addClass('opera');
	}
	$.browser.camino = /camino/.test(navigator.userAgent.toLowerCase()); 
	if ($.browser.camino) { 
		$('html').addClass('camino');
	}
});

Lots of folks will tell you NOT to do this, and I can’t say I disagree, but it’s a useful technique nonetheless. Note that there is probably a more efficient way of writing this snippet, or you could even use a script like modernizr for much more. Either way, the goal here is to provide options for you, the discerning individual, to find suitable solutions.

Learn more

WordPress Themes In Depth