0

I’m very new to WP, and to JS as well, and need to do a simple change to existing code, so forgive my ignorance…

For getting the current User Id I followed examples and added an action + function to functions.php of my child theme (pasted below) Now I need to use it within a WP page within a <script>…. </script>

I tried to assign it into a var and failed (an example script part also pasted below, with non-functioning assignment).

How do I do that right?

Added to functions.php:

    add_action('init',’my demo_function');
    function my demo_function(){
        $theid=get_current_user_id();
        $params = array(
            'userid' => $theid
        );
        wp_localize_script( 'myuserscript', 'MyUserParams', $params );
        wp_enqueue_script('myuserscript');
    }

The example of code I tried in the WP page (which fails)

   <script>
    // when using this line I get the alert, as expected
    // var myData = "1234"; 
    // but when using this, alert is skipped, I suppose because this assignment is invalid 
    var myData = MyUserParams.userid; 
    alert("your id is: " + myData)
    </script>
0

You have to make sure your script is registered with wp_register_script before your call to wp_localize_script.

So in your functions.php file:

add_action('init',’my demo_function');
function my demo_function() {


    // Register the script
    wp_register_script( 'myuserscript', 'path/to/myscript.js' );

    // Localize the script with your data
    $theid=get_current_user_id();
    $params = array(
        'userid' => $theid
    );
    wp_localize_script( 'myuserscript', 'MyUserParams', $params );

    // Enqueued script with localized data.
    wp_enqueue_script('myuserscript');
}

Then the parameter would be available to you in the frontend

<script>
    var myData = MyUserParams.userid; 
    alert("your id is: " + myData)
</script>

Reference: wp_localize_script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.