wp_localize_script Function not Working: Followed Similar Questions Solutions

Rate this post

In functions.php I have put as below:

function wp12311_enqueue_scripts() {
     wp_enqueue_script( 'wp12311-scripts',  get_stylesheet_directory_uri() . '/test/scripts-test.js', array( 'jquery' ), false, true );
     wp_localize_script( 'wp12311-scripts', 'userDetails', array(
         'current_user' => wp_get_current_user()
     ) ) ;
add_action( 'wp_enqueue_scripts', 'wp12311_enqueue_scripts' );

Then, in /test/scripts-test.js I have below code:

var userEmail =;
console.log("display is " + userEmail);

In my HTML file I have below code:

<html lang="en">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src="/test/scripts-test.js"></script>


    <link href=",700" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />





When I load the html file, I get the error:

scripts-test.js:3 Uncaught ReferenceError: userDetails is not defined

Please let know what is the issue and how can I make it work. Thanks.



You are calling it too early, try to wait until document is ready. and it’s better to use the global window object

jQuery(document).on( 'ready', function() {
    var userEmail =;
    console.log("display is " + userEmail);

Leave a Reply

Your email address will not be published.

Back to top button