0
votes

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

2

2 Answers

0
votes

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>';
    }
?>
0
votes

The function is_user_logged_in() will return TRUE if the current user is logged in and FALSE if not which makes it straight forward to check.

The simplest solution would be to wrap your link display code inside a IF/ELSE statement. Something like the following:

Check whether they're logged in or not:

<?php if(is_user_logged_in()) {
   // do the stuff to display "Log Out"
}
else {
   // the user isn't logged in so display "Log In"
}
?>

Log Out function looks like this in use:

<a href="<?php echo esc_url( wp_logout_url() ); ?>">Logout</a>

To make things a bit more proper, do this logic in your functions.php then replace your header code with a template tag calling the custom function. But, it would work to handle it all in the header.