Add WooCommerce MyAccount Page Login/Logout to Menu

This code adds a login/logout link to your WordPress primary menu to log the user into the WooCommerce My Account page and then also log out to the same or different page.

<?php //<~ don't add me in
add_filter( 'wp_nav_menu_items', 'my_account_loginout_link', 10, 2 );
/**
* Add WooCommerce My Account Login/Logout to Registered Menu
*
* @link https://support.woothemes.com/hc/en-us/articles/203106357-Add-Login-Logout-Links-To-The-Custom-Primary-Menu-Area
*/
function my_account_loginout_link( $items, $args ) {
if (is_user_logged_in() && $args->theme_location == 'primary') { //change your theme registered menu name to suit
$items .= '<li><a href="'. wp_logout_url( get_permalink( wc_get_page_id( 'shop' ) ) ) .'">Log Out</a></li>'; //change logout link, here it goes to 'shop', you may want to put it to 'myaccount'
}
elseif (!is_user_logged_in() && $args->theme_location == 'primary') {//change your theme registered menu name to suit
$items .= '<li><a href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '">Log In</a></li>';
}
return $items;
}
view raw woologin.php hosted with ❤ by GitHub

It differs from the referred article as that adds the WordPress default login/logout page.

The menus need to be registered via register_nav_menu and positioned with theme_location, so the trick is to find the registered menu name. You can find this in the dashboard on the menus page – then inspect with browser dev tools to see what it is.

Menu Location Dashboard

Dashboard Menus Page

 

Menu Location Menu Name

See Menu Name in Code

 

So in the above example, the name to use would be header

ref

6 Comments

  1. ErnestPH on October 14, 2018 at 2:55 am

    Indeed, this is not working on a DIVI theme and probably other specific themes also. I hope this has a workaround…

    • Neil Gowran on October 14, 2018 at 3:22 am

      It works fine as long as the theme correctly is registering Menus with register_nav_menus, I don’t use Avada but if you find out the Theme location name from support for the menu you want to manipulate and then add it in the code snippet, it will work.

  2. Gibber on January 12, 2018 at 8:52 am

    Hi, can you tell me what exactly should the value on ‘primary’ to it works on my site?

    My ‘Site Menu’ is currently set as the’ Main Navigation’.

    Thanks,

  3. Bri on October 20, 2016 at 6:03 pm

    Great snippet thank you.

    Quick question, if I have ‘My Account’ already defined as part of the primary menu then how can I add Login/Logout to that as a sub-menu?

  4. Evan on April 29, 2016 at 12:38 pm

    Any idea why this php snippet is putting the link below the existing secondary menu and not adding it too the three other menu items? Running Divine Theme modified heavily; but core menu structure is default.

Leave a Comment