使用wordpress建自适应网站时,要想在PC端网站与手机移动设备端网站显示不同的内容,就需要判断当前浏览设备是否为手机移动设备。如果是手机移动设备,跳转手机版,显示一套手机移动设备内容,否则,显示一套PC端网站版面。
wordpress 代码判断手机移动设备
WordPress可以通过纯代码的方法去判断跳转手机版并跳转,步骤如下:
第一步:在自己网站主题的 functions.php 内加上如下代码,目前已包含常见移动浏览器的useragent,基本上可以涵盖可能会用手机上网的用户群了。
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 ;?>
通过以上二步,我们就可以通过代码来判断手机移动设备并跳转手机版了。