I have the code below in my functions.php file. However, when I try to access the variable theUser
in my custom.js
file it comes back as undefined
.
Functions.php:
function theme_scripts() {
global $current_user;
$current_user = wp_get_current_user();
wp_enqueue_script( 'theme-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array( 'jquery' ), '', true );
wp_localize_script( 'theme-script', 'theUser', array (
'username' => $current_user,
) );
}
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
Custom.js:
var theUser;
var userName = theUser.username.data.display_name;
var userEmail = theUser.username.data.user_email;
console.log(theUser);