分享这篇文章

In this article, learn how you can add a Repeater Field to your block using ACF.

If you missed our previous article titled: Creating a Custom Gutenberg Block Using Advanced Custom Fields (ACF) in WordPress, make sure to check it out before you dive into this advanced tutorial on using ACF Repeater Fields.

Repeater fields allow you to create a set of sub-fields that can be repeated multiple times, which is particularly useful when creating blocks like image galleries, testimonial sliders, or lists of content.

Create the Repeater Field

Navigate to the ACF settings on your WordPress dashboard. Create a new Field Group or select an existing one that you want to add a repeater field to. Add a new field and select the field type as Repeater. You can then add sub-fields to the repeater field as required.

Update Block Template

Next, update the block’s PHP template to handle the repeater field. If your block’s name is testimonial, your file should be block-testimonial.php. This file should contain PHP and HTML to display the content of your block. If the name of your repeater field is testimonial_repeater, and it has two subfields testimonial_name 还有 testimonial_text, your PHP code may look like:

<code><?php 
  if (have_rows('testimonial_repeater')) : 
    while (have_rows('testimonial_repeater')) : the_row();
      $name = get_sub_field('testimonial_name');
      $text = get_sub_field('testimonial_text');
?>
      <div class="testimonial">
        <h2><?php echo $name; ?></h2>
        <p><?php echo $text; ?></p>
      </div>
<?php 
    endwhile;
  endif; 
?>

This code uses ACF’s have_rows function to check if any rows exist for the repeater field, and then the_row function to loop through each row. The get_sub_field function is used to retrieve the value of the sub-fields.

Use the Block

Finally, you can add the block to any post or page, and you will see the repeater field in the editor. You can add as many rows as you need, and each row will be displayed on the front-end as defined in your block’s PHP template.

Remember that repeater fields are a premium feature of ACF, so you need ACF Pro to use them. Also, make sure your theme’s CSS styles the .testimonial class (or whatever class you use) appropriately to achieve the desired appearance.

Please note that the above PHP code is a very basic implementation and doesn’t contain any error checks. In a production environment, you might want to add more checks to make sure the code doesn’t break if certain fields are empty.

准备好迁移您的网站了吗?

首先进行免费的无义务网站评估。我们将对您的项目进行评估,推荐合适的平台,并为您提供明确的报价。

保证零数据丢失
完整 SEO 保留与重定向映射
准时且按预算交付
专业化的平台专家,而非泛泛的专家

请告诉我们您的网站信息

"*"*” 表示必填字段

此字段用于验证目的,不应更改。
姓名*