Skip to content

Instantly share code, notes, and snippets.

@DrizzlyOwl
Last active March 18, 2016 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrizzlyOwl/3647f4d296f2c144e4b4 to your computer and use it in GitHub Desktop.
Save DrizzlyOwl/3647f4d296f2c144e4b4 to your computer and use it in GitHub Desktop.
WordPress pagination snippet
<?php
// Get the header
get_header();
// Results pagination offset
$offset = ($_GET["offset"] ? $_GET["offset"] : 0);
global $wp_query;
$found_posts = $wp_query->found_posts;
$ppp = $wp_query->query_vars["posts_per_page"];
$total_pages = $wp_query->max_num_pages;
?>
<main class="section">
<div class="container">
<div class="search-results">
<?php if ( have_posts() ): ?>
<?php if ($found_posts > 10): ?>
<p><strong><?php echo $offset+1; ?> to <?php echo $offset+$ppp; ?> of <?php echo $found_posts; ?> results</strong></p>
<?php else: ?>
<p>Showing <strong><?php echo $found_posts; ?> result(s)</strong></p>
<?php endif; ?>
<?php while ( have_posts() ): the_post(); ?>
<article>
<!-- the post -->
</article>
<?php endwhile; ?>
<section class="search-pagination">
<!-- Previous Results Page -->
<?php if ($offset): ?>
<a href="<?php echo esc_url( add_query_arg( 'offset', $offset-$ppp ) ); ?>" class="btn--prev | search-pagination__prev">Previous Page</a>
<?php else: ?>
<span class="btn--prev | search-pagination__prev search-pagination--disabled">Previous Page</span>
<?php endif; ?>
<!-- Pagination -->
<ol class="search-pagination__list">
<?php for ($i = 1; $i <= $total_pages; $i++) : ?>
<li>
<a href="<?php echo esc_url( add_query_arg( 'offset', ($i*10)-10 ) ); ?>" class="<?php echo ((($i*10)-10) == $offset ? "search-pagination__link--disabled" : ""); ?> search-pagination__link"><?php echo $i; ?></a>
</li>
<?php endfor; ?>
</ol>
<!-- Next Results Page -->
<?php if ($found_posts-$offset > 10): ?>
<a href="<?php echo esc_url( add_query_arg( 'offset', $offset+$ppp ) ); ?>" class="btn--next | search-pagination__next">Next Page</a>
<?php else: ?>
<span class="btn--next | search-pagination__next search-pagination--disabled">Next Page</span>
<?php endif; ?>
</section>
<?php else: ?>
<!-- No posts found -->
<?php endif; ?>
</div>
</div>
<!-- .container -->
</main>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment