Search code examples
wordpressuser-registration

Switching between log in and log out menu


I included a menu for the login and user registration in my Wordpress site, which appear in the header selecting it in the Wordpress dashboard (Appearance> Menu). For this one, I wrote the code below.

What code would it include so that when the user is logged or registered, the register menu switch to a link that allows closing the user's session (logout page)and vice versa?

function.php (child theme):

<?php
register_nav_menus( array(
'login' => esc_html__( 'Login', 'music' ),
) );
?>

header.php:

if ( has_nav_menu( 'login' ) ) {
echo '<div class="login-nav">';
$login_menu_args = array(
'theme_location'  => 'login',
'container'       => 'ul',
'menu_class'      => 'nolmp',
'echo'            => true,
'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
);
wp_nav_menu( $login_menu_args );
echo '</div>';
}

Thanks


Solution

  • Try this code.

    <?php 
        if(is_user_logged_in()) {
    
            echo $items = '<li class="right"><a href="'. wp_login_url(get_permalink()) .'">'. __("Log Out") .'</a></li>';
        }
        else {
           echo '<div class="login-nav">';
            $login_menu_args = array(
            'theme_location'  => 'login',
            'container'       => 'ul',
            'menu_class'      => 'nolmp',
            'echo'            => true,
            'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
            );
            wp_nav_menu( $login_menu_args );
            echo '</div>';
        }
    ?>