通过添加判断函数可以使某个菜单项或者小工具只显示在指定的分类页面或者文章页面,这种更符合自己的个性化需求,针对wordpress网站大多数都是自适应的居多,所以可以利用条件判断分别设置是否在移动端显示,下面77生活网就来与大家分享自己的操作。
貌似导航菜单中一般我们会放一个类似“网站首页”的自定义链接,方便浏览者直达网站首页。但所有页面文字都是一样的,通过添加判断可以让“网站首页”文字只显示站点的首页,其它页面显示“返回首页”文字,这样更加合理。
本站是用针对移动与PC分别投放不懂的百度联盟代码,因为代码是没有自适应的,所以只能分开设置,利用小工具添加的广告代码,这一段代码是不显示在移动端的,添加条件判断[code]!wp_is_mobile()[/code]就不会显示了,如果添加的是[code]wp_is_mobile()则就在移动端显示PC端不会显示,如下图:
这样在移动端就不会显示这段代码了,如下图这个位置就不会显示这个了,
只在移动端显示:[code]wp_is_mobile()[/code]
只在PC端显示:[code]!wp_is_mobile()[/code]
其实区别也就只是多了一个符号[code]![/code]
更多WordPress条件判断标签,请阅读:https://codex.wordpress.org/Conditional_Tags
其次如果不是知更鸟主题的话,可以采用通用的形式判断用户PC电脑端和手机移动端,不同客户端显示不同的内容是WordPress必不可少的功能,通过php通过http_user_agent即可判断用户的客户端,新手站长网分享PC电脑端和移动手机端显示不同内容的方法:
在functions.php中加入如下代码
找到你的WordPress主题中的functions.php文件,在functions.php中插入以下代码:
// 判断PC端 function is_pc() { $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 = ture; foreach ($mobile_browser as $device) { if (stristr($user_agent, $device)) { $is_mobile = false; break; } } return $is_mobile; } // 判断手机端 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 = ture; break; } } return $is_mobile; }
WordPress模板中调用
在WP模板中调用,如index.php、footer.php、single.php等,调用方式:
1、在PC电脑端显示,移动端不显示
<?php if (is_pc() ): ?> <div> <p>我在PC电脑端显示</p> </div> <?php endif ;?>
2、在移动端显示,PC端不显示
<?php if (is_mobile() ): ?> <div> <p>我在移动端显示,不在PC端显示</p> </div> <?php endif ;?>
综上,第一步在主题下的functions.php文件中插入代码,然后再WordPress主题模板中调用即可。
该代码的主要解决的问题自动判断用户的客户端,然后站长根据不同的客户端来展示不同的内容。
使用is_pc()这段代码,该代码会自动判断访客客户端是否是PC,如果是PC则显示,不是PC则不显示;
使用is_mobile()这段代码,该代码会自动判断访客客户端是否是移动端,如果是移动端则显示,不是移动端则不显示;