【DeveMobile实例】利用Mobile Detect 制作单独移动端页面项目

时间:2022-04-23
本文章向大家介绍【DeveMobile实例】利用Mobile Detect 制作单独移动端页面项目,主要内容包括Mobile Detect 简介、实例介绍、Devework 主题手机版的切换实现、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Mobile Detect 这个PHP 类库Jeff 很早就运用到实际项目中了,如Devework 主题,移动主题、DW Mobile Swither及最近的DeveMobile主题主页

Mobile Detect 简介

Mobile Detect 是一个轻量级PHP 移动设备探测类,它通过HTTP Header 中的User-Agent 字符串来检测移动设备。该PHP 类库最强大的地方是,它有一个非常完整的库,可以检测出所用的设备类型(包括操作类型,以及手机品牌等都能检测)和浏览器的详细信息。

项目主页 Github主页

使用演示:

// Include and instantiate the class. require_once 'Mobile_Detect.php'; $detect = new Mobile_Detect;   // Any mobile device (phones or tablets). if ( $detect->isMobile() ) {   }   // Any tablet device. if( $detect->isTablet() ){   }   // Exclude tablets. if( $detect->isMobile() && !$detect->isTablet() ){   }   // Check for a specific platform with the help of the magic methods: if( $detect->isiOS() ){   }   if( $detect->isAndroidOS() ){   }   // Alternative method is() for checking specific properties. // WARNING: this method is in BETA, some keyword properties will change in the future. $detect->is('Chrome') $detect->is('iOS') $detect->is('UC Browser')

实例介绍

DeveMobile 主题主页pc、移动单独页面的实现

可能你发现DeveMobile主题主页用pc浏览器及在手机上的访问页面是不同的,实现的方法异常简单,就是上面的代码:

if ( $detect->isMobile() ) { include('mobile-index.php'); }else { include('index.php'); }

Devework 主题手机版的切换实现

如果你希望为你的WordPress 主题制作一个附属的手机版本(附属是指文件都是单独在一个主题中且自动切换,而非一个pc端主题+一个手机主题),思路其实可以这样:对单个主题构成文件采用pc端+手机独立的方法,比如说header.php,正常PC 访问就是主题根目录的header.php,移动端访问则为mobile/header.php(即独立另外个header.php)。那么借助Mobile Detect,你可以这样实现(以下部分使用“伪代码”):

比如说heade.php 原来是这样的:

<!DOCTYPE html> ..... ..... <?php wp_head();?> <head/>

那么要按照上面的思路,则为:

<?php if($detect->isMobile())): include('mobile/header.php');else : ?> <!DOCTYPE html> ..... ..... <?php wp_head();?> <head/> <?php endif;?>

以此类推,其他主题文件都是如此。

PS:WordPress虽然有 wp_mobile 这个函数,但这不在本文讨论之列。