Saturday, May 21, 2016

WordPress get active menu item

In WordPress menu are dynamically managed. User can set Primary Header and footer menu from admin section.

If you want to get the current Menu item name you can get it by using the following function.

Open your active theme's functions.php and add the following function at the bottom of the file.

<?php
function Get_menu_item_name( $loc ) {
global $post;
$locs = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locs[$loc] );

if($menu) {
$items = wp_get_nav_menu_items($menu->term_id);

foreach ($items as $k => $v) {          
if ($items[$k]->object_id == $post->ID) {
$name = $items[$k]->title;
break;
}
}
}
return $name;
}
?>

The usage of the function is as follows:

<?php
$current_menu_name = Get_menu_item_name( 'primary' ); // here you enter another alias if your menu is not primary
echo $current_menu_name;
?>

$current_menu_name will contain the value of the current menu name.

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...