You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中WP_Query设置showposts=1却返回2篇文章问题求助

问题修复方案

  • 首先替换废弃参数:showposts 是WordPress早已弃用的参数,虽然目前仍有向下兼容,但请先替换为官方推荐的 posts_per_page 参数。
  • 新增忽略置顶文章参数:你遇到的返回数量超出设置值的核心原因几乎都是WordPress默认会将全局置顶文章额外插入查询结果首位,且不计入你设置的返回条数限制。在查询参数中加入 'ignore_sticky_posts' => true 即可禁用该逻辑,严格按照你设置的数量返回文章。
  • 修正摘要获取逻辑:你现有代码中 the_excerpt() 是直接输出内容的函数,不会返回字符串赋值给变量,需要替换为 get_the_excerpt() 才能正常执行后续的截断逻辑。
  • 排查第三方冲突:如果修改后问题仍然存在,可临时禁用所有自定义插件、切换为WordPress默认主题,验证是否是其他主题/插件通过 pre_get_posts 钩子篡改了你的查询参数。

修正后完整代码

<?php $args = array(
    'post_status' => 'publish',
    'post_type' => 'post',
    'orderby' => 'date',
    'cat' => 0,
    'order' => 'DESC',
    'posts_per_page' => 1,
    'ignore_sticky_posts' => true,
);
$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 = get_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(); ?>

内容的提问来源于stack exchange,提问作者N.Tuyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:15:05