javascriptphpwordpressmobile

Redirecting mobile users according to their OS


I need to add a clickable ad banner on my WP site for mobile users so that i can redirect users to the releveant store according to their OS. i.e. redirecting android users to play store, and iOS users to apple store.

Could you please help me do this?

Best regards


Solution

  • Asuming that you want to send to App Store or playstore based on Google Device or android one way to do it would be to add Javascript in header.php of your Wordpress.

    HTML of the Banner

     <a href="#" id="mobile-store-link">
        <img src="YOUR_BANNER_IMAGE_URL" alt="Download App" />
        </a>
    

    Followrd by Script

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var userAgent = navigator.userAgent || navigator.vendor || window.opera;
            var storeLink = document.getElementById("mobile-store-link");
    
            // Define your store URLs
            var playStoreUrl = "https://play.google.com/store/apps/details?id=YOUR_APP_ID";
            var appStoreUrl = "https://apps.apple.com/us/app/YOUR_APP_ID";
    
            if (/android/i.test(userAgent)) {
                // Redirect Android users to Play Store
                storeLink.setAttribute("href", playStoreUrl);
            } else if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
                // Redirect iOS users to Apple Store
                    storeLink.setAttribute("href", appStoreUrl);
                } else {
                    // Fallback if neither iOS nor Android
                    storeLink.setAttribute("href", "#");
                }
            });
    </script>
    

    Do think about responsive banner image. CSS media query can be used to achieve this.