Support

Account

Home Forums Front-end Issues Showing one random post object from a sub_field list Reply To: Showing one random post object from a sub_field list

  • Hi @qhuit

    In this case, you need to pass the total number of the products to the array_rand() function like this:

    <?php
    $repeater = get_field('products');
    
    // get 4 keys of the repeater
    $repeater_keys = array_rand($repeater, 4);
    
    if($repeater):
    
    	echo "<section class='shopThis'>
            <h3 class='title md-col-3'>Shop this in our store</h3>
            <!--<p>This article is available in our brand new online store.<br>-->
            <p>We brought a few things back from this trip, and it's now available in our brand new online store.<br />
            Gets yours by clicking here!</p>
            
            <div class='articles_container'>";
        
        // loop through the keys
        foreach( $repeater_keys as $repeater_key ){
            
            //get the post object using the repeater key
            $post_object = $repeater[$repeater_key]['product_image'];
                
            if( $post_object ){
                $post = $post_object;
                setup_postdata($post);
                ?>
    
                <article>
                    <a href="<?php echo the_permalink();?>"><?php the_post_thumbnail();?></a>
                    <a href="<?php echo the_permalink();?>" class="btn">shop this</a>
                </article>
                
                <?php
            }
            
        }
        
        wp_reset_postdata();
        
        echo "</div>
            </section>";
    
    endif; ?>

    Hope this helps 🙂