• Hi…

    In comment_template.php there’s the id of the active post. In PHP, it’s $post_id.

    If I do this in comment_template.php:

    echo $post_id

    The post id shows up in just above the comment:

    <img src="https://dalcotech.com/d3/dtest.jpg" alt="dtest" />

    How do I show it in a javascript function that I can call. This doesn’t work:

    	function getJSPostID() {
    		try {
    			var test='<?php echo $post_id; ?>';
    			return test;
    		} catch (e) {
    			return 'unavailable';
    		}
    	}
    
    	var ID = getJSPostID(); <--- Returns a string "<?php echo $post_id; ?>"

    Thanks
    Fred

Viewing 3 replies - 1 through 3 (of 3 total)
  • 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; ?>”
    Thread Starter punchlines

    (@punchlines)

    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:

    dtest1

    Fred

    Moderator bcworkz

    (@bcworkz)

    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.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Show $post_id via javascript function’ is closed to new replies.