0

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; and
  • menu-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.

enter image description here

I would be grateful if someone could please point me in the right direction. Thank you.

  • If the <UL> is part of $items you could remove it in the function using str_replace('<UL>','',$items); Often the <UL> is opened in the template itself before the <li> s are supplied dynamically. – Steve Feb 22 '16 at 1:47
  • A regex way t get rid of the <UL> by "willshouse" on this page looks promising wordpress.org/support/topic/… and it is put in a usable function too. – Steve Feb 22 '16 at 1:56
0

Okay, figured it out! I've amended my theme function as follows:

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 .= wp_nav_menu( array('menu' => 'menu-logged-in', 'container' => '', 'echo' => false, 'items_wrap' => '%3$s') );
    }
    elseif (!is_user_logged_in() && $args->theme_location == 'top_navigation') {
        $items .= wp_nav_menu( array('menu' => 'menu-logged-out', 'container' => '', 'echo' => false, 'items_wrap' => '%3$s') );
    }
    return $items;
}

So now, just gives me the <li> items I need and rendered in the correct position. Hope this helps someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.