Support » Fixing WordPress » Post id in javascript

  • zglows

    (@zglows)


    I’d like to know how to call a post id from a javascript file.
    In the template I use <?php the_ID(); ?> but how can I call the same id from Javascript?

Viewing 6 replies - 1 through 6 (of 6 total)
  • haochi

    (@haochi)

    I don’t really get what you are trying to do but I will attempt to answer it.

    <script>
    function the_ID(){
       return "<?php the_ID(); ?>";
    }
    </script>

    zglows

    (@zglows)

    ok, thanks for your answer. The problem is I’m trying to call the id from an external javascript file. I do this wich is wrong:

    document.getElementById("message_<?php the_ID(); ?>")

    and I get > “document.getElementById(“message_<?php the_ID(); ?>”) has no properties” in Firebug.

    what am I doing wrong?

    haochi

    (@haochi)

    Are you calling the JS before the content appears? Use window.onload.
    Post your blog’s URL by the way.

    zglows

    (@zglows)

    I’m trying this:

    <script type="text/javascript">
    function the_ID(){
    alert("<?php the_ID(); ?>");
    }
    </script>

    And when I click on this link

    <a href="#" onclick="the_ID();">CLICK</a>

    I get always the value 18 no matter what post I click on.

    haochi

    (@haochi)

    *palmface*

    You should’ve just post your URL because:
    #1: You are doing it wrong.
    #2: You are doing it wrong.

    It should be something like this for a standard WordPress blog.

    <script>
    function get_post_content(id){
       return document.getElementById("post-"+id).innerHTML;
    }//you should probably use textContent/innerText but I am not going to get into that here
    </script>
    
    <a href="#" onclick="alert(get_post_content(<?php the_ID(); ?>));">CLICK</a>
    zglows

    (@zglows)

    i love you haochi.
    Thanks!!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Post id in javascript’ is closed to new replies.