Useful Pagination Function for WordPress

It’s not always easy to style WordPress’s post pagination links using CSS only. Here’s a function that will output pagination links. You can use it to customise the HTML output in your WordPress theme.

WordPress posts can be broken into multiple pages using the <!--nextpage--> quicktag. I’ve written this function to output WordPress numerical pagination links using the HTML format expected by Zurb Foundation’s Pagination links. This is based on WordPress’ own wp_link_pages function.

[GARD]

function gc_link_pages() {
  global $page, $numpages, $multipage, $more;
  $output = '';

  if ( $multipage && is_singular() ) {
    $output = '<div class="alignright"><span style="font-size:.7rem;color:#999">PAGES</span> <ul class="pagination alignright">';

    for ( $i = 1; $i <= $numpages; $i++ ) {
      $link = '';

      // Add left arrow to start of page list
      if ($i==1 && $page==1) {
        $link .= '<li class="arrow unavailable"><a href="">«</a></li>';
      } elseif ($i==1) {
        $link .= '<li class="arrow">' . _wp_link_page($page-1) . '«</a></li>';
      }

      // Add page number links
      if ($page == $i) {
        $link .= '<li class="current">' . _wp_link_page($i) . $i . '</a></li>';
      } else {
        $link .= '<li>' . _wp_link_page($i) . $i . '</a></li>';
      }

      // Add right arrow to end of page links
      if ( $page==$numpages && $i==$numpages) {
        $link .= '<li class="arrow unavailable"><a href="">»</a></li>';
      } elseif ($i==$numpages) {
        $link .= '<li class="arrow">' . _wp_link_page($page+1) . '»</a></li>';
      }

      /**
      * Filter the HTML output of individual page number links.
      *
      * @param string $link The page number HTML output.
      * @param int    $i    Page number for paginated posts' page links.
      */
      $link = apply_filters( 'wp_link_pages_link', $link, $i );
      $output .= $link;
    }
    $output .= '</ul></div>';
  }

  $html = apply_filters( 'wp_link_pages', $output, $args );
  echo $html;

}

[GARD]


COMMENTS