I'm creating a custom theme and I'm struggling to get pagination working on my archive.php template.
I've tried to adapt the code I'm using on my main blog page, but it's simply displaying all blog posts rather than just those with a certain tag or category.
Any ideas where I'm going wrong and how to get the archive.php template working as it should be WITH pagination?
Thanks in advance,
Tom
<?php get_header(); ?>
<!-- PAGE INTRODUCTION -->
<div class="container">
<h1 class="page_title"><?php the_archive_title(); ?></h1>
</div>
<!-- PAGE CONTENTS -->
<div class="container">
<div class="row">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => $paged
);
$custom_query = new WP_Query( $custom_args );
?>
<?php if( $custom_query->have_posts() ) : while( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
<div class="item">
<h3><?php the_title(); ?></h3>
<a href="<?php the_permalink(); ?>">Read more</a>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
</div>
<!-- PAGINATION -->
<?php
if (function_exists(custom_pagination)) {
custom_pagination($custom_query->max_num_pages,"",$paged);
}
?>
</div>
<?php get_footer(); ?>
WP_Query
on archive pages, if you're displaying the main loop.. Just display the posts that already fetched from the database by the main WordPress query that runs automatically on page load. Pagination would also conflict with the main query, e.g. if it had 2 pages only, and yet your custom query had 3 or more pages.pre_get_posts
hook to modify the main query's args.pre_get_posts
to modify the main query to get what you want and use a standard post loop instead of creating a brand new loop with a customWP_Query
that has the parameters you wanted. Then the official pagination functions will work. What you're doing right now doubles the amount of work WP has to do and doubles the queries it makes, and introduces lots of new problems