How to Retrieve Values from Advanced Custom Fields (ACF)

How to Retrieve Values from Advanced Custom Fields (ACF) in WordPress

In WordPress, Advanced Custom Fields (ACF) allows you to add custom fields to your posts, pages, or custom post types. One of the most powerful features of ACF is the repeater field, which allows you to add and manage multiple rows of data. In this guide, we’ll show you how to retrieve the values of an ACF repeater field using the have_rows() and the_row() functions.

Step-by-Step Guide to Retrieving ACF Repeater Field Values

Assume you have a repeater field named “my_repeater_field” with two subfields: “sub_field_1” and “sub_field_2”, attached to a post. Here’s how you can retrieve and display those values:

Step 1: Check if the Repeater Field Has Rows

First, check if the repeater field contains any rows using the have_rows() function:

<?php
// Check if the repeater field has rows
if (have_rows('my_repeater_field')) {

    // Loop through each repeater row
    while (have_rows('my_repeater_field')) {
        the_row();

        // Get the subfield values for the current row
        $sub_field_1_value = get_sub_field('sub_field_1');
        $sub_field_2_value = get_sub_field('sub_field_2');

        // Do something with the subfield values
        echo 'Subfield 1: ' . $sub_field_1_value . '<br>';
        echo 'Subfield 2: ' . $sub_field_2_value . '<br>';
    }
}
?>

Step 2: Access Subfield Values for Each Row

Inside the loop, we use the the_row() function to set the current row and then retrieve the values of the subfields using get_sub_field():

  • get_sub_field('sub_field_1'): Retrieves the value of the first subfield.
  • get_sub_field('sub_field_2'): Retrieves the value of the second subfield.

The above code will output the values of each row’s subfields. If you have more subfields in your repeater field, simply repeat the get_sub_field() function with the appropriate field names.

Why Use ACF Repeater Fields?

ACF repeater fields are great for adding dynamic content such as image galleries, testimonials, or team members to your WordPress site. They provide an easy way to manage multiple pieces of data for a single post or page. With the have_rows() and the_row() functions, you can easily loop through the repeater rows and display them on the front end of your website.

Related Resources

For more in-depth learning, here are some useful external resources:

By following this guide, you’ll be able to efficiently retrieve and display values from ACF repeater fields in your WordPress projects.

Scroll to Top

Request A Quote