自定义查询WordPress循环中的重复帖子



我是PHP的新手,我正在尝试自定义查询。我总共有 5 个帖子,应该显示在 2 页分页中。下面的代码显示 2 页分页,重复前 3 篇博客文章。我不知道为什么它两次显示前 3 个帖子而不是一次显示所有 5 个帖子。下面是我的索引中的代码部分.php。任何帮助将不胜感激!

<?php
$args = array('post_type' => 'post');
$allPosts = new WP_Query($args);
while ($allPosts->have_posts()) {
$allPosts->the_post(); ?>
<h1 class="nobottommargin"><a href="<?php the_permalink(); ?>"><?php 
the_title(); ?></a></h1>
<p class="notopmargin">Posted by <?php the_author_posts_link(); ?> in 
<?php echo get_the_category_list(', '); ?> on <?php the_time('d/m/Y') ?>.</p>
<p><?php echo wp_trim_words(get_the_content(), 20); ?> <a href="<?php the_permalink(); ?>">read more &raquo;</a></p>
<hr>
<?php } 
echo paginate_links();
?>

我认为您需要添加每页帖子参数。

$args = array(
'posts_per_page' => 3,
'paged' => $paged
'post_type'=>'post'
);

您也可以为paginate_links函数添加参数。 检查paginate_links

解决方案是使您的自定义查询覆盖全局$wp_query变量,这会欺骗WordPress函数认为它是主查询。然后,完成分页后,添加wp_reset_query()以将查询设置回应有的状态。

//WP_Query arguments
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type'              => ['post'],           
'posts_per_page'         => 10,
'paged'                  => $paged,     
'orderby'                => 'title', 
'order'                  => 'ASC',
);
//The Query
global $wp_query;
$wp_query = new WP_Query($args);
//The Loop
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) :
$wp_query->the_post();
//Do Stuff
endwhile;
endif;
//Reset Post Data
wp_reset_postdata();
  • 构建您的自定义循环$args,并包括'paged' => get_query_var( 'paged'(

  • 用新的覆盖$wp_query。所以而不是

$loop = new WP_Query( $args );

您使用

global $wp_query; 
$wp_query = new WP_Query( $args );

最新更新