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


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>
    			<a href="<?php the_sub_field('block_link_url'); ?>" class="btn"><?php the_sub_field('block_link_text'); ?></a>
    <?php endif; ?>
    <?php $i++; ?>
    <?php endwhile; ?>
    • Elliot

    • July 16, 2013 at 12:41 pm

    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!

    • Elliot

    • July 17, 2013 at 2:28 pm

    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.


  • 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>
    		<a href="<?php echo $rows[$i]['block_link_url']; ?>" class="btn"><?php echo $rows[$i]['block_link_text']; ?></a>
Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.