How can I get the logged in username in a jQuery
script?
Background:
I’m working with ACF repeater fields, and I want to auto populate a subfield with the logged in username. This should be executed each time the user adds a new row in the repeatable field.
Everything looks pretty well, but I’m stuck at the point of getting the logged in username in jQuery
. I don’t know how to get it. Any guidance will be appreciated!
You would need to use the wp_localize_script()
function which allows you to create a JavaScript object, fill it with data using PHP, and then pass it into the JavaScript file.
This is done in your functions.php
file inside the function where you’re enqueuing your JavaScript file. You will need to pass it the handle you enqueue your script as, the name of the object you want to use in JavaScript, and an array of properties and values for the object.
From then on you just use the wp_get_current_user()
function to get your values.
For example:
function theme_scripts() {
global $current_user;
$current_user = wp_get_current_user();
wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '', true );
wp_localize_script( 'theme-script', 'theUser', array (
'username' => $current_user->user_login,
) );
}
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
The thing is that $current_user
is not populated by default in your enqueue function, so you’re going to need to call it somewhere before hand as follows:
global $current_user;
$current_user = wp_get_current_user();
This object can now be accessed in your script with properties for every key you put in the array. So in this case you would access the user’s login name as theUser.username
.