首页 > 解决方案 > 使用带有参数“showposts”= 1 的 WP_query,但结果显示为 2 - Wordpress

问题描述

当我收到一个我不知道为什么的错误时,我正在尝试获取最新的 wp 帖子。

我使用 showpost 来获取展示次数,但结果总是多了一篇。

我尝试搜索但不知道问题的原因在哪里。我尝试用 posts_per_page 替换 showposts 但仍然是同样的错误。

遇到同样错误的朋友请帮帮我,谢谢!

<?php $args = array(
    'post_status' => 'publish',
    'post_type' => 'post',
    'orderby' => 'date',
    'cat' => 0,
    'order' => 'DESC',
    'showposts' => 1,
);
$getposts_related = new WP_query($args);

if ($getposts_related->have_posts()) :
    while ($getposts_related->have_posts()) : $getposts_related->the_post();
        $placeholder = get_field('logo', 'option'); ?>
        <div class="col-6 col-md-4 col-lg-4 pb-4">
            <div class="baiviet-wrap">
                <a href="<?php the_permalink(); ?>">
                    <div class="thumbnail">
                        <img src="<?php
                        $url = wp_get_attachment_url(get_post_thumbnail_id(), 'thumbnail');
                        if ($url) {
                            echo $url;
                        } else {
                            echo $placeholder;
                        }
                        ?>" alt="<?php the_title(); ?>">
                    </div>
                    <div class="tieu-de">
                        <h3><?php the_title(); ?></h3>
                    </div>
                </a>
                <div class="description">
                    <?php
                    $excerpt = the_excerpt();
                    $excerpt = substr($excerpt, 0, 200);
                    $result = substr($excerpt, 0, strrpos($excerpt, ' '));
                    echo $result; ?>
                </div>
                <div class="col-6 col-md-6 col-lg-6 cta-baiviet">
                    <a href="<?php echo get_permalink(); ?>">
                        <div class="detail-product btn-kgin kgin-sharp-5">
                            <div class="btn-wrap kgin-sharp-5">
                                <span>Xem chi tiết</span><i
                                        class="fas fa-angle-double-right"></i>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    <?php endwhile;
endif;
wp_reset_postdata(); ?>

标签: wordpress

解决方案


你不应该使用showposts

尝试posts_per_page与 一起使用paged。像这样:

$args = array(
    'post_status' => 'publish',
    'post_type' => 'post',
    'posts_per_page' => 1,
    'paged' => 1
    'cat' => 0,
    'orderby' => 'date',
    'order' => 'DESC',
);

推荐阅读