I am using wordpress and have the following code on functions.php file
function fun1() {
wp_enqueue_script( 'aldi_code', 'wp-content/uploads/custom-css-js/675.js', array( 'jquery' ), false, true );
wp_localize_script( 'aldi_code', 'test', array(
'current_user' => wp_get_current_user()
) ) ;
}
add_action( 'wp_enqueue_scripts', 'fun1' );
I want to access the value of current_user
from wp_admin
through jquery using the following code
jQuery(document).ready(function( $ ){
var displayName = test.current_user.display_name;
});
The problem is that I get the error:
test is not defined.
Do you have any idea what is wrong on this code??
2
Answers
If you don’t wanna pass values between JS and PHP directly, you can use
cookies
. Both of them can read and write data in there.Set a cookie in PHP, then read it in JS.
Based on how you’re passing the
current_user
object to the jQuery. Your jQuery should look like this to getdisplay_name
.To see what is passed to
current_user
in the JS. Just go to the developer’s console and type intest.current_user
and you’ll see thatdata
is where the userdata is stored as an object.You also don’t need to use
document(ready)
– for whatever that’s worth.