WordPress pagination

<?php

function v5_get_pagination( $range = 3, $prevanchor = '&laquo;', $nextanchor = '&raquo;' ) {

    global $wp_query;
    global $paged; // current page
    if ( !$paged )
        $paged = 1;

    $max    = $wp_query->max_num_pages;
    if ( $max == 1 )
        return;

    $start  = intval( $paged - $range / 2 );
    $stop   = intval( $paged + $range - $range / 2 );

    if ( $start < 1 ) { 
        $stop   = $stop - $start;
        $start  = 1;  
    }
    if ( $stop > $max ) {
        $start  = $start - ( $stop - $max ); // fixme check > 0
        $stop   = $max; 
        if ( $start < 1 ) 
            $start  = 1;  
    }
    if ( $start > 1 ) { 
        $back = true; 
        if ( $start > 2 ) 
            $back_separator = true; 
    }
    if ( $stop < $max ) {
        $forward = true; 
        if ( $stop < $max - 1 ) 
            $forward_separator = true; 
    }

    if ( $stop < $start )
        return;

    if ( $back ) {
        echo '<span class="prev">';
        previous_posts_link( $prevanchor );
        echo "</span>\n";
    }
    else {
        echo '<span class="prev">';
        echo $prevanchor;
        echo "</span>\n";
    }
    if ( $back_separator ) {
        echo '<span><a href="' . get_pagenum_link( 1 ) . '">1</a></span>';
        echo '<span> ... </span>';
    }
    for ( $i = $start; $i <= $stop; $i++ ) {
        echo '<span><a href="' . get_pagenum_link( $i ) .'"'; 
        if ( $i == $paged ) echo ' class="current"';
        echo ">$i</a></span>\n";
    }

    if ( $forward_separator ) {
        echo '<span> ... </span>';
        echo '<span><a href="' . get_pagenum_link( $max ) . '">' . $max . '</a></span>';
    }
    if ( $forward ) {
        echo '<span class="next">';
        next_posts_link( $nextanchor );
        echo "</span>\n";
    }
    else {
        echo '<span class="next">';
        echo $nextanchor;
        echo "</span>\n";
    }
}
?>

1 comment

  1. avatar
    wrote this comment on

    make sure to use esc_url() on the get_pagenum_link() calls!

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.