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>