前言

目前使用手机或平板浏览页面越来越普遍,这就要有必要给自己网站做一个手机主题,但是如果要使用手机主题,就必须进行判断,判断是否为手机用户,如果是,返回移动端页面,如果否则返回正常PC端页面。下面这个PHP函数,可以用来判断客户端类型,从而确定输出的页面类型。

自定义函数

在functions.php内加入如下代码

/*判断是否移动端访问*/
function is_mobile() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $mobile_browser = Array(
        "mqqbrowser", //手机QQ浏览器
        "opera mobi", //手机Opera
        "juc","iuc",//UC浏览器
        "fennec","ios","applewebKit/420","applewebkit/525","applewebkit/532","ipad","iphone","ipaq","ipod",
        "iemobile", "windows ce",//windows phone
        "240x320","480x640","acer","android","anywhereyougo.com","asus","audio","blackberry","blazer","coolpad" ,"dopod", "etouch", "hitachi","htc","huawei", "jbrowser", "lenovo","lg","lg-","lge-","lge", "mobi","moto","nokia","phone","samsung","sony","symbian","tablet","tianyu","wap","xda","xde","zte"
    );
    $is_mobile = false;
    foreach ($mobile_browser as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}
函数调用

条件判断,在调用时返回不同的页面内容

<?php if (is_mobile() ): ?>
    // 移动端输出内容
<?php else: ?>
    // PC端输出内容
<?php endif; ?>