Search code examples
phpwordpressadvanced-custom-fields

Add pagination to archive.php template


I have created an archive template within my bespoke Wordpress site but I need to add pagination - I have tried different plugins/code but nothing seems to work. I currently have 6 posts setup on the backend but I have limited it to 3 posts per page for testing purposes. Existing code below:

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

$args = array(
    'post_type'  =>  'post',
    'post_status'       =>  'publish',
    'orderby'   => 'date', 
    'order'     => 'ASC',
    'posts_per_page' => 3,
    'paged' => $paged
  );

$posts_query = new WP_Query($args);

if($posts_query->have_posts()) { ?>

    <div class="index-grid">
        <div class="grid-column">
            <?php while($posts_query->have_posts()) {
                $posts_query->the_post(); ?>
                <div class="related-item">
                    <a href="<?php the_permalink(); ?>">
                        <img src="<?php the_field('header_image'); ?>" />
                        <h3 class="title"><?php the_title(); ?></h3>
                        <p class="blurb"><?php the_field('introduction'); ?></p>
                    </a>
                </div>
            <?php } ?>
        </div>
    </div>

    <?php wp_reset_postdata();
}

?>

</section>```

Any help would be greatly appreciated!

Thanks

Solution

  • Try this:

    <div class='pagination'>
      <?php
        $big = 999999999;
          echo paginate_links( array(
          'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
          'format' => '?paged=%#%',
          'current' => max( 1, get_query_var('paged') ),
          'total' => $posts_query->max_num_pages
        ));
      ?>
    <div>