我需要在wordpress的每个页面上获取当前活动的菜单项(如Home,关于我们等菜单标题)。我正在使用wordpress代码来显示菜单&它显示正确。代码如下所示,
$menu_name = 'primary';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) )
{
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-' . $menu_name . '" class="nav navbar-nav" style="width:100%;">';
foreach ( (array) $menu_items as $key => $menu_item )
{
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= '<li class="menu-line"><a href="' . $url . '">' . $title . '</a></li>';
}
$menu_list .= '</ul>';
} else {
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
echo $menu_list;
但我现在无法确定哪个菜单项处于活动状态。 任何帮助表示赞赏!
答案 0 :(得分:2)
像这样更新您的代码并根据您的要求添加您的CSS。
<?php
$menu_name = 'primary';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) )
{
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-' . $menu_name . '" class="nav navbar-nav" style="width:100%;">';
foreach ( (array) $menu_items as $key => $menu_item )
{
$title = $menu_item->title;
$url = $menu_item->url;
$active = '';
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if($url == $actual_link)
{
$active = 'active';
}
else
{
$active = '';
}
$menu_list .= '<li class="menu-line"><a href="' . $url . '" class="'.$active.'">' . $title . '</a></li>';
}
$menu_list .= '</ul>';
} else {
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
echo $menu_list;
?>
CSS如下
<style>
.active { border:1px solid #f00;}
</style>
它适用于我的代码。