Skip to content

Instantly share code, notes, and snippets.

@conkonig
Last active February 17, 2020 10:41
Show Gist options
  • Save conkonig/3a16e49997f89a1a444133c268a6642a to your computer and use it in GitHub Desktop.
Save conkonig/3a16e49997f89a1a444133c268a6642a to your computer and use it in GitHub Desktop.
Wordpress pagination for bootstrap 4 - that works anywhere and doesn't suck
Original credit to renzramos/wordpress-bootstrap-4-pagination - however his only works with the main loop. Small modification.
Now you can use in main query or custom wp query.
```php
<?php
if (!function_exists('pagination_that_doesnt_suck')) {
function pagination_that_doesnt_suck($query = 0)
{
if (!$query) {
global $wp_query;
$query = $wp_query;
}
if ($query->max_num_pages <= 1)
return;
$paged = get_query_var('paged') ? absint(get_query_var('paged')) : 1;
$max = intval($query->max_num_pages);
if ($paged >= 1)
$links[] = $paged;
if ($paged >= 3) {
$links[] = $paged - 1;
$links[] = $paged - 2;
}
if (($paged + 2) <= $max) {
$links[] = $paged + 2;
$links[] = $paged + 1;
}
echo '<div class="pagination-container"><ul class="pagination">' . "\n";
if (get_previous_posts_link())
printf('<li class="page-item">%s</li>' . "\n", get_previous_posts_link());
if (!in_array(1, $links)) {
$class = 1 == $paged ? ' class="page-item active"' : ' class="page-item"';
printf('<li%s><a class="page-link" href="%s">%s</a></li>' . "\n", $class, esc_url(get_pagenum_link(1)), '1');
if (!in_array(2, $links))
echo '<li>…</li>';
}
sort($links);
foreach ((array) $links as $link) {
$class = $paged == $link ? ' class="page-item active"' : ' class="page-item"';
printf('<li%s><a class="page-link" href="%s">%s</a></li>' . "\n", $class, esc_url(get_pagenum_link($link)), $link);
}
if (!in_array($max, $links)) {
if (!in_array($max - 1, $links))
echo '<li>…</li>' . "\n";
$class = $paged == $max ? ' class="page-item active"' : ' class="page-item"';
printf('<li%s><a class="page-link" href="%s">%s</a></li>' . "\n", $class, esc_url(get_pagenum_link($max)), $max);
}
if (get_next_posts_link())
printf('<li class="page-item">%s</li>' . "\n", get_next_posts_link());
echo '</ul></div>' . "\n";
}
}
add_filter('next_posts_link_attributes', 'fix_wp_pagination_link_attributes_bootstrap_4');
add_filter('previous_posts_link_attributes', 'fix_wp_pagination_link_attributes_bootstrap_4');
function fix_wp_pagination_link_attributes_bootstrap_4()
{
return 'class="page-link"';
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment