現在手機行動裝置越來越普及,也越來越智能,使用手機瀏覽網頁已經比較流行了,所以,身為WordPress主題開發者,你必須好好考慮如何應對手機行動用戶了。
這是一段php通用的判斷行動瀏覽器的函數,原理比較簡單,就是判斷瀏覽器回傳的user_agent,條件包含手機系統、品牌和視窗大小。
以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() ): ?> //如何如何..(这里可以添加一个mobile.css,如<link rel="stylesheet" type="text/css" media="all" href="http://www.jqueryba.com/"<?php echo get_template_directory_uri(); ?>/mobile.css" />) <?php endif ;?>
還需要注意的一點:不管是單獨的WordPress主題還是自適應主題,都需要在頭部將添加下面meta,否者可能導致手機顯示字體過小等問題。
<meta name="viewport" content="width=device-width"/>
更多wordpress相關技術文章,請造訪wordpress教學欄位進行學習!
以上是wordpress如何判斷是否為手機行動裝置的詳細內容。更多資訊請關注PHP中文網其他相關文章!