dungey_140
dungey_140

Reputation: 2802

wp_query pagination on archive.php

I'm using the following wp_query on a few pages in Wordpress, and as you can see I am trying to ensure the query is paginated. Everything is working successfully on a custom page template page-articles.php, however I'm unable to get the same results on the archive.php template.

The pagination link renders successfully (e.g mydomain.com/category/my-cat/page/2) however upon clicking the link does not work, it just throws a 404 error? How can these links not go anywhere?

I'm assuming there is some issue with using custom wp_query on the archive.php template?

Thanks!

Query

$args = array(
    'post_type'         => 'post',
    'posts_per_page'    => 1,
    'paged'             => $paged,
    'orderby'           => 'date',
    'order'             => 'DESC'
);
$articles = new WP_Query($args );
?>

Loop

<?php if ( $articles->have_posts() ) : ?>
   <?php while ( $articles->have_posts() ) : $articles->the_post(); ?>
       Posts here!
   <?php endwhile; ?>
   <?php wp_reset_postdata(); ?>
<?php endif; ?>

Pagination

<nav>
    <div class="prev"><?php echo get_previous_posts_link( 'Previous', $articles->max_num_pages );   ?></div>
    <div class="next"><?php echo get_next_posts_link( 'Next', $articles->max_num_pages ); ?></div>
</nav>

Upvotes: 0

Views: 4055

Answers (2)

dungey_140
dungey_140

Reputation: 2802

After a bit of digging around, and with help from this article, the below solution solves the issue. Just place this in your functions.php file and thats it. The below implementation works for archives of custom post types, as well as categories.

/**
 * Wordpress has a known bug with the posts_per_page value and overriding it using
 * query_posts. The result is that although the number of allowed posts_per_page
 * is abided by on the first page, subsequent pages give a 404 error and act as if
 * there are no more custom post type posts to show and thus gives a 404 error.
 *
 * This fix is a nicer alternative to setting the blog pages show at most value in the
 * WP Admin reading options screen to a low value like 1.
 *
 */
function custom_posts_per_page( $query ) {

    if ( $query->is_archive('cpt_name') || $query->is_category() ) {
        set_query_var('posts_per_page', 1);
    }
}
add_action( 'pre_get_posts', 'custom_posts_per_page' );

Upvotes: 4

Elvin Haci
Elvin Haci

Reputation: 3572

Yes, it is.

It is because main query of archive.php is kept unchanged while you are playing with WP_QUERY. Try use query_posts() in archive.php.

query_posts($args);

and then default loop (instead of $articles)

<?php if ( have_posts() ) : ?>
   <?php while (have_posts() ) : the_post(); ?>
       Posts here!
   <?php endwhile; ?>
   <?php wp_reset_postdata(); ?>
<?php endif; ?>

Upvotes: 0

Related Questions