Are you looking for a way to attach a navigation menu to the admin bar? While there’s probably a plugin for this, we have created a quick code snippet that you can use to attach a navigation menu to the admin bar in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
add_action( 'admin_bar_menu', 'wpse15186_admin_bar_menu' );
function wpse15186_admin_bar_menu( &$wp_admin_bar )
{
$menu = wp_get_nav_menu_object( 'WPSE 15186 test menu' );
$menu_items = wp_get_nav_menu_items( $menu->term_id );
$wp_admin_bar->add_menu( array(
'id' => 'wpse15186-menu-0',
'title' => 'WPSE 15186 menu',
) );
foreach ( $menu_items as $menu_item ) {
$wp_admin_bar->add_menu( array(
'id' => 'wpse15186-menu-' . $menu_item->ID,
'parent' => 'wpse15186-menu-' . $menu_item->menu_item_parent,
'title' => $menu_item->title,
'href' => $menu_item->url,
'meta' => array(
'title' => $menu_item->attr_title,
'target' => $menu_item->target,
'class' => implode( ' ', $menu_item->classes ),
),
) );
}
}
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 11 best WordPress plugins for writers and how to use Google Optimize in WordPress.
Comments Leave a Reply