ou have to replace ” echo ” to ” print “.
function getJSPostID() {
try {
var test='<?php print $post_id; ?>’;
return test;
} catch (e) {
return ‘unavailable’;
}
}
var ID = getJSPostID(); <— Returns a string “<?php print $post_id; ?>”
Thanks, but that doesn’t work either.
Here’s what I have:
function getJSPostID() {
try {
var test=”<?php print $post_id; ?>”;
return test;
} catch (e) {
return “unavailable”;
}
}
function showMe() {
var ID = getJSPostID();
alert(“ID is ” + ID);
and here’s what happens:

Fred
Hi Fred,
Your JS is not interpreted as PHP, so PHP code simply appears as plain text. For PHP within JS to be interpreted, the entire JS code has to be output as part of a page’s HTML output within <script> tags. This is OK for brief snippets, but most JS should be part of an external file. That file is not interpreted as PHP, so dynamic content there is out. (there’s a workaround for that but it’s generally not warranted)
As with passing comment parent IDs (as discussed on your other topic), post IDs can be passed in a similar manner by including it in the JS call that’s on an HTML page that is the result of interpreting PHP.
There is another option. This applies for general situations where values in PHP need to be passed to JS code that is often times in external files. External JS files should be enqueued, which among other things, establishes a “handle” you can use to refer to that script file. You can pass PHP values using that handle with wp_localize_script(). Using this function will result in a script block in the page’s head section that declares the values determined with PHP as JS variables.