If you want to add the post id to your javaScript, i would think of 2 methods.
Output a variable and then retrieve it using javascript
Let’s say you need the post it. You can create a hidden div, and assign the value of your post id to it:
<div id="my-post-id"><?php echo get_the_ID(); ?></div>
Now you can retrieve this in your script by using this:
var x = document.getElementById("my-post-id").textContent;
You have your post id now, proceed to further steps.
Use wp_add_inline_script()
to output your script
You can directly add javaScript code to your header or footer by using wp_add_inline_script()
. Take a look at this example:
wp_add_inline_script('js_script','alert("'.get_the_date().'");');
Now you can directly use php functions to output contents, use in loops, and more. However you need to enqueue a JS file first and then hook your inline script to it ( in this case, a script that has the ID of js-script
is being used for hooking ).