简体   繁体   English

在while循环之后,限制if语句中的项目数

[英]Limit the number of items in if statement, after a while loop

I have a custom-made calendar lister in wordpress, which gets the custom-post type Events, which have an ACF field with the Events' date and compares it with today's date to list it. 我在wordpress中有一个自定义的日历列表器,它获取自定义帖子类型的事件,该事件具有一个带有事件日期的ACF字段,并将其与今天的日期进行比较以将其列出。 I want to limit the number of the posts to 5, but with the logic that filters out 5 events in the while loop the older events also get in the filter and count in the 5, so in the end with the comparison they are also counted in, and for eg. 我想将帖子数限制为5个,但是通过在while循环中过滤掉5个事件的逻辑,较旧的事件也将进入过滤器并计入5个,因此最后通过比较它们也被计算在内在,例如。 if I have 2 older events only 3 are show in the if statement. 如果我有2个较旧的事件,则if语句中仅显示3个事件。 Here is the code: 这是代码:

    $args = array( 
    'post_type' => 'events', 'meta_key'=>'date', 'orderby'=>'meta_value', 'order'=>'ASC', 'posts_per_page'=>5 );

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post(); 

    $title = get_the_title();

    $maindate = DateTime::createFromFormat('Ymd', get_field('date'));
    $today = DateTime::createFromFormat('Ymd', date('Ymd'));

if ( $maindate >= $today ) :

... + then the html code with the elements ... +然后是带有元素的html代码

Any idea how can I restructure it? 知道如何重组吗?

If I understand you correctly you want to list the 5 upcoming events, and leave out the old ones. 如果我对您的理解正确,那么您想列出5个即将发生的事件,而忽略旧的事件。 You now filter them in your while loop, but you can better filter them in your query. 现在,您可以在while循环中对其进行过滤,但可以在查询中更好地对其进行过滤。

ACF uses Wordpress meta fields (see this link ), so you can query on those as well. ACF使用Wordpress元字段(请参阅此链接 ),因此您也可以对其进行查询。 This would come down to something like this: 这将归结为这样的事情:

$args = array( 
    'post_type' => 'events', 
    'meta_key'=>'date', 
    'meta_query' => [
        ['key' => 'date', 
         'value' => date('Y-m-d'), 
         'compare' => '>=']
     ],  
     'orderby'=>'meta_value', 
     'order'=>'ASC', 
     'posts_per_page'=>5 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM