Combining WordPress pagination functions for archives and search results

From the Codex:

To add pagination to your search results and archives, you can use
the following example:

<?php
global $wp_query;

$big = 999999999; // need an unlikely integer

echo paginate_links( array(
  'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
  'format' => '?paged=%#%',
  'current' => max( 1, get_query_var('paged') ),
  'total' => $wp_query->max_num_pages
) );
?>

So based on that, I modified your function:

function pagination_bar( $query = null ) {
    global $wp_query;

    $total_pages = $query ?
        $query->max_num_pages :
        $wp_query->max_num_pages;

    if ( $total_pages > 1 ) {
        $big = 999999999; // need an unlikely integer
        $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,
            'prev_text' => __( '« Previous page' ),
            'next_text' => __( 'Next page »' ),
        ) );
    }
}

and it worked well, both with archives and search results.

I also added support for custom query (i.e. new WP_Query), so that you could for example do:

$my_query = new WP_Query( array( ... ) );
pagination_bar( $my_query );

Leave a Comment