You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中使用Timber获取ACF Repeater首行数据

Got it, let's figure out how to grab just that first image from your ACF repeater using Timber! You don't need to loop through all the items—here are two straightforward approaches:

Method 1: Grab the first element directly (most efficient)

Since get_field('product_images') returns an array of your repeater rows, you can access the first item directly using the zero-index [0] (arrays start at 0 in PHP/Twig). Always add a check to make sure the array isn't empty first to avoid errors:

{% set product_images = item.get_field('product_images') %}
{% if product_images is not empty %}
  {{ TimberImage(product_images[0].product_image).src('thumbnail') }}
{% endif %}

This skips the loop entirely and gets straight to the first image—super clean and efficient.

Method 2: Loop and break after the first item

If you prefer using a loop (maybe you need to run extra checks on the first item), use Twig's built-in loop.first variable to target the first iteration, then {% break %} to stop the loop right after:

{% for image_item in item.get_field('product_images') %}
  {% if loop.first %}
    {{ TimberImage(image_item.product_image).src('thumbnail') }}
    {% break %}
  {% endif %}
{% endfor %}

The loop.first variable is automatically available in Twig loops and only returns true for the first item. Once we output the image, {% break %} stops the loop from processing the rest of the repeater rows.

Quick Note

Don't skip the empty array check (like in Method 1) or make sure your loop handles empty repeaters gracefully—this prevents PHP/Twig errors if no images have been added to the repeater yet.

内容的提问来源于stack exchange,提问作者mfos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:02:08