I'm developing a site in WordPress and creating my own theme. As part of the theme, I have a custom user login. When a user logs in, the form action directs back to itself and in the header of the page, I have a simple script which determines if the user is logged in or not.
While this script runs as expected, the issue I encounter is trying to load the user's first and last name with the use of wp_get_current_user function, the name returned is blank on the initial load (although it does show once the page is refreshed or when migrating to a new page).
I've searched several user questions and articles and many of them mention hooking into the init function (such as this one), but none of them provide additional detail on this. I've attempted to add a filter to the init function, but have had no luck.
Here's my code to handle the login, located at the start of the header.php file:
<?php
if (is_user_logged_in()) {
$userLoggedIn = true;
if (isset($_POST['spLogout'])) {
wp_logout();
$userLoggedIn = false;
}
} else {
$userLoggedIn = false;
if (isset($_POST['spLogin'])) {
$ax_user = $_POST['email'];
$ax_pswd = $_POST['pswd'];
$creds = array(
'user_login' => $ax_user,
'user_password' => $ax_pswd,
'remember' => true
);
$user = wp_signon( $creds, false);
if (is_wp_error($user)) {
echo $user->get_error_message();
} else {
$userLoggedIn = true;
}
}
}
?>
And in my functions.php file, here is the hook and function:
add_filter('init', 'ax_get_user_info');
function avox_get_user_info() {
if (is_user_logged_in()) {
$currentUser = wp_get_current_user();
$fName = $currentUser->user_firstname;
}
return $fName;
}
I'd like to be able to load user information without requiring a page refresh. Perhaps I'm doing this wrong, I'm only just starting to learn about hooks and loading order within WordPress, but any advice is greatly appreciated.