我正在 WordPress 中设置一个新闻网站,我设置了一个按类别显示新闻的查询(例如:巴西类别、世界类别)。查询就可以了,人家点击的时候,就出现详细的新闻,如我所愿。但是,在底部,我可以选择查看更多新闻,我在其中设置了另一个查询,显示该类别中的更多新闻。我问,如何设置第二个查询,以便它不会与主要新闻重复该选项。例如,它显示新闻“A”,下面会出现新闻“B”和“C”吗?
这是我如何设置第二个查询的代码:
<?php
$args = array(
"post_type" => array("noticias"),
"order" => "randon",
"category_name"=>"mundo",
"posts_per_page" => 2,
"paged' => $paged
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
?>
您的 WP_Query 中有一些错误。当您使用 "random" order by 参数时,您可以使用 PHP cookies 逐步存储显示的新闻(帖子 ID),然后在查询中使用这些帖子 ID 以避免再次显示它们,使用
posts__not_in
争论。
您也必须在初始查询中使用该代码。
代码(带有您重新访问的查询):
// We look if our cookie exist
if( isset($_COOKIE['wp_query_news_ids']) ) {
// cookie exist: we set in it the previous news Ids
$post_ids = explode(',', $_COOKIE['wp_query_news_ids']);
} else {
$post_ids = array(); // Initializing variable
}
// The WP query
$query = new WP_Query( array(
'post_type' => array('noticias'),
'posts_per_page' => 2,
'category_name' => 'mundo',
'paged' => $paged
'orderby' => 'rand', // <== Changed that
'posts__not_in' => $post_ids, // The query will not those previous posts Ids
) );
// Loop through the news (posts)
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
// We add to the array the current post ID
$post_ids[] = $query->post->ID;
// ==> Here your code that display the news
endwhile;
// We set all the displayed news IDs (posts Ids) in the cookie
setcookie('wp_query_news_ids', implode(',' ,$post_ids), time()+86400);
wp_reset_postdata();
else:
unset($_COOKIE['wp_query_news_ids']); // Now we can remove the cookie
echo 'No more news found';
endif;
}