php – 高级自定义字段显示最后三个子转发器行

前端之家收集整理的这篇文章主要介绍了php – 高级自定义字段显示最后三个子转发器行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用高级自定义字段(ACF)从事件页面提取转发器信息,并在主页上显示事件的缩短列表.

我已经设置了一个转发器,允许用户输入事件发生的月份(允许它们放入多个月的事件),然后是子转发器,允许它们为给定的月份添加多个事件.示例如下:

游行

> 3月9日活动
> 3月12日活动
> 3月28日活动

四月

> 4月1日活动
> 4月28日活动

这是事件页面上的当前输出,它按预期工作.

在网站的主页上,我需要将最新的3个事件(位于列表底部的事件是最新事件)拉出并显示在主页上.

我在主页上拉动和显示事件时没有问题.我遇到的问题是显示最后三个事件(子转发器)在月份之间交叉的事件(父转发器).

简单地使用跨越if,while,语句的PHP循环限制事件输出仅限制该月输出的事件数.我目前在主页上使用的代码如下.

@H_404_22@<?PHP if( have_rows('event_month',1263)): ?> <ul> <?PHP while ( have_rows('event_month',1263) ) : the_row(); ?> <?PHP if( have_rows('event',1263)):; ?> <?PHP while ( have_rows('event',1263) ) : the_row(); ?> <li> <h3> <a href="<?PHP echo esc_url( home_url( '/' ) ); ?>events/"><?PHP $summary = get_sub_field('event_title'); echo substr($summary,34),'...'; ?></a> <span><?PHP the_sub_field('event_day_of_week');?>,<?PHP the_sub_field('event_sub_month');?> <?PHP the_sub_field('event_day');?></span> </h3> </li> <?PHP endwhile; ?> <?PHP else: ?> <p>Show dates to be announced soon.</p><?PHP the_sub_field('event_title'); ?> <?PHP endif; ?> <?PHP endwhile; ?> </ul>

如果我们捕获三个最新事件,主页上我想要的输出会是什么样子:

> 3月28日活动
> 4月1日活动
> 4月28日活动

可能你应该用而不是用.并考虑以下算法:

1) Get the last row from event_month

2) Count the number of events in that month

3) If the number of events are more than or equal to 3.

3.1) Get last 3 events and display them

4) Else count the number of remaing events (3-<<events in last month>>)

4.1) Now get the second last row and repeat steps 2,3,4

因此,使用上面的逻辑,您的代码应该类似于:

@H_404_22@<?PHP function getEvents($rows,$noOfEvents){ $resultArray = array(); if($rows && count($rows > 0)) { $events = $rows[count($rows)-1]['event']; $events = is_array($events) ? $events : array(); $eventCount = count($events); if($eventCount < $noOfEvents){ $noOfOtherEvents = $noOfEvents-$eventCount; array_pop($rows); $iterate = getEvents($rows,$noOfOtherEvents); $resultArray = array_merge($events,$iterate); } else{ $resultArray = array_slice($rows,0-$eventCount,$eventCount); } return $resultArray; } $rows = get_field('event_month',1263); if($rows) { $requiredEvents = getEvents($rows,3); //3 or how many ever last you want foreach($requiredEvents as $event){ var_dump($event); //this should have all you need like $event['event_title'],$event['event_day'],ect... } }

猜你在找的PHP相关文章