WordPress custom functions help

How do I transform this code to work in WordPress? I need to use the if statements in the theme template files:

function iOSDetect() {

 global $device;
 $browser = $_SERVER['HTTP_USER_AGENT'];
 if(strstr($browser, 'iPhone') || strstr($browser, 'iPod')) {
     $device = 'iPhone';
  } else { $device = 'default'; } 

}

iOSDetect();

if($device == 'default') {
 // Do something
} else { /* Do something else */  }

Related posts

Leave a Reply

2 comments

  1. try it this way:

    $device = '';
    
    iOSDetect();
    
    if($device == 'default') {
     // Do something
    } else { /* Do something else */  }
    

    Or, you can use a better way:

    function iOSDetect() {
    
     global $device;
     $browser = $_SERVER['HTTP_USER_AGENT'];
     if(strstr($browser, 'iPhone') || strstr($browser, 'iPod')) {
         $device = 'iPhone';
      } else { $device = 'default'; } 
      return $device;
    }
    

    and then, use it this way:

    if(iOSDetect() == 'default') {
     // Do something
    } else { /* Do something else */  }
    
  2. It looks like you’ll just call the function once, so it’s not like you really need it to be a function.

    Also, that looks like kind of a global vars abuse to me.

    $browser = $_SERVER['HTTP_USER_AGENT'];
    if(strstr($browser, 'iPhone') || strstr($browser, 'iPod')) {
       $device = 'iPhone';
    } else { 
       $device = 'default'; 
    } 
    if($device == 'default') {
       // Do something
    } else { 
       // Do something else 
    }
    

    BTW, if the thing to do is just one (loading different css/js files) you can simplify:

    $browser = $_SERVER['HTTP_USER_AGENT'];
    if(strstr($browser, 'iPhone') || strstr($browser, 'iPod')) {
       //load iphone files
    } else { 
       //load standard files 
    }