On my WordPress site I have a modal button in the header that allows users to login. Once logged in the button text changes from 'LOGIN' to 'LOGOUT', giving the user the ability to logout if they want to. How can I get that button to show the users name instead of 'LOGOUT'. For example my name is Tina and when I first select the login button & login successfully the header shows 'LOGOUT' but I want it to show 'TINA' instead. Thanks for the help in advance!
HTML:
<?php if (is_user_logged_in()) { ?>
<a class="login_button" href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a>
<?php } else { ?>
<a class="login_button" id="show_login" href="">Login</a>
<?php } ?>
<form id="login" action="login" method="post">
<h1><img src="image.png" class="login-logo" width="80" height="auto"></h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username">
<label for="password">Password</label>
<input id="password" type="password" name="password">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Forgotten your password?<br><br></a>
<input class="submit_button" type="submit" value="Login" name="submit">
<a class="close" href=""><span class="glyphicon glyphicon-remove"></span></a>
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
You can use wp_get_current_user()
built-in function provided by wordpress, as per the following code-snippet, function will return the current logged in user information object:
<?php
$current_user = wp_get_current_user();
echo 'User first name:' . $current_user->user_firstname;
echo 'User last name:' . $current_user->user_lastname;
?>
Here is the way to achieve your expectations:
I hope you should have been stored username in session if not, please store logged-in user name in the session.
i.e: $_SESSION['username']='ABC'; //Store your username in session when you will Log-In to the site.
<?php if (is_user_logged_in()) {
$logout = $_SESSION['username'] ? $_SESSION['username'] : "Logout";
?>
<a class="login_button" href="<?php echo wp_logout_url( home_url() ); ?>"> <?php echo $logout; ?> </a>
<?php } else { ?>
<a class="login_button" id="show_login" href="">Login</a>
<?php } ?>
try this, it will work for you.