WordPress Ajax Numbered Pagination in 5 minutes

As we know that in the current era, everyone is looking for the websites with minimum number of refresh. One of the solution for that is “Ajax”. We consider that you already have basic knowledge of how to use Ajax in wordPress. So lets start with “wordPress Ajax Numbered Pagination in 5 minutes”

Step 1: Creating Ajax function for WordPress Ajax Numbered Pagination

First of all, we have to create an Ajax function which we will call to load the content without refreshing the page. Use the following code and put it in your theme’s functions.php file.

<?php
/* ########################################## */
/* ###### Ajax function for pagination ###### */
/* ########################################## */
/* ########################################## */
add_action( 'wp_ajax_demo-pagination-load-posts', 'dcs_demo_pagination_load_posts' );
add_action( 'wp_ajax_nopriv_demo-pagination-load-posts', 'dcs_demo_pagination_load_posts' ); 
function dcs_demo_pagination_load_posts() {
    global $wpdb;
    // Set default variables
    $msg = '';
    if(isset($_POST['page'])){
        // Sanitize the received page   
        $page = sanitize_text_field($_POST['page']);
        $cur_page = $page;
        $page -= 1;
        $per_page = 2;//set the per page limit
        $previous_btn = true;
        $next_btn = true;
        $first_btn = true;
        $last_btn = true;
        $start = $page * $per_page;
        $all_blog_posts = new WP_Query(
            array(
                'post_type'         => 'post',
                'post_status '      => 'publish',
                'orderby'           => 'post_date',
                'order'             => 'DESC',
                'posts_per_page'    => $per_page,
                'offset'            => $start
            )
        );

        $count = new WP_Query(
            array(
                'post_type'         => 'post',
                'post_status '      => 'publish',
                'posts_per_page'    => -1
            )
        );
        $count = $count->post_count;
        if ( $all_blog_posts->have_posts() ) {
            while ( $all_blog_posts->have_posts() ) {
                $all_blog_posts->the_post(); ?>
                <div class = "col-md-12">       
                    <h2><a href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a></h2>
                    <p><?php the_excerpt(); ?></p>
                </div>
                <?php
            }
        }
        // This is where the magic happens
        $no_of_paginations = ceil($count / $per_page);
        if ($cur_page >= 7) {
            $start_loop = $cur_page - 3;
            if ($no_of_paginations > $cur_page + 3)
                $end_loop = $cur_page + 3;
            else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
                $start_loop = $no_of_paginations - 6;
                $end_loop = $no_of_paginations;
            } else {
                $end_loop = $no_of_paginations;
            }
        } else {
            $start_loop = 1;
            if ($no_of_paginations > 7)
                $end_loop = 7;
            else
                $end_loop = $no_of_paginations;
        }
        // Pagination Buttons logic     
        ?>
        <div class='dcs-universal-pagination'>
            <ul>
                <?php
                if ($first_btn && $cur_page > 1) { ?>
                    <li p='1' class='active'><<</li>
                    <?php
                } else if ($first_btn) { ?>
                    <li p='1' class='inactive'><<</li>
                    <?php
                }
                if ($previous_btn && $cur_page > 1) {
                    $pre = $cur_page - 1; ?>
                    <li p='<?php echo $pre; ?>' class='active'><</li>
                    <?php
                } else if ($previous_btn) { ?>
                    <li class='inactive'><</li>
                    <?php
                }
                for ($i = $start_loop; $i <= $end_loop; $i++) {
                    if ($cur_page == $i){ ?>
                        <li p='<?php echo $i; ?>' class = 'selected' ><?php echo $i; ?></li>
                        <?php
                    }else{ ?>
                        <li p='<?php echo $i; ?>' class='active'><?php echo $i; ?></li>
                        <?php
                    }
                }
                if ($next_btn && $cur_page < $no_of_paginations) {
                    $nex = $cur_page + 1; ?>
                    <li p='<?php echo $nex; ?>' class='active'>></li>
                    <?php
                } else if ($next_btn) { ?>
                    <li class='inactive'>></li>
                    <?php 
                }

                if ($last_btn && $cur_page < $no_of_paginations) { ?>
                    <li p='<?php echo $no_of_paginations; ?>' class='active'>>></li>
                    <?php 
                } else if ($last_btn) { ?>
                    <li p='<?php echo $no_of_paginations; ?>' class='inactive'>>></li>
                    <?php 
                } ?>
            </ul>
        </div>
        <?php
    }
    exit();
}

4 minutes left…

Step 2: Making structure to append data

Now we need to make the layout where we will actually append the response from our ajax function. You can do this in two ways:
1) Using shortcode.
2) By making the template.

In this tutorial, we are using the first way i.e Using shortcode because using this way, you can reuse the same shortcode again on a different page for another Ajaxified pagination. Paste the following code again into your theme’s functions.php file.

<?php
/* ########################################## */
/* ########################################## */
/* ###### Shortcode  for pagination ######### */
/* ########################################## */
/* ########################################## */
add_shortcode('dcs_postsWithAjaxPagination','dcs_postsWithAjaxPagination');
function dcs_postsWithAjaxPagination(){
?>
<div class="col-md-12 content">
    <div class = "inner-box content no-right-margin darkviolet">
    <div class = "dcs_pag_loading">
            <div class = "dcs_universal_container">
                <div class="dcs-universal-content"></div>
            </div>
        </div>
    </div>      
</div>
<?php
}

2 minutes left…

Step 3: Make a script to load the content using ajax – On Page load

Now we have to make a script to load the content using ajax. For that, simply paste the following code into your theme’s footer.php file or you can make a custom script file and enqueue that script into your theme.

<script type="text/javascript">
jQuery(document).ready(function($) {
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    function dcs_load_all_posts(page){
        $(".dcs_pag_loading").fadeIn().css('background','#ccc');
        var data = {
            page: page,
            action: "demo-pagination-load-posts"
        };
        $.post(ajaxurl, data, function(response) {
            $(".dcs_universal_container").html('').append(response);
            $(".dcs_pag_loading").css({'background':'none', 'transition':'all 1s ease-out'});
        });
    }
    dcs_load_all_posts(1);
    $('.dcs_universal_container .dcs-universal-pagination li.active').live('click',function(){
        var page = $(this).attr('p');
        dcs_load_all_posts(page);
    });
}); 
</script>

1 minute left…

Step 4: Styling the pagination

This is an optional step if you are a developer and want the designer to do the rest of the work on pagination to make it more attractive. If not just use the basic design for pagination and put the following code into your theme’s style.css file.

.dcs_pag_loading {padding: 20px;}
.dcs-universal-pagination ul {margin: 0; padding: 0;}
.dcs-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
.dcs-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
.dcs-universal-pagination ul li.inactive {background: #7E7E7E;}
.dcs-universal-pagination ul li.selected {background-color: #ee6e73; color: white;}

Time up and you are ready with the WordPress Ajax Numbered Pagination in 5 minutes.

If you have any queries, you can ask a question in our Questionsbank section by clicking here.