0
votes

I have the normal WP loop for showing blog posts on home.php. Im trying to get a random div to populate after each blog post. So it will be:

BLOG POST -> RANDOM DIV -> BLOG POST -> RANDOM DIV

and so on...I've tried to create "testimonials" post type and randomize them with WP_Query, but it still will only pull one PER PAGE. I need multiple to display, but differently below each post. I am also using ACF, so I created testimonial custom field blocks, but I still cant them to randomize display multiple items.

PHP (within loop):

<a class="row blogRoll"href="<?php the_permalink(); ?>">

    <div class="blogImg col-sm-3">
    <?php the_post_thumbnail(); ?>
    </div>

   <div class="col-md-9 blogBlack">
    <h2 class="entry-title"><?php the_title(); ?></h2>

        <?php the_excerpt(); ?>

    </div><!-- .entry-content -->
</a>
<div class="testimonial">
<?php the_field('testimonial_content1', 'option');
the_field('testimonial_author1','option'); ?>
</div>
<div class="testimonial">
<?php the_field('testimonial_content2', 'option');
the_field('testimonial_author2', 'option'); ?>
</div>
<div class="testimonial">
<?php the_field('testimonial_content3', 'option');
the_field('testimonial_author3', 'option'); ?>
</div>
</div> 

JS:

var elems = $(".testimonial");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
  if (i !== keep) {
    $(elems[i]).hide();
  }
 }
}

Obviously, the loop is causing me the headache, because it will pull most recent posts and I just need to pull and not DUPLICATE the testimonial divs below a blog post. Any ideas will be appreciated.

1

1 Answers

0
votes

Instead of shuffling and outputing the result straight away, you could shuffled an array (pool of testimonials) and then apply the first value to a first .testimonial class for example, and a second value from the shuffled array to the second .testimonial class, ... etc.

That article might be of some help, Randomly iterate through array without pulling duplicate values. You could replace numbers by testimonials... Regards.