How to Add Bootstrap 5 Pagination in WordPress without Plugin

How to Add Bootstrap 5 Pagination in WordPress without Plugin

Looking for Bootstrap 5 Pagination for WordPress? You are in right place. In this article, I will show You How to Add Bootstrap 5 Pagination in WordPress without Plugin.

Bootstrap 5 is the most popular framework for building responsive, mobile-first sites, with jsDelivr and a template starter page. Most websites use bootstrap. We will try to build pagination using bootstrap 5.

Pagination lets you split your WordPress site’s content into multiple pages. That can be easy to understand for humans and search engines. There are many designs on the internet for pagination. But for popularity and responsive design, we select Bootstrap 5 Pagination.

Make WordPress Default Function To Bootstrap 5 Supported

We have huge resources in WordPress default If you have utilized it. It is enough for theme development. However, you need just a significant change in those functions. Look like the paginate_links() function, It can output a list, There is a problem with that function. We have many classes and other attributes. So, we are going to modify this function and place some bootstrap CSS classes in right place. Also, We give it a new name.

Copy this function and place it into the function.php

function wpk_paginate_links( $args = '' ) {
    global $wp_query, $wp_rewrite;

    // Setting up default values based on the current URL.
    $pagenum_link = html_entity_decode( get_pagenum_link() );
    $url_parts    = explode( '?', $pagenum_link );

    // Get max pages and current page out of the current query, if available.
    $total   = isset( $wp_query->max_num_pages ) ? $wp_query->max_num_pages : 1;
    $current = get_query_var( 'paged' ) ? (int) get_query_var( 'paged' ) : 1;

    // Append the format placeholder to the base URL.
    $pagenum_link = trailingslashit( $url_parts[0] ) . '%_%';

    // URL base depends on permalink settings.
    $format  = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
    $format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';

    $defaults = array(
        'base'               => $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below).
        'format'             => $format, // ?page=%#% : %#% is replaced by the page number.
        'total'              => $total,
        'current'            => $current,
        'aria_current'       => 'page',
        'show_all'           => false,
        'prev_next'          => true,
        'prev_text'          => __( '« Previous' ),
        'next_text'          => __( 'Next »' ),
        'end_size'           => 1,
        'mid_size'           => 2,
        'type'               => 'plain',
        'add_args'           => array(), // Array of query args to add.
        'add_fragment'       => '',
        'before_page_number' => '',
        'after_page_number'  => '',
    );

    $args = wp_parse_args( $args, $defaults );

    if ( ! is_array( $args['add_args'] ) ) {
        $args['add_args'] = array();
    }

    // Merge additional query vars found in the original URL into 'add_args' array.
    if ( isset( $url_parts[1] ) ) {
        // Find the format argument.
        $format       = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) );
        $format_query = isset( $format[1] ) ? $format[1] : '';
        wp_parse_str( $format_query, $format_args );

        // Find the query args of the requested URL.
        wp_parse_str( $url_parts[1], $url_query_args );

        // Remove the format argument from the array of query arguments, to avoid overwriting custom format.
        foreach ( $format_args as $format_arg => $format_arg_value ) {
            unset( $url_query_args[ $format_arg ] );
        }

        $args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) );
    }

    // Who knows what else people pass in $args.
    $total = (int) $args['total'];
    if ( $total < 2 ) {
        return;
    }
    $current  = (int) $args['current'];
    $end_size = (int) $args['end_size']; // Out of bounds? Make it the default.
    if ( $end_size < 1 ) {
        $end_size = 1;
    }
    $mid_size = (int) $args['mid_size'];
    if ( $mid_size < 0 ) {
        $mid_size = 2;
    }

    $add_args   = $args['add_args'];
    $r          = '';
    $page_links = array();
    $dots       = false;

    if ( $args['prev_next'] && $current && 1 < $current ) :
        $link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] );
        $link = str_replace( '%#%', $current - 1, $link );
        if ( $add_args ) {
            $link = add_query_arg( $add_args, $link );
        }
        $link .= $args['add_fragment'];

        $page_links[] = sprintf(
            '<a class="prev page-numbers page-link" href="%s">%s</a>',
            /**
             * Filters the paginated links for the given archive pages.
             *
             * @since 3.0.0
             *
             * @param string $link The paginated link URL.
             */
            esc_url( apply_filters( 'paginate_links', $link ) ),
            $args['prev_text']
        );
    endif;

    for ( $n = 1; $n <= $total; $n++ ) :
        if ( $n == $current ) :
            $page_links[] = sprintf(
                '<span aria-current="%s" class="page-numbers current">%s</span>',
                esc_attr( $args['aria_current'] ),
                $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']
            );

            $dots = true;
        else :
            if ( $args['show_all'] || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) :
                $link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] );
                $link = str_replace( '%#%', $n, $link );
                if ( $add_args ) {
                    $link = add_query_arg( $add_args, $link );
                }
                $link .= $args['add_fragment'];

                $page_links[] = sprintf(
                    '<a class="page-numbers page-link" href="%s">%s</a>',
                    /** This filter is documented in wp-includes/general-template.php */
                    esc_url( apply_filters( 'paginate_links', $link ) ),
                    $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']
                );

                $dots = true;
            elseif ( $dots && ! $args['show_all'] ) :
                $page_links[] = '<span class="page-numbers dots">' . __( '&hellip;' ) . '</span>';

                $dots = false;
            endif;
        endif;
    endfor;

    if ( $args['prev_next'] && $current && $current < $total ) :
        $link = str_replace( '%_%', $args['format'], $args['base'] );
        $link = str_replace( '%#%', $current + 1, $link );
        if ( $add_args ) {
            $link = add_query_arg( $add_args, $link );
        }
        $link .= $args['add_fragment'];

        $page_links[] = sprintf(
            '<a class="next page-numbers page-link" href="%s">%s</a>',
            /** This filter is documented in wp-includes/general-template.php */
            esc_url( apply_filters( 'paginate_links', $link ) ),
            $args['next_text']
        );
    endif;

    switch ( $args['type'] ) {
        case 'array':
            return $page_links;

        case 'list':
            $r .= "<ul class='pagination'>\n\t<li class='page-item'>";
            $r .= implode( "</li>\n\t<li class='page-item'>", $page_links );
            $r .= "</li>\n</ul>\n";
            break;

        default:
            $r = implode( "\n", $page_links );
            break;
    }

    /**
     * Filters the HTML output of paginated links for archives.
     *
     * @since 5.7.0
     *
     * @param string $r    HTML output.
     * @param array  $args An array of arguments. See paginate_links()
     *                     for information on accepted arguments.
     */
    $r = apply_filters( 'paginate_links_output', $r, $args );

    return $r;
}

Okay, Now let’s create pagination.

Create Bootstrap 5 Pagination

Although, WordPress’s default theme has good pagination. You can use it. First of all, you need to know about PHP basics. Because Coding is not under plagiarism restriction. If you can understand others’ programmer code you can copy it. But you can not do it without knowing anything.

If you can understand code or modify any code. You may make your own custom code. Also, You perform to modify the code that is provided by me. In case you cannot modify it. Just copy the code below and paste it into your function.php file. That’s the reason, I have followed the Bootstrap 5 structure.

Use this code in your function.php

function wpk_get_the_posts_pagination( $args = array() ) {

   global $wp_query;

   $total = $wp_query->max_num_pages;

   $html = '';

   // only bother with the rest if you have more than 1 page!
   if ( $total > 1 )  {
      // get the current page
      if ( !$current_page = get_query_var('paged'))
         $current_page = 1;
         // structure of "format" depends on whether we're using pretty permalinks
         $format = empty( get_option('permalink_structure') ) ? '&page=%#%' : 'page/%#%/';

         $pagination = wpk_paginate_links(array(
            'base'      => get_pagenum_link(1) . '%_%',
            'format'    => $format,
            'current'   => $current_page,
            'total'     => $total,
            'mid_size'  => 3,
            'type'   => 'list'
         )
      );
    
      $html .= '<nav aria-label="Page navigation">';
      $html .= $pagination;
      $html .= '</nav>';

      return $html;
   }
}

If you have copied and placed into your file those two functions above. It’s already ready to use your bootstrap 5 pagination.

Then just place this function into your index.php or whatever you need. Look like:

<?php echo wpk_get_the_posts_pagination(); ?>

I hope you will get satisfied answer.

Conclusion

Pagination is one of the most important parts of any WordPress theme developer. WordPress CMS is first made for blogs so when you want to develop the best quality WordPress theme. You need to maintain the theme unit test. That is blog based test and pagination part of it.

I hope you like this article. I think you already How to Add Bootstrap 5 Pagination in WordPress without Plugin.

See More:

How to get the next and previous post link in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *