Pagination Without Page Reload Using Ajax In WordPress

In this article, we are going to learn about how to create pagination without page reload by using ajax in WordPress.

what is pagination :
Pagination is a method of dividing web content into some pages, thus presenting content in a limited and digestible manner.

First, you have to add following code in your functions.php file to call ajax in your template

add_action( 'wp_ajax_demo_pagination_posts', 'demo_pagination_posts' );
add_action( 'wp_ajax_nopriv_demo_pagination_posts', 'demo_pagination_posts' ); 

function demo_pagination_posts() {
  global $wpdb;
  $msg = '';
  if(isset($_POST['page'])){
    $page = sanitize_text_field($_POST['page']);
    $cur_page = $page;
    $page -= 1;
    $per_page = 2;
    $previous_btn = true;
    $next_btn = true;
    $start = $page * $per_page;

    // Set the table where we will be querying data
    $table_name = $wpdb->prefix . "posts";

    // Query the posts
    $all_blog_posts = $wpdb->get_results($wpdb->prepare("
      SELECT * FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page ) );

    // At the same time, count the number of queried posts
      $count = $wpdb->get_var($wpdb->prepare("
      SELECT COUNT(ID) FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish'", array() ) );

    // Loop into all the posts
    foreach($all_blog_posts as $key => $post): 
      $msg .= '
      <div class = "col-md-12">       
        <h2>' . $post->post_title . '</a></h2>
        <p>' . $post->post_content . '</p>
      </div>';
    endforeach;
   
    $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     
    $pag_container .= "
    <div class='pagination-link'>
      <ul>";
        if ($previous_btn && $cur_page > 1) {
          $pre = $cur_page - 1;
          $pag_container .= "<li p='$pre' class='active'>Previous</li>";
        } else if ($previous_btn) {
          $pag_container .= "<li class='inactive'>Previous</li>";
        }
        for ($i = $start_loop; $i <= $end_loop; $i++) {
          if ($cur_page == $i)
            $pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
          else
            $pag_container .= "<li p='$i' class='active'>{$i}</li>";
        }
        if ($next_btn && $cur_page < $no_of_paginations) {
          $nex = $cur_page + 1;
          $pag_container .= "<li p='$nex' class='active'>Next</li>";
        } else if ($next_btn) {
          $pag_container .= "<li class='inactive'>Next</li>";
        }
        $pag_container = $pag_container . "
      </ul>
    </div>";
    echo 
    '<div class = "pagination-content">' . $msg . '</div>' . 
    '<div class = "pagination-nav">' . $pag_container . '</div>';
  }
  die();
}

Now add this following code where you want to display your post (like index.php, home.php), here I will add this code in one template file. Modafinil without prescription http://sellersvillepharmacy.com/modafinil.php

<?php 
/*
Template Name: pagination
*/
get_header(); ?>
<div class="wrap">
  <div id="primary" class="content-area">
    <div class="col-md-12 content">
      <div class = "inner-box content no-right-margin darkviolet">
        <script type="text/javascript">
          jQuery(document).ready(function($) {
            // This is required for AJAX to work on our page
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
            function load_all_posts(page){
              var data = {
                page: page,
                action: "demo_pagination_posts"
              };
              // Send the data
              $.post(ajaxurl, data, function(response) {
                $(".pagination_container").html(response);
              });
            }
            load_all_posts(1); // Load page 1 as the default
            $(document).on('click','.pagination-link ul li',function(){
              var page = $(this).attr('p');
              load_all_posts(page);
            });

          }); 
        </script>
        <div class = "pag_loading">
          <div class = "pagination_container">
            <div class="post-content"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php get_footer();

And at the last put this code into your style.css to style your pagination

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

Now, create one page and select a template “pagination” so you can be show results as below.

Hire WordPress developers in India with years of experience building WordPress websites, including the development of themes, Woocommerce, and plugins. Our specialized WordPress website developers in India give development services in two ways, using WordPress designs, custom themes, and state-of-the-art, elegantly arranged mark-ups. WP solutions can deliver the most well-written programs as well as pixel-perfect outputs.

5 Comments

  1. Eric

    How we can make these types of paginations by using plugins??

    0
    0
    Reply
  2. Jimmy

    Hey thanks for the article, it helped. However, I’m getting a PHP ajax error in the console saying “‘Undefined variable: pag_container’.” Everything shows up correctly but the pagination itself does not work. Not sure how to fix it, would appreciate any help!

    0
    0
    Reply
  3. alejandro ferguson

    thanks for this article!
    the front end looks exatly as on your screenshots but I get the same error as Gagan Bafna.
    Where should I add that code?
    $(‘#parentElement’).on(‘click’, ‘.myButton’, function)

    I put it this way but nothing is displayed
    load_all_posts(1); // Load page 1 as the default
    /*$(‘.pagination_container .pagination-link li.active’).live(‘click’,function(){ */
    $(‘#parentElement’).on(‘click’, ‘.myButton’, function) {
    var page = $(this).attr(‘p’);
    load_all_posts(page);
    });

    0
    0
    Reply
  4. Gagan Bafna

    Pagination is not working. Display error in the console
    Uncaught TypeError: $(…).live is not a function
    at HTMLDocument. ((index):800)
    at e (jquery.min.js?ver=3.5.1:2)

    1
    0
    Reply
    1. Hiral solanki

      you can use in place of live function
      $(‘#parentElement’).on(‘click’, ‘.myButton’, function)

      0
      0
      Reply

Submit a Comment

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

Subscribe

Select Categories