Web Development & WordPress

Check if it is mobile then show something : wordpress template php code

For coders sometimes it is needed to show something only for mobile in template fiile. So here is the coding

for functions.php file

function is_mobile_device() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $mobile_agents = ['Android', 'iPhone', 'iPad', 'iPod', 'Windows Phone', 'BlackBerry'];
    
    foreach ($mobile_agents as $agent) {
        if (stripos($user_agent, $agent) !== false) {
            return true;
        }
    }
    return false;
}

in template file ( like single.php, page.php etc)

 <?php
 
  $is_mobileb = wp_is_mobile() || is_mobile_device();
  if( $is_mobileb){ 
    
?> 
YOUR CODE WILL GO HERE 

<?php } ?>

Leave a comment