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

如何为WordPress/ACF关系字段的最后两篇文章单独包裹div

解决ACF关系字段分块展示文章的问题

嘿,这个需求很好实现,咱们可以把循环拆成两部分来处理——先单独输出第一篇选中的文章,再把剩下的两篇打包进一个独立的<div>里。这里给你调整后的代码,注释都标清楚了:

<?php 
$items = get_field('my_items'); 
if( $items && count($items) >= 1 ): ?> 
    <div class="my-items">
        <!-- 输出第一篇文章 -->
        <?php $first_item = array_shift($items); ?>
        <div class="item">
            <!-- 这里放你的第一篇文章内容,比如: -->
            <h3><?php echo get_the_title($first_item->ID); ?></h3>
            <?php echo get_the_excerpt($first_item->ID); ?>
        </div>

        <!-- 如果还有剩下的文章(也就是最后两篇),打包进单独的div -->
        <?php if( !empty($items) ): ?>
            <div class="last-two-items">
                <?php foreach( $items as $item ): ?>
                    <div class="item">
                        <!-- 这里放剩下两篇的内容,比如: -->
                        <h3><?php echo get_the_title($item->ID); ?></h3>
                        <?php echo get_the_excerpt($item->ID); ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
<?php endif; ?>

代码逻辑说明:

  • 先用array_shift()从$items数组里取出第一个元素(也就是用户选中的第一篇文章),单独输出它的结构。
  • 剩下的元素会自动留在$items数组里,之后判断数组不为空时,把它们包裹进last-two-items这个容器里。
  • 这样就能完美实现“第一篇单独展示,最后两篇用单独div包裹”的效果啦。

另外如果你更习惯用索引判断的方式(不用修改原数组),也可以这么写:

<?php 
$items = get_field('my_items'); 
if( $items ): ?> 
    <div class="my-items">
        <?php $index = 0; ?>
        <?php foreach( $items as $item ): ?>
            <?php if( $index === 0 ): ?>
                <!-- 第一篇文章 -->
                <div class="item">...</div>
            <?php else: ?>
                <!-- 从第二篇开始,先判断是否是第二篇,打开包裹div -->
                <?php if( $index === 1 ): ?>
                    <div class="last-two-items">
                <?php endif; ?>
                    <div class="item">...</div>
                <!-- 最后一篇的时候关闭包裹div -->
                <?php if( $index === count($items)-1 ): ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
            <?php $index++; ?>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

两种方法都能达到你的需求,选你觉得更顺手的就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:17:51