首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将wordpress循环限制为10或20个帖子

问将wordpress循环限制为10或20个帖子
EN

Stack Overflow用户
提问于 2021-04-22 20:33:35
回答 2查看 39关注 0票数 1

我正在使用自定义字段插件,并且我在wordpress中制作了一些自定义字段。

我使用下面的代码编写php来把自定义字段放在前面,但是它不会停止循环,我只需要循环10到20次。

所以我想改变,但我不知道如何改变。

代码语言:javascript
复制
<?php if( $banner_query2->have_posts() ): ?>
        <?php while ( $banner_query2->have_posts() ) : $banner_query2->the_post(); ?>
                
                    

<?php 
        $post_id = get_the_ID();
        
        ?>
        <?php
            $featured_matches = get_field('locations');
            if( $featured_matches ): ?>
                <ul>
                <?php foreach( $featured_matches as $post ): 

                    // Setup this post for WP functions (variable must be named $post).
                    setup_postdata($post); ?>
                    
            <!--             <a href="<?php //the_permalink(); ?>"><?php //the_title(); ?></a> -->
            

                        <span><?php the_field( 'customfile' ); ?></span>
                        <span><?php the_field( 'customfile2' ); ?></span>
                        
                    
                <?php endforeach; ?>
                </ul>
                <?php 
                // Reset the global post object so that the rest of the page works correctly.
                wp_reset_postdata(); ?>
            <?php endif; ?>
                    
                
            
        <?php endwhile; ?>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-23 17:16:05

在wordpress中,如果您只在foreach循环的末尾添加break;,就可以很好地工作。

票数 -1
EN

Stack Overflow用户

发布于 2021-04-22 20:47:34

通过使用break;,可以提前终止一个foreach循环或其他任何循环,这样您所需要做的就是维护一个计数器,当它达到神奇的数字时,就会break循环。

代码语言:javascript
复制
<?php 
    $cnt = 0;
    $maxcnt = 10;
    foreach( $featured_matches as $post ): 

        // do your funky stuff

        $cnt++;
        if ( $cnt >= $maxcnt ) :
            break;
        endif;
    endforeach;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67213399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档