I am trying to add a conditional Login/Logout button depending on the user role. (if the user is logged in or not). I have gotten this to work, but only when accessing the menu items as a string and not an array.

My code:

    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 == 'primary') {
    $items .= '<li><a href="'. wp_logout_url( get_permalink( woocommerce_get_page_id( 'myaccount' ) ) ) .'">Log Out</a></li>';
    elseif (!is_user_logged_in() && $args->theme_location == 'primary') {
    $items .= '<li><a href="' . get_permalink( woocommerce_get_page_id( 'myaccount' ) ) . '">Log In</a></li>';
    return $items;

The Logout/Login option is currently placed at the end of the menu. I would rather like it inside the "My Plan" dropdown menu at the bottom.

How would i add this menu item to the submenu of the "My Plan" instead of the primary menu? Help would be much appreciated.

An image of the menu and the submenu dropdown is below:

enter image description here

  • Maybe you can use the WooCommerce Endpoints with/or a plugin. Go to Appearance > Menus open the Screen Options and activate WooCommerce endpoints here. After this you can add the endpoints as normal menu-items where you want. There are endpoints for Account Details (which redirects to login page if not logged in) and Logout. In addition to that there are also plugins like Nav Menu Roles where you can configure each menu items for logged in and out users. – LWS-Mo May 4 '18 at 12:30

With .= you are appending you HTML code to the HTML code of the menu contained in the string $items, so the login will appear at the end.

You instead want to insert the link inside the HTML of $items, so you must manipulate the string.

You for example can search for the HMTL of the link the should appear before yours with str_replace()

I suggest you to var_dump $items and see the HTML than manipulate it with str_replace()

| improve this answer | |

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.