WordPress   

Create custom post loop with pagination in WordPress

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(  
	'post_type' => 'post',
	'post_status' => 'publish',
	'posts_per_page' => 6,
	'paged' => $paged			
);
$loop = new WP_Query( $args ); 
while ( $loop->have_posts() ) : $loop->the_post(); ?> 
<div class="post-card">
	<div class="post-image">
		<img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'full' ); ?>" class="image">
	</div>
	<div class="post-body">
		<p class="published-on"><?php echo get_the_date(); ?></p>
		<h3 class="post-title"><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h3>
	</div> 
</div>
<?php endwhile; ?>
<div class="post-pagination">
	<?php pagination_bar( $loop ); ?>
</div>
<?php wp_reset_postdata(); ?>

Pagination function

function pagination_bar( $custom_query ) {
    $total_pages = $custom_query->max_num_pages;
    $big = 999999999; // need an unlikely integer
    if ($total_pages > 1){
        $current_page = max(1, get_query_var('paged'));
        echo paginate_links(array(
            'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format' => '?paged=%#%',
            'current' => $current_page,
            'total' => $total_pages,
        ));
    }
}
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us