Here is a quick and easy win for your Monday! Its very easy to add a nicely styled login/logout item to your Astra Theme menu like so:
Just add the following PHP code (note this should be added to your child theme):
/**
* Adds login/logout to the Astra menu
*/
add_filter('wp_nav_menu_items', function ($items, $args) {
// Only used on main and mobile menus -adjust this as needed
if (('primary' != $args->theme_location) && ('mobile_menu' != $args->theme_location)) {
return $items;
}
// Add custom item
$items .= '<li class="astra-child-custom-login-logout-link menu-button menu-item">';
// Log-out link
if (is_user_logged_in()) {
$text = 'Logout';
$logout_redirect = home_url('/'); // Change logout redirect URl here
$items .= '<a class="ast-custom-button-link" href="' . wp_logout_url($logout_redirect) . '" title="' . esc_attr($text) . '">
<div class="ast-button">' . strip_tags($text) . '</div></a>';
}
// Log-in link
else {
$text = 'Login';
$login_url = wp_login_url(); // Change if you want a custom login url
$items .= '<a class="ast-custom-button-link" href="' . esc_url($login_url) . '" title="' . esc_attr($text) . '">
<div class="ast-button">' . strip_tags($text) . '</div></a>';
}
$items .= '</li>';
// Return nav $items
return $items;
}, 20, 2);
If you don’t have a child theme setup, then you might want to use this resource. Then all you need to do is upload the generated theme and activate it (note: you might need to tweak some customizer settings after this).
*2024 update: I added the login/logout button to the mobile menu as well as pointed out by Alex – thanks again!
Thanks Rhyso!
This is very useful for non coders like me.
I added to all the menus…not only primary. One thing I would request your help on – I dont want the new login/logout button stylised like this but rather retain the default style of the other menu items. How do I do that?
Many thanks for all your guidance, its deeply appreciated.
I changed the theme_location check to the following so the login/logout button shows on mobile too…
if ((‘primary’ != $args->theme_location) and (‘mobile_menu’ != $args->theme_location)) {
Cool cheers! Thats very helpful. I have updated my code 🙂
Where do we add this code?
You would add this to the functions.php of your child theme 🙂