How To Add Pagination To Your WordPress Theme

Share Now

Share on facebook
Share on pinterest
Share on twitter
Share on linkedin
Share on email

#Query On main page

<?php
$args = array(
    'post_type' => 'before-after',
    'posts_per_page' => 3,
    'paged' => $paged
);
$bf_af_query = new WP_Query($args);
?>
<?php if ($bf_af_query->have_posts()): ?>
<?php while ($bf_af_query->have_posts()):
$bf_af_query->the_post(); ?>
<a id="bf-af-card" href="<?php echo the_permalink(); ?>">
<h4><?php the_title(); ?></h4>
</a>
<?php endwhile;
wp_reset_postdata(); ?>
<?php else:  ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

# Pagination HTML block

<div class="pagination">
    <div class="container">
        <div class="row">
            <div class="col-12 col-lg-12 col-xl-12">
            <!-- Pagination Support -->
            <?php bfaf_theme_pagination(); ?>
            <!-- Pagination Support -->
            </div>
        </div>
    </div>
</div>

# Code On functions.php

// Pagination Start
// Numbered Pagination
if ( !function_exists( 'bfaf_theme_pagination' ) ) {
	
	function bfaf_theme_pagination( ) {
		
		$prev_arrow = is_rtl() ? '→' : '←';
		$next_arrow = is_rtl() ? '←' : '→';
		
		global $wp_query, $bf_af_query;
		$total = $wp_query->max_num_pages;
		$big = 999999999;

		//before after query
		if ( $bf_af_query ) {
			$total = $bf_af_query->max_num_pages;
		} else {
			$total = $wp_query->max_num_pages;
		}
		
		if( $total > 1 )  {
			 if( !$current_page = get_query_var('paged') )
				 $current_page = 1;
			 if( get_option('permalink_structure') ) {
				 $format = 'page/%#%/';
			 } else {
				 $format = '&paged=%#%';
			 }
			echo paginate_links(array(
				'base'			=> str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
				'format'		=> $format,
				'current'		=> max( 1, get_query_var('paged') ),
				'total' 		=> $total,
				'mid_size'		=> 3,
				'type' 			=> 'list',
				'prev_text'		=> $prev_arrow,
				'next_text'		=> $next_arrow,
			 ) );
		}
	}
	
}

How To Add Pagination To Your WordPress Theme

 

Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert