質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません wordpress.stackexchange
scroll top