Skip to content

Instantly share code, notes, and snippets.

@joeydi
Last active December 25, 2015 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeydi/7016878 to your computer and use it in GitHub Desktop.
Save joeydi/7016878 to your computer and use it in GitHub Desktop.
Redirect mobile users in Wordpress

You can use this function to redirect a mobile user to a different homepage in Wordpress. In practice you would probably want to use a more robust user agent sniffer than the is_mobile() function shown here, such as Mobile Detect.

This code assumes you are using a static page with an ID of 1 for the homepage. If you are using the blog index for your homepage, replace !is_page(1) with !is_home().

If you wanted to not redirect but fetch a different page, you should be able to modify the query_vars on $query, but I haven't tried that.

<?php
function is_mobile() {
$is_mobile = (bool)preg_match( '#\b(ip(hone|od)|android\b.+\bmobile|'.
'opera m(ob|in)i|windows (phone|ce)|blackberry|s(ymbian'.
'|eries60|amsung)|p(alm|rofile/midp|laystation portable'.
')|nokia|fennec|htc[\-_]|up\.browser|[1-4][0-9]{2}x[1-4]'.
'[0-9]{2})\b#i', $_SERVER['HTTP_USER_AGENT'] );
return $is_mobile;
}
function mobile_redirect( $query ) {
if ( !is_main_query() || !is_page(1) || !is_mobile() ) {
return;
}
$mobile_homepage_id = 2;
wp_redirect( get_permalink( $mobile_homepage_id ) );
exit;
}
add_filter( 'pre_get_posts', 'mobile_redirect' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment