I am using the Avada Theme from Themeforest and I have set up 2 menus under Appearances > Menu:
menu-logged-in
which contains a parent item (My Account) and then several child items; andmenu-logged-out
which contains a single link to the/my-account
page where users can log in or register.
My intention hereafter is to dynamically show the relevant menu in the Theme location called "Top Navigation" depending on whether the user is logged in or is anonymous.
I've added this code into my child theme's function.php
:
add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 );
function add_loginout_link( $items, $args ) {
if (is_user_logged_in() && $args->theme_location == 'top_navigation') {
$items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>';
//$items .= wp_nav_menu( array('menu' => 'menu-logged-in', 'container' => '') );
}
elseif (!is_user_logged_in() && $args->theme_location == 'top_navigation') {
$items .= '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>';
}
return $items;
}
Now this does work, but I would prefer to be able to call a Wordpress menu into the location instead of hard-coding these into the function. In the block above I have commented line 5 that helps me achieve this, but it then renders a pre-formatted HTML <UL> at the very top of the page, and not where I want it to go.
I would be grateful if someone could please point me in the right direction. Thank you.
<UL>
is part of$items
you could remove it in the function usingstr_replace('<UL>','',$items);
Often the<UL>
is opened in the template itself before the<li>
s are supplied dynamically.