Search code examples
phpjqueryhttp-redirectmobileback

Redirect a user if on mobile device (not tablet) but provide back link


This is completely new to me and haven't a clue what I'm doing so I would really prefer a simple to implement solution (if it exists).

I need to redirect users who visit www.domain.co.uk (hosted on Wordpress) on mobile devices (not tablets) to a specific page like this (with WP's permalinks):

www.domain.co.uk/mobile-home

From that mobile page, I also need to provide a link back to the desktop homepage on the same domain, like this:

www.domain.co.uk/desktop-home

I had been playing with code similar to this in my header.php file:

<script>if( 'ontouchstart' in window ) window.location = 'mobile.html';</script>

but it will just redirect a mobile user back to the mobile version if I link directly to the desktop page. How can I get the functionality I require?

UPDATE

Ok, my first step is to direct my mobile visitors to the mobile page. So I have pasted the following code into my page template of the homepage for my website and tested seems to work. I've put it just beneath the opening 'body' tag:

<script>
if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile/i.test(navigator.userAgent) ) {
window.location = "176.32.230.17/domain.co.uk/m";
}
</script>

Now I'm having trouble linking back to the homepage using the below code. It takes me back to the hompage but the homepage has the code above detecting the device and keeps taking me back to the mobile site. Am I putting the device detection in the right place?:

<a href="http://176.32.230.17/domain.co.uk/?ref=desktop">Link back to desktop website</a>

Solution

  • So from using @Phillip's code I have managed to come up with a complete solution to my question.

    I place the following JS in my header.php template to detect if user agent is a mobile device, if is then perform another check to see if the URL contains the hashtag '#desktop', if it does, do nothing and keep user on desktop version. If it doesn't then redirect to mobile website:

    JS

    <script>
    if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile/i.test(navigator.userAgent) ) {
    
    if(window.location.hash == "#desktop"){
        // Stay on desktop website
    } else {
        window.location = "http://www.domain.co.uk/m";
    }
    
    }
    </script>
    

    Then to complete the loop, add a link on the mobile site that adds the hashtag '#desktop' to the URL ensuring they don't get redirected back to the mobile version automatically:

    <a href="http://www.domain.co.uk/#desktop">View desktop site</a>