In the process of building Scarlett, a Bootstrap WordPress theme for small businesses and freelancers, I frequently ran into issues where I needed to modify default WordPress output to fit it into Bootstrap’s styles. One such instance was when I wanted to paginate the blog index of the Scarlett theme.
Normally, you would use get_next_posts_link();
and get_previous_posts_link();
to get a simple pager. But, these functions either return a link or an empty string.
So, to coax that default output into something that would work with Bootstrap’s styles I ended up with this:
“`<ul class=”pager”>
<?php
$next = get_next_posts_link( 'Newer →');
$prev = get_previous_posts_link( 'Older ←' );
if ( !empty($prev) ) {
echo '<li class="previous">'.$prev.'</li>';
}
if ( !empty($next) ) {
echo '<li class="next">'.$next.'</li>';
}
?>
</ul>
<br /><br /><br /><h3>Factoring Pager Snippet into a Function</h3>
As I only needed to add a Bootstrap pager on the index page, I simply used this snippet directly in the <code>index.php</code>. But, if you were to add a pager in multiple parts of your theme, I would suggest breaking this functionality out into a function that goes into <code>functions.php</code>. Here is an example of what that might look like.
```<?php
function bootstrap_wp_pager() {
echo '<ul class="pager">';
$next = get_next_posts_link( 'Newer →');
$prev = get_previous_posts_link( 'Older ←' );
if ( !empty($prev) )
echo '<li class="previous">'.$prev.'</li>';
if ( !empty($next) )
echo '<li class="next">'.$next.'</li>';
echo '</ul>';
}
This snippet would need to go in your functions.php
. Then anytime you needed to add a pager, you would simply use <?php bootstrap_wp_pager(); ?>
in your code.