In this tutorial we’ll learn how to add login/logout links to menu for Woocommerce accounts. To achieve this first of all you need to add a menu and insert it to primary section of the site.
You can add and insert menu to primary section from backend. Just go to backend then appearance > menus and create one.
If you already have a menu in your site then you don’t need to add one, if not then add a new one and assign to primary menu from here:
After creating menu, add the following lines of code at the end of your theme’s functions.php file.
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; }
Add the above code in functions.php file of your theme.
Now if you go to front end and refresh the page you’ll see the login link being added to the menu.
After logging in you’ll see the logout link.
And that is all we need.
Thankyou so much sir this working fine
Thanks for this!
Just a heads up that ‘woocommerce_get_page_id’ is now depreciated.
Needs to be replaced with ‘wc_get_page_id’