How to redirect to its mobile page when mobile devices access the front page or homepage in WordPress

Redirect to mobile page in WordPress using hook

Since most WordPress themes are responsive, no special changes are needed for mobile devices in most themes. You can modify the layout for mobile devices using media queries (CSS.)

Adding a user code to header.php

You might want to create a mobile page and this page will be loaded for mobile devices. In other words, you might be able to create a separate page for mobile (apart from the default page for PC.) In this case, you can use the wp_is_mobile() function.

For example, you create a page whose name is mobile. You want to redirect to this page for mobile devices. For this purpose, you can place the following code on top of the header.php file.

// For users with mobile devices, the following code will redirect them to http://www.example.com/mobile
<?php
if ( wp_is_mobile() && (is_home() || Is_front_page()) ) {
$url = home_url( 'mobile', 'relative' );
wp_redirect( $url);
exit;
}
?>

On the front page or homepage in WordPress, users with mobile devices will be redirected to http://user_site_url/mobile. Of course, you can use header('Location: http://user_site_url/mobile'); instead of  wp_redirect. Please refer to this WordPress Codex page for wp_redirect.

The better method: Using the wp_print_scripts hook

For your reference, you can implement this feature without editing WordPress theme file if you use a filter or action such as wp_head. However, the wp_is_mobile() function does not work with the wp_head action. In this case, you can use the wp_print_scripts action. Please refer here for the action wp_print_scripts.

// Redirect to its mobile page when users access the front page or homepage using mobile devices
function deque_my_scripts () {
if (is_home() || is_front_page()) {
$url = home_url( 'mobile', 'relative' );
wp_redirect( $url);
exit;
}
}

if (wp_is_mobile())
{
add_action('wp_print_scripts','deque_my_scripts');
}

Like this, you can easily redirect mobile users to its mobile page without any other scripts if you use wp_is_mobile().


Leave a Comment