Today blog and website designs have one important aspect, responsive layout. Responsive design is where a website layout adjusts itself to the device from which it is being viewed. So as a webmaster, it is tough job to add elements like advertisement or other codes to a responsive design as it might just break up. For example, you want to show a particular advertisement only when website is viewed on desktop and rest all cases you want to skip the ad. In such cases how do we detect the device from which is being viewed and hide the code?
In such cases, Mobile_Detect will be of great help. It is a lightweight PHP class for detecting mobile devices. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.
Using the code, you can detect all the popular mobile and tablet browsers. You can even write separate code for iOS, Android etc which means these code will be executed based on the condition. The script is as reliable as server-side detection can be. This is not a replacement for RWD (media queries) or other forms of client-side detection.
You can also check for certain phones, like isiPhone() fetches whether the website is opened from iPhone. There are quite a lot of options available and you can view the complete list here.
How to Use this Code:
The usage of the code is pretty simple, download the Mobile_Detect class file from here and upload it your theme directory. Now you can simply call the class anywhere in the php code.
<?php
include 'Mobile_Detect.php'; $detect = new Mobile_Detect; // 1. Check for mobile environment. if ($detect->isMobile()) { // Your code here. } // 2. Check for tablet device. if($detect->isTablet()){ // Your code here. } // 3. Check for any mobile device, excluding tablets. if ($detect->isMobile() && !$detect->isTablet()) { // Your code here. }
Here the code gets the device and then executes the If condition based on it. You can find typical use cases here.
If you are using WordPress blog, you can check out the WP Mobile Detect plugin which uses this class, which means you do not have to manually write the code.
The PHP class is really helpful in executing the code based on the device on which it is being opened. We tested it on a WordPress site and it worked perfectly.
You can download Mobile Detect from here.
Is it better than what we use to identify screen sizes in CSS? Just wanted your consent over this.
You can identify screen size using CSS, but you cannot execute conditions based on it, I meant scripts.
Use CSS media queries for document layout and content adaptation but use Server-Side detection for serving less or different JavaScript/CSS/HTML content for mobile devices.
Is it better than what we use to identify screen sizes in CSS? Just wanted your consent over this.
Is it better than what we use to identify screen sizes in CSS? Just wanted your consent over this.