You can use the built in function wp_is_mobile()
Override a style with wp_enqueue_style
add_action('wp_enqueue_scripts', 'my_mobile_styles');
function my_mobile_styles(){
if(wp_is_mobile()){
wp_register_style( 'my-mobile-style', 'URL_to_stylesheet', array('id-of-main-stylesheet') );
wp_enqueue_style( 'my-mobile-style' );
}
}
Switch themes by filters
You can use the stylesheet
and template
filters to alter which theme WordPress will render.
# Parent Theme
add_filter( 'template', 'my_mobile_template', 99999, 1);
function my_mobile_template($template){
if(wp_is_mobile())
return 'mobile_template_dir_name';
return $template;
}
# Parent or Child Theme (if applicable)
add_filter( 'stylesheet', 'my_mobile_stylesheet', 999999, 1);
function my_mobile_stylesheet($stylesheet){
if(wp_is_mobile())
return 'mobile_stylesheet_dir_name';
return $stylesheet;
}
Isolating to a mobile user-agent
You can further extend this by using the following extracted from wp_is_mobile() within your conditional IF statement brackets.
$is_ios = strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile');
$is_android = strpos($_SERVER['HTTP_USER_AGENT'], 'Android');
$is_silk = strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/');
$is_kindle = strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle');
$is_blackberry = strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry');
$is_opera_mini = strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini');
From there, you can enqueue styles that override your main theme.
Caveat
It’s important to note there is a function called switch_theme()
which is not to be used for this case. It literally changes the theme and stylesheet location in the database. switch_theme()
would change your theme to the mobile version for all users whenever a mobile user-agent is detected.
Testing
I typically use some browser extensions that alter the browser user-agent definition for testing something like this. Here are some links to the ones I’ve used:
- Chrome – User Agent Switcher
- Firefox – User Agent Switcher
Hope this helps you out!