Home > Software design >  Wordpress Add Current User ID into HTML Script
Wordpress Add Current User ID into HTML Script

Time:04-29

I have a script called in my header:

<head>
<script src="xxxx.script.js" data-user-id=" *** "    .....   </script>

I want to add in the current logged in user's ID into this script but not sure how to go about it. I know there is the get_current_user_id() function, but I'm not sure how to add that data into the script as a variable.

CodePudding user response:

You have the right idea. You will need to go to the PHP source where that template is rendered from. As you said, you can fetch the current user's id like so:

$current_user_id = get_current_user_id();

Now, in your PHP template you will have to inject the result into what is rendered in the HTML:

<script src="script.js" data-user-id="<?php echo $current_user_id; ?>"></script>

Then, within your JS file, you can fetch the attribute and use it like so:

let attr = document.currentScript.getAttribute('data-user-id')

I don't use WordPress much, but I think it's worth noting that exposing the user id client side doesn't seem like the greatest approach professionally and an API request to the server would be preferable, but regardless, this should work.

  • Related