questions

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 = userDetails.current_user.username.data.user_email;
console.log("display is " + userEmail);

In my HTML file I have below code:

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="/test/scripts-test.js"></script>

    <title>Test</title>

    <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />



  </head>

  <body>

</body>


</html>

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.

 

✔️Solution:

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 = window.userDetails.current_user.username.data.user_email;
    console.log("display is " + userEmail);
});

Leave a Reply

Your email address will not be published.

Back to top button