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

WordPress分类新闻WP_Query:如何避免「查看更多」显示重复文章?

要实现「查看更多」不加载已展示过的文章,核心是排除已显示的文章ID,结合你的代码,按以下步骤调整:

第一步:收集已展示的文章ID

在你初始展示新闻的第一个WP_Query循环里,把每篇文章的ID存入一个数组,比如$displayed_post_ids:

<?php
// 初始查询(展示第一组新闻)
$initial_args = array(
    "post_type" => "noticias",
    "orderby" => "rand",
    "category_name" => "mundo",
    "posts_per_page" => 1 // 假设你第一次只显示1篇,比如新闻"A"
);
$initial_query = new WP_Query($initial_args);

// 初始化存储已展示ID的数组
$displayed_post_ids = array();

if ($initial_query->have_posts()) :
    while ($initial_query->have_posts()) : $initial_query->the_post();
        // 输出文章内容...
        
        // 将当前文章ID加入数组
        $displayed_post_ids[] = get_the_ID();
    endwhile;
    wp_reset_postdata();
endif;
?>

第二步:修改「查看更多」的查询参数

在你的第二个查询里,添加post__not_in参数排除已展示的ID,同时修正代码里的两处错误:

  • 随机排序的参数是orderby而非order,值为rand
  • paged的引号写错了,要和其他参数保持一致的双引号,且确保$paged变量正确获取

修改后的「查看更多」查询代码:

<?php
// 获取当前分页,默认值为1
$paged = get_query_var('paged', 1);

$args = array(
    "post_type" => array("noticias"),
    "orderby" => "rand", // 修正随机排序参数
    "category_name" => "mundo",
    "posts_per_page" => 2,
    "paged" => $paged, // 修正引号错误
    "post__not_in" => $displayed_post_ids // 排除已展示的文章ID
); 

$query = new WP_Query( $args );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        // 输出更多文章内容...
    endwhile;
    wp_reset_postdata();
endif;
?>

额外注意事项

  • 如果你的「查看更多」是通过AJAX加载,需要把$displayed_post_ids作为参数传递给AJAX接口,在后端查询时使用post__not_in排除
  • 确保每次加载更多后,更新$displayed_post_ids数组,把新加载的文章ID也加入,避免后续重复加载

内容的提问来源于stack exchange,提问作者Sérgio Junior

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:28:28