最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Issue with custom loop in Archive page

programmeradmin2浏览0评论

I customized my loop in archive.php to display 8 posts per page. However I have an issue passing the args: the loop displays all my posts from all my categories.

Here is my PHP code for the loop:

<?php
$archive_args = array( 'posts_per_page' => 8 );

  query_posts( $archive_args );

  if ( have_posts() ) : while (have_posts()) : the_post();

    get_template_part( 'template-parts/content', 'archive' );

  endwhile;

  wp_reset_postdata();

  else :

    get_template_part( 'template-parts/content', 'none' );

  endif; 
?>

I tried to use WP_query(); or query_posts(); and same issue.

Any help would be much appreciated, thanks!

I customized my loop in archive.php to display 8 posts per page. However I have an issue passing the args: the loop displays all my posts from all my categories.

Here is my PHP code for the loop:

<?php
$archive_args = array( 'posts_per_page' => 8 );

  query_posts( $archive_args );

  if ( have_posts() ) : while (have_posts()) : the_post();

    get_template_part( 'template-parts/content', 'archive' );

  endwhile;

  wp_reset_postdata();

  else :

    get_template_part( 'template-parts/content', 'none' );

  endif; 
?>

I tried to use WP_query(); or query_posts(); and same issue.

Any help would be much appreciated, thanks!

Share Improve this question asked Jan 28, 2020 at 16:52 Mathieu PréaudMathieu Préaud 2035 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

The problem is you aren't saving your custom query's results. To do it your way, you would need to save the query's results to a variable, like so:

$myposts = query_posts( $archive_args );
if ( $myposts->have_posts() ) : while ($myposts->have_posts()) : $myposts->the_post();

However, that's not the most efficient way. WP runs the default query in addition to this custom one. So, you would be better off using pre_get_posts to alter the main query and just using its results - meaning you would not need to do a custom query or add the $myposts part at all.

Your pre_get_posts filter would just be something simple like:

// If this is the main query, not in wp-admin, and it's for an archive
if($query->is_main_query() && !is_admin() && $query->is_post_type_archive()) {
    // Pull 8 posts per page
    $query->set('posts_per_page', '8');
}
发布评论

评论列表(0)

  1. 暂无评论