让wordpress根据用户访问设备智能地在电脑端和移动端主题之间切换

这是一个小插件,就一个文件,根据用户设备的USER AGENT来做判断,如果是移动设备则wordpress展示移动主题,如果是电脑,则展示电脑主题。事先你需要在theme目录下放好两个主题文件夹以备启用。

代码如下:

<?php
/*
Plugin Name: 移动端主题切换
Plugin URI: http://redren.net
Description: 根据用户访问设备,智能地在电脑端和移动端主题之间切换
Version: 1.0.0
Author: David Zhang
Author URI: http://redren.net/
*/
if (!function_exists('theme_Mobile')) {
    function theme_Mobile()
    {
        //判断手机发送的客户端标志
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'opera mobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", $userAgent) && strpos($userAgent, 'ipad') === false) {
                return true;
            }
        }
        return false;
    }
}
function angela_switch_theme($theme)
{
    if (theme_Mobile()) {
        $theme = 'sparkling-mobile';
    }
    return $theme;
}
add_filter('template', 'angela_switch_theme');
add_filter('stylesheet', 'angela_switch_theme');

演示可以看 http://www.99ayi.com 网站在社区部分针对移动端做了更多的美化。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注