Skip to content

Instantly share code, notes, and snippets.

@mtx-z
Last active April 4, 2023 12:55
Show Gist options
  • Save mtx-z/f95af6cc6fb562eb1a1540ca715ed928 to your computer and use it in GitHub Desktop.
Save mtx-z/f95af6cc6fb562eb1a1540ca715ed928 to your computer and use it in GitHub Desktop.
Wordpress 5.4 Bootstrap 4.4 pagination (with custom WP_Query() and global $wp_query support) (UPDATED for Bootstrap 5: https://gist.github.com/mtx-z/af85d3abd4c19a84a9713e69956e1507)
<?php
/**
* @param WP_Query|null $wp_query
* @param bool $echo
* @param array $params
*
* @return string|null
*
* UPDATE for Bootstrap 5.0: https://gist.github.com/mtx-z/af85d3abd4c19a84a9713e69956e1507
*
* Accepts a WP_Query instance to build pagination (for custom wp_query()),
* or nothing to use the current global $wp_query (eg: taxonomy term page)
* - Tested on WP 5.7.1
* - Tested with Bootstrap 4.4
* - Tested on Sage 9.0.9
*
* INSTALLATION:
* add this file content to your theme function.php or equivalent
*
* USAGE:
* <?php echo bootstrap_pagination(); ?> //uses global $wp_query
* or with custom WP_Query():
* <?php
* $query = new \WP_Query($args);
* ... while(have_posts()), $query->posts stuff ... endwhile() ...
* echo bootstrap_pagination($query);
* ?>
*/
function bootstrap_pagination( \WP_Query $wp_query = null, $echo = true, $params = [] ) {
if ( null === $wp_query ) {
global $wp_query;
}
$add_args = [];
//add query (GET) parameters to generated page URLs
/*if (isset($_GET[ 'sort' ])) {
$add_args[ 'sort' ] = (string)$_GET[ 'sort' ];
}*/
$pages = paginate_links( array_merge( [
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $wp_query->max_num_pages,
'type' => 'array',
'show_all' => false,
'end_size' => 3,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => __( '« Prev' ),
'next_text' => __( 'Next »' ),
'add_args' => $add_args,
'add_fragment' => ''
], $params )
);
if ( is_array( $pages ) ) {
//$current_page = ( get_query_var( 'paged' ) == 0 ) ? 1 : get_query_var( 'paged' );
$pagination = '<div class="pagination"><ul class="pagination">';
foreach ( $pages as $page ) {
$pagination .= '<li class="page-item' . (strpos($page, 'current') !== false ? ' active' : '') . '"> ' . str_replace('page-numbers', 'page-link', $page) . '</li>';
}
$pagination .= '</ul></div>';
if ( $echo ) {
echo $pagination;
} else {
return $pagination;
}
}
return null;
}
/**
* Notes:
* AJAX:
* - When used with wp_ajax (generate pagination HTML from ajax) you'll need to provide base URL (or it'll be admin-ajax URL)
* - Example for a term page: bootstrap_pagination( $query, false, ['base' => get_term_link($term) . '?paged=%#%'] )
*
* Images as next/prev:
* - You can use image as next/prev buttons
* - Example: 'prev_text' => '<img src="' . get_stylesheet_directory_uri() . '/assets/images/prev-arrow.svg">',
*
* Add query parameters to page URLs
* - If you need custom URL parameters on your page URLS, use the "add_args" attribute
* - Example (before paginate_links() call):
* $arg = [];
* if (isset($_GET[ 'sort' ])) {
* $args[ 'sort' ] = (string)$_GET[ 'sort' ];
* }
* ...
* 'add_args' => $args,
*/
@mtx-z
Copy link
Author

mtx-z commented May 20, 2020

Updated with :

  • capability to override paginate_links() parameters
  • Notes for ajax usage (generate pagination HTML from wp_ajax call)
  • Notes on how to add query (GET) parameters to generated page URLs
  • Notes on how to use images as next/prev buttons

@madshostrup
Copy link

madshostrup commented May 29, 2020

Thank you @mtx-z !
Let me suggest to wrap it in a nav for accessibility
<nav aria-label="pagination"></nav>

@elioncho
Copy link

elioncho commented Jun 3, 2020

Thanks for this!

@nabeelkondotty
Copy link

The function name has a 'test' in registration.
In USAGE the function is called without 'test' and it causes error.

Thank You for the code, It helped

@mtx-z
Copy link
Author

mtx-z commented Jun 9, 2020

@nabeelkondotty thanks. A mistake from the latest update corrected thanks to you.

@demartini
Copy link

Hey @mtx-z thanks for this amazing function!

I would like to know how to remove the link added to "page 1" when returning the navigation to the first page?

@mtx-z
Copy link
Author

mtx-z commented Jun 14, 2020

@demartini, if I get you well, you want to remove the "page 1" link (not only href attribute) if user is on page 1?
Have you tried line 57 commented code $current_page = ( get_query_var( 'paged' ) == 0 ) ? 1 : get_query_var( 'paged' ); ? If the number is correct, then you can add something like this:

$current_page = (int)(( get_query_var( 'paged' ) == 0 ) ? 1 : get_query_var( 'paged' ));
...
foreach ( $pages as $page ) {
     if($current_page === 1 && (strpos($page, 'current') !== false)) {continue;}
     ....
}

Not tested (test it before using it in production), but it should prevent "page 1" <a> to be added to the pagination when the current page is 1.

@demartini
Copy link

@mtx-z thanks for the quick response, your suggestion worked well, but not as I expected.

For example, if I am on the homepage (https://example.com/blog), it hides the navigation from page 1, when going to page 2 it displays the page 1, and adds the permanent link https://example.com/blog/page/1/, what I would like was that when on page 2 or others the permanent link on page 1 was https://example.com/blog.

I don't know if you managed to understand what I want, anyway I managed to solve my problem using the understrap pagination example, commenting the lines 40 and 41 of your example:

            ...
            // 'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
            // 'format'       => '?paged=%#%',
            ...

Now it worked perfectly as I wanted.

Thanks again for your attention.

@Yvan-2032
Copy link

Thank you men, greatings from Peru

@tinkutharasing
Copy link

Thanks man. Was a great help

@lordmodkore
Copy link

How can we display NExt and Previous button always?

@OhmDios
Copy link

OhmDios commented Sep 30, 2020

Hello, Thanks for nice code. It saves lot of time.
How to make it this one work for ajax pagination.

@mtx-z
Copy link
Author

mtx-z commented Oct 12, 2020

@OhmDios I added some comments about how to use it with Ajax at the end. If you already know how to properly handle WordPress ajax, and the JS side, following what I wrote to fix the page URL generation should be ok. I'm using it with ajax without any issues.

@mtx-z
Copy link
Author

mtx-z commented Oct 12, 2020

@lordmodkore yes, you can easily edit the output to add a link for the first page before the loop, and the last page after the loop. $wp_query->max_num_pages allows you to know the last page. So you can then generate first-page link, and last page link, then add the required HTML around the foreach.

@DaneJC
Copy link

DaneJC commented Nov 9, 2020

NICE!!! Great job.. thanks mate!

@asus323
Copy link

asus323 commented Jan 26, 2021

How do we set this in our .php pages?

@mtx-z
Copy link
Author

mtx-z commented Jan 26, 2021

@asus323

  • copy the entire bootstrap_pagination() method into your active theme function.php, or related
  • then, from your template, you can call this method, passing or not a custom wp_query as parameter

@asus323
Copy link

asus323 commented Jan 27, 2021 via email

@thomi137
Copy link

thomi137 commented May 1, 2021

Thanks a lot for this! Just minor adaptations needed for Bootstrap 5 (no div outside, just a nav) and using kses to output just because I am paranoid, but this saved me a ton of time!

@mtx-z
Copy link
Author

mtx-z commented May 1, 2021

Hi @thomi137, thanks for the input. I created another gist for Bootstrap 5 support.
kses (wp_kses) are cool! But I admit rarely using them.

In this case, the only user input we rely on is max( 1, get_query_var( 'paged' ) ). As per PHP documentation examples about max(), doing something like this: echo max(0, 'hello'); will return 0. So I don't think it can be exploited. Changing page number will only result in changing the pagination SQL query, but no the rest of your query (and potential restriction). Anyway, it's cool to make it safer :) If you have any time, please post an example here or on the Bootstrap 5 Gist for any next developer looking for it.

@diogui
Copy link

diogui commented May 18, 2021

Great work. Thanks !

@Mark-in-Motion
Copy link

I'm using this on my search.php results page and the paginated links it's giving me the url like this:

http://example.com/?s=test&lang=en#038;lang=en&paged=2

can anyone help?

@mtx-z
Copy link
Author

mtx-z commented May 21, 2021

@mmoser-markl I need more details to try to help you:

  • are you implementing a post text search?
  • are you handling yourself the wp_query for this search?
  • is the form on a page, and then should redirect to a specific result page? Or search.php contains the form, and the form will post and redirect to search.php again?

@OsitaNathan
Copy link

Great job! Thanks!

@hussamedinetarig
Copy link

Great Job, Deeply Thanks

@wagjim
Copy link

wagjim commented Aug 14, 2021

Excellent, thanks

@nurrehmet
Copy link

Thanks, man! randomly found on google search and save my headache

@cengizilhan
Copy link

amazing!

@Jonnas123
Copy link

Hi,not working for me. It update the page url (page/2) but I'm still on the first page.

@mtx-z
Copy link
Author

mtx-z commented Dec 15, 2022

Hi @Jonnas123, does it work when you are using the classic WP pagination?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment