php - Getting currently active menu title in wordpress -
i need active menu item (menu title home, us, etc..) on each page in wordpress. using wordpress codes display menu & displayed correctly. code shown below,
$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 $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;
but not able identify menu item active now. appreciated!
update code , add css per requirement.
<?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 $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 below
<style> .active { border:1px solid #f00;} </style>
it work fine code.
Comments
Post a Comment