admiva
admiva

Reputation: 17

Wordpress: Get ID from wp_query post for jquery

I have a code:

<div id="parent-<?php the_ID(); ?>" class="first">

and I want to use it in JQuery for click function, like:

$('#parent-**??**').click(function (){

How should I proceed?

Upvotes: 0

Views: 1373

Answers (3)

treyBake
treyBake

Reputation: 6560

It's hard to get dynamically generated DOM attributes. jQuery, whilst it can get the value using AJAX, it's a bit of an overhead to do that. The best thing IMO is to simply assign the ID to a hidden element with a generic class. In your jQuery you can then use the generic class to get the dynamic value and append that to the jQuery selector to get the dynamic element.

If you can change the HTML, you could do this:

<div id="hidden-parent" data-id="<?php the_ID(); ?>"></div>

<div id="parent-<?php the_ID(); ?>" class="first">
    <!-- etc. -->
</div>

Then in your jQuery:

let id = $('#hidden-parent').attr('data-id'),
    parentDiv = $('#parent-'+ id);

parentDiv.click(function()
{
    //whatever
})

here we just get the data-id value and use that to get the parent-* div

There is one thing to note about this. If you're looping divs to build a page then using an ID on the hidden-parent element won't work. What you could do is append the key, e.g.

<?php foreach ($elements as $key => $el) : ?>
    <div id="foo-<?php echo $key; ?>">
        <!-- etc. -->
    </div>
<?php endforeach; ?>

Then in your jQuery just use $('#foo-1') etc.

Upvotes: 0

Beneris
Beneris

Reputation: 637

<div id="parent-<?php the_ID(); ?>" class="first parent" data-id="<?php the_ID(); ?>">
<script>
    $('.parent').click(function (){
         var parentId = $(this).attr('data-id');
        if (parentId != undefined && parentId != '') {
            // do something
        }

     });
</script>

Upvotes: -2

Eriks Klotins
Eriks Klotins

Reputation: 4180

Try passing the value from PHP to JS:

PHP:

echo sprintf("<script> var theID = %d;</script>", the_ID());
<div id="parent-<?php the_ID(); ?>" class="first">

JS:

 <script>
   alert("current post id = "+theID);
 </script>

UPDATE:

In case you are printing posts in a loop, you may want to push all the ids into an array.

PHP:

<?php
$posts = [];
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 
        ?>
        <div id="parent-<?php the_ID(); ?>" class="first">
        //
        // Post Content here
        //
        </div>
        <?php
        posts[] = get_the_ID();
    } 
}

echo sprintf("<script> var thePostIDs = %s;</script>", json_encode(posts));

JS:

<script>
    thePostIDs.map(function(id){
     // do something with the id
     $('#parent-'+id).click(function (){
       // do something
     });
    });
</script>

Upvotes: 0

Related Questions