
I’ve been beating my head against the wall trying to make this work. I have a repeater field and a nested repeater within it. I’m trying to extract a random entry from the nested repeater, but I can’t even pull the nested entries into an array. I’ve tried dozens of code configurations, but I’ll post my latest here:
<?php if( have_rows('section_content') ): //repeater nested inside another repeater
$rows = get_sub_field('content_option'); //this just fails
print_r($rows); //returns nothing
endif; ?>
Once I’m able to pull valid data, I’ll shuffle the rows and only return the first one.
I read somewhere in another post that you can’t create an array using sub field functions. If this is the case, then I can understand why the above fails. But I’m not sure what to try instead.
If it matters, the content inside ‘content_option’ will need to run through the_content filter and has shortcodes that need to run as well. If I can get an array to print, I can probably take it from there. Any help would be most appreciated!
So, I ended up doing this:
<?php if( have_rows('section_content') ):
$rows = array();
$i = 0;
while ( have_rows('section_content') ):
the_row();
$rows[$i] = get_sub_field('content_option');
$i++;
endwhile;
$i = mt_rand(0,count($rows)-1);
echo $rows[$i];
else:
// some other stuff
endif; ?>
Hackfest 2015! But at least I’m getting the results I need. I’m guessing this isn’t very efficient, but I’m going to end up putting caching on this, and we’re talking about a very small audience (maybe 1000 visitors per month across 6 sites). So I think it will end up working out fine.
Still, I would love it if there’s a more native way to do what I’m doing, where I just pull one result, instead of pulling all of them and then selecting one from an array. It feels dirty…
Hi @studio1337,
You can always get the repeater content using get_field() function. You can see the content of the repeater field using a code like this:
print_r(get_field('section_content'));
This way you can generate a random number as the index of the returned array.
I hope this makes sense.