phpwordpresswordpress-theming

Wordpress Pagination in Custom theme


I am using the following code to generate pagination on my wordpress pages:

<?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
    ) );
?>

Notice 'format' => '?paged=%#%'. According to the Codex there'd be a different format for pretty links i.e. codex says

format (string) (optional) Used for Pagination structure. The default value is '?page=%#%', If using pretty permalinks this would be '/page/%#%', where the '%#%' is replaced by the page number. Default: '?page=%#%'

What I'm getting is, I'd have to change the php code in my theme file whenever I change the permalinks format. That'd be pretty much tedious, so Is there any way that I can make my pagination adapt itself to the permalink style i.e. it doesn't break if I change the permalinks style to pretty?


Solution

  • I dug up a little something in the Wordpress Codex here

    using_mod_rewrite_permalinks - Returns true your blog is using "pretty" permalinks via mod_rewrite.

    So try this

    <?php
    global $wp_query;
    global $wp_rewrite;
    
    $big = 999999999; // need an unlikely integer
    
    if( $wp_rewrite->using_mod_rewrite_permalinks() ) {
        myformat = '/page/%#%';
    } else {
        myformat = '?page=%#%';
    }
    
    echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => myformat,
        'current' => max( 1, get_query_var('paged') ),
        'total' => $wp_query->max_num_pages
    ) );
    ?>