Tad
Tad

Reputation: 73

Adding a button that's unique in every post

I want to make a button that's in a "if" loop that will unroll / show more images from the Advanced Custom Fields plugin. The problem is that it doesn't work when there are more post on page than one, because the same button is in all of the posts and all the images have the same class. Is there a way to make a unique button that will work only in it's post?

<?php if (have_posts()) :   while (have_posts()) : the_post(); ?>

<?php the_content();    if (get_field('project_detail')) {
 the_field('project_detail');
 } ?>

<img src="<?php echo the_field('visible_image_1'); ?>" /> 

<button type="button">Show more</button> 

<script> 
$("button").click(function(){ $(".more").slideToggle(500); });
</script> 

<div class="more"> 
 <img src="<?php echo the_field('hidden_image_1'); ?>" /> 
 <img src="<?php echo the_field('hidden_image_2'); ?>" /> 
</div>  

<?php endwhile;
 else :
  echo '<p>No content found</p>';   endif;

get_footer();   ?>

CSS

.more { display: none; }

Upvotes: 1

Views: 71

Answers (1)

L L
L L

Reputation: 1470

Try something like this:

<?php
if (have_posts()) :   while (have_posts()) : the_post(); ?>

<?php the_content();    if (get_field('project_detail')) {
 the_field('project_detail');
 } ?>

<img src="<?php echo the_field('visible_image_1'); ?>" /> 

<button type="button" id="button<?php echo get_the_ID()?>">Show more</button> 

<script> 
$("#button<?php echo get_the_ID()?>").click(function(){ $(".more<?php echo get_the_ID()?>").slideToggle(500); });
</script> 

<div class="more<?php echo get_the_ID()?>"> 
 <img src="<?php echo the_field('hidden_image_1'); ?>" /> 
 <img src="<?php echo the_field('hidden_image_2'); ?>" /> 
</div>  

<?php endwhile;
 else :
  echo '<p>No content found</p>';   endif;

get_footer();   ?>

We are using a variable which will be added to each button ID, so they will be button1, button2, etc. Let me know if this works :)

Upvotes: 1

Related Questions