首页 > 解决方案 > 在 Wordpress 中使用 WP_Query 在循环中显示帖子时遇到问题

问题描述

我在尝试使用 WP_Query 显示当前的 4 个帖子时遇到问题。但是,较早的帖子(第一篇文章)也显示在第一个循环中。

这是我的代码:

<?php
    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => '3'
    );
    $query = new WP_Query( $args ); //show 4 post
    if ( $query->have_posts() ){
        /* Start the Loop */
        while ( $query->have_posts() ) {
            $query->the_post();?>
            <div class="col-md-3 d-flex align-items-stretch">
                <div class="card ">
                    <?php if (has_post_thumbnail()) { 
                        $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full'); 
                        ?>
                        

                        <img class="miniimg" src="<?php echo $featured_img_url;  ?>" width="auto" height="200px">
                    <?php } ?>
                    <div class="card-body">
                        <h4><a href="<?php the_permalink(); ?>">
                            <?php the_title(); 
                            $post_date = get_the_date( 'j F Y' );
                            ?>
                        </a></h4>
                        <p class="card-text"><?php the_excerpt();?></p>
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="btn-group">
                                <button type="button" class="btn btn-sm btn-primary">Read More</button>
                            </div>
                            <small class="text-muted"><?= $post_date; ?></small>
                        </div>
                    </div>
                </div>
            </div>
            <?php 
            $counter++; }
        }
        ?>

这是结果=>结果图片

如何解决这个问题?我的代码有问题吗?谢谢你。

标签: phpwordpress

解决方案


如果指定'posts_per_page' => 3返回 4 个帖子,则几乎 100% 确定第一个帖子是置顶帖子。使用选项ignore_sticky_posts忽略它们。

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 4,
        'ignore_sticky_posts' => 1,
    );
    ...

推荐阅读