WordPress主题判断手机移动端口设备

秦兽兽 2020-10-02 108 0
当前位置 : 首页 经验总结 Wordpress建站 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="<?php echo get_template_directory_uri(); ?>/mobile.css" rel="external nofollow"  />)
<?php endif ;?>

还需要注意的一点:不管是单独的WordPress主题还是自适应主题,都需要在头部<head>将添加下面meta,否者可能导致手机显示字体过小等问题。

<meta name="viewport" content="width=device-width"/>
本站大部分下载资源收集于网络,只做学习和交流使用,版权归原作者所有。若您需要使用非免费的软件或服务,请购买正版授权并合法使用。本站发布的内容若侵犯到您的权益,请联系站长删除,我们将及时处理。
留言
相关推荐
公众号
秦兽兽

个人博客-得之,我幸。失之,我命,如此而已

https://www.qinshoushou.com