1

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
  • Is the document.ready function inside the wp-content/uploads/custom-css-js/675.js file? Commented Dec 17, 2021 at 20:55
  • The 675.js file has only the this code jQuery(document).ready(function( $ ){ var displayName = test.current_user.display_name; }); Commented Dec 17, 2021 at 21:03

2 Answers 2

2

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;
    }
);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.