我正在尝试根据设备/屏幕宽度显示不同的wordpress菜单。
<script>
$(function() {
if ($(window).width() > 959) {
<?php wp_nav_menu( array( 'menu' => 'primary', 'container' => '', 'menu_id' => 'menu' ) ); ?>
} else {
<?php wp_nav_menu( array( 'theme_location' => 'mobile' ) ); ?>
}
});
</script>
我已尝试使用此代码以及其他几种变体,但似乎没有任何效果。有什么想法吗?
提前致谢
威廉
答案 0 :(得分:0)
据我所知,wp_nav_menu只输出菜单html,所以在客户端,你会得到这个:
<script>
$(function() {
if ($(window).width() > 959) {
<div>....menu html....</div>
} else {
<div>....menu html....</div>
}
});
</script>
我认为那里应该有javascript错误。
试试这个:
<div id="menu_a" style="display:none">
<?php wp_nav_menu( array( 'menu' => 'primary', 'container' => '', 'menu_id' => 'menu' ) ); ?>
</div>
<div id="menu_b" style="display:none">
<?php wp_nav_menu( array( 'theme_location' => 'mobile' ) ); ?>
</div>
<script>
$(function() {
if ($(window).width() > 959) {
$("#menu_a").show();
} else {
$("#menu_b").show();
}
});
</script>
或者在响应设计风格中,不涉及Javascript:
@media all and (max-width: 958px) { #menu_a{display:none};}
@media all and (min-width: 959px) { #menu_b{display:none};}
答案 1 :(得分:0)
我最终使用了这个:
<?php
/* USER-AGENTS
================================================== */
function check_user_agent ( $type = NULL ) {
$user_agent = strtolower ( $_SERVER['HTTP_USER_AGENT'] );
if ( $type == 'bot' ) {
// matches popular bots
if ( preg_match ( "/googlebot|adsbot|yahooseeker|yahoobot|msnbot|watchmouse|pingdom\.com|feedfetcher-google/", $user_agent ) ) {
return true;
// watchmouse|pingdom\.com are "uptime services"
}
} else if ( $type == 'browser' ) {
// matches core browser types
if ( preg_match ( "/mozilla\/|opera\//", $user_agent ) ) {
return true;
}
} else if ( $type == 'mobile' ) {
// matches popular mobile devices that have small screens and/or touch inputs
// mobile devices have regional trends; some of these will have varying popularity in Europe, Asia, and America
// detailed demographics are unknown, and South America, the Pacific Islands, and Africa trends might not be represented, here
if ( preg_match ( "/phone|iphone|itouch|ipod|symbian|android|htc_|htc-|palmos|blackberry|opera mini|iemobile|windows ce|nokia|fennec|hiptop|kindle|mot |mot-|webos\/|samsung|sonyericsson|^sie-|nintendo/", $user_agent ) ) {
// these are the most common
return true;
} else if ( preg_match ( "/mobile|pda;|avantgo|eudoraweb|minimo|netfront|brew|teleca|lg;|lge |wap;| wap /", $user_agent ) ) {
// these are less common, and might not be worth checking
return true;
}
}
return false;
}
?>
然后:
<?php
$ismobile = check_user_agent('mobile');
if($ismobile) {
wp_nav_menu( array( 'theme_location' => 'mobile' ) );
} else {
wp_nav_menu( array( 'menu' => 'primary', 'container' => '', 'menu_id' => 'menu' ) );
}
?>
这不适用于设备尺寸,而是适用于是否从移动设备访问该网站。
感谢
威廉