Custom Pagination for WordPress Taxonomy Archive

By default, A custom taxonomy archive page uses WordPress reading settings to decide the number of posts to display. But, Those default settings might not be good enough for your project needs. So, You need a way to change that number to fulfill your requirements.

I came across this while developing a real estate theme and in that theme I have a custom post type ‘property’ that has a custom taxonomy ‘property-city’. So, I am going to provide the simplified version of code from my theme to share the solution.

A simplified version of custom taxonomy archive page will have a WordPress loop working in it similar to the code snippet given below. The only addition is the pagination function.

if ( have_posts() ) :
 while ( have_posts() ) :
 the_post();
 // output property post here
 endwhile;
 global $wp_query;
 inspiry_pagination( $wp_query ); // custom pagination function
endif;

The pagination function’s code snippet is given below.

function inspiry_pagination( $query ) {
    echo "<div class='pagination'>";
    $big = 999999999; // need an unlikely integer
    echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url ( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'prev_text' => __( '<i class="fa fa-angle-left"></i>', 'inspiry' ),
        'next_text' => __( '<i class="fa fa-angle-right"></i>', 'inspiry' ),
        'current' => max( 1, get_query_var ( 'paged' ) ),
        'total' => $query->max_num_pages,
    ) );
    echo "</div>";
}

Now, We have a basic loop and related pagination function and it is using WordPress default settings to determine the number of properties to display on a page.

So, We are going to change that using ‘pre_get_posts’ action. As displayed in code snipped below.

function inspiry_update_taxonomy_pagination( $query ) {
    if ( is_tax( 'property-city' ) ) ) {

        // Theme options array
        global $inspiry_options;

        if ( $query->is_main_query() ) {

            // Get number of properties from theme options
            $number_of_properties = $inspiry_options['archive_properties_number'];

            if ( !$number_of_properties ) {
                $number_of_properties = 6;  // default number
            }
        
            $query->set ( 'posts_per_page', $number_of_properties );
        }
    }
}

add_action( 'pre_get_posts', 'inspiry_update_taxonomy_pagination' );

After this we can use theme options to change the number of properties to display on a property city taxonomy archive page.

I hope above given code snippets will help you do it for your project.

Share

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *