WordPress.org

Ready to get started?Download WordPress

Forums

Post id in javascript (7 posts)

  1. zglows
    Member
    Posted 6 years ago #

    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?

  2. haochi
    Member
    Posted 6 years ago #

    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>
  3. zglows
    Member
    Posted 6 years ago #

    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?

  4. haochi
    Member
    Posted 6 years ago #

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

  5. zglows
    Member
    Posted 6 years ago #

    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.

  6. haochi
    Member
    Posted 6 years ago #

    *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>
  7. zglows
    Member
    Posted 6 years ago #

    i love you haochi.
    Thanks!!

Topic Closed

This topic has been closed to new replies.

About this Topic