Support

Account

Home Forums Add-ons Repeater Field Random Repeater Field [Options Page]

Solved

Random Repeater Field [Options Page]

  • Hi,

    I’m trying to get my repeater field (on an options page) to randomly pick a row to display. The code I have shows a row successfully, but it’s the same row every time (row 2)

    <?php $rand_max = count(get_field('the_block')); $i = 0; ?>
    <?php while(the_repeater_field('the_block', 'option')): ?>
    <?php if($rand_max == $i): ?>
    
    	<section id="theblock" style="background: url('<?php the_sub_field('block_background'); ?>');">
    		<div id="theblock-inner" class="container">
    			<div class="section-title civider">
    				<h2><?php the_sub_field('block_title'); ?></h2>
    				<h5 class="subtitle"><?php the_sub_field('block_subtitle'); ?></h5>
    			</div>
    			<a href="<?php the_sub_field('block_link_url'); ?>" class="btn"><?php the_sub_field('block_link_text'); ?></a>
    		</div>
    	</section>
    
    <?php endif; ?>
    <?php $i++; ?>
    <?php endwhile; ?>
  • Hi @tommysvr

    Your code does not contains any function to find a random number, only the amount of rows.. that is the issue.

  • Oh…haha sorry! Bit of a PHP novice. Would you mind pointing me in the right direction for that? Sorry if asking too much.

    Appreciate your help!

  • Hi @tommysvr

    Sorry mate, that parts up to you.
    Please read to ACF docs. There are some code exmaples on the repeater field that will help you out

    Please note: ACF is a developer tool and this support fourm is for providing help on bugs / ACF issues.

    Thanks
    Elliot

  • No worries. Thanks for ACF – unbelievable plugin!

  • In case anyone stumbles upon this, I managed to get the code example to work with me…it was just adding ‘option’.

    <?php $rows = get_field('the_block', 'option'); $row_count = count($rows); $i = rand(0, $row_count - 1); ?>
    <section id="theblock" style="background: url('<?php echo $rows[$i]['block_background']; ?>');">
    	<div id="theblock-inner" class="container">
    		<div class="section-title civider">
    			<h2><?php echo $rows[$i]['block_title']; ?></h2>
    			<h5 class="subtitle"><?php echo $rows[$i]['block_subtitle']; ?></h5>
    		</div>
    		<a href="<?php echo $rows[$i]['block_link_url']; ?>" class="btn"><?php echo $rows[$i]['block_link_text']; ?></a>
    	</div>
    </section>
Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Random Repeater Field [Options Page]’ is closed to new replies.