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 falue of current_user from wp_admin through a 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??
CodePudding user response:
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.
CodePudding user response:
Based on how you're passing the current_user
object to the jQuery. Your jQuery should look like this to get display_name
.
To see what is passed to current_user
in the JS. Just go to the developer's console and type in test.current_user
and you'll see that data
is where the userdata is stored as an object.
You also don't need to use document(ready)
- for whatever that's worth.
jQuery(
function($){
let display_name = test.current_user.data.display_name;
}
);