Outputting the First or Last Repeater Row in ACF to a Widget in WordPress

This guide follows on from a previous one using ACF Pro repeater field group to output rows of Testimonials on a WordPress page instead of using a custom post type single/archive structure.

What I wanted to also show is how you can take one of these testimonial data rows and display it in a widget on the home page that just pulls the first, last or random row from the actual testimonial page. Here I will be adding PHP code in widgets so you’ll  need to ensure that you are allowing PHP to run in widgets.

ACF Repeater First

Single Testimonial on Home Page

So in the layout above instead of manually copying and pasting a single testimonial into a widget, we can get a single ACF repeater data row in there or a random or latest one from the existing data.

 

acf-testimonial-styled-css

Existing Testimonial Page

Just add the relavant PHP code below into the required widget.

First Repeater Row

Last Repeater Row

Random Repeater Row

I have marked up the code in the Gist – essentially in all three we are initially grabbing the custom field which is called testimonials and the page ID that it is on.

For the first row, 2 variables are set against each sub-field row with a value of [0] which is the first in an array, then a final variable is assigned $first and echo’ed out.

For the random row, again all rows are grabbed and then a random row is grabbed with array_rand, the sub-fields are then also assigned variables, then a final variable is assigned $random and echo’ed out.

For the last row, all rows are grabbed and then the end row is grabbed with end, the sub-fields are then also assigned variables, then a final variable is assigned $random and echo’ed out.

More ACF Repeater code is here, I think being able to extract specific rows of data and output them elsewhere really makes this tool like a Swiss Army Knife.

Leave all Comment