Thursday 15 October 2015

How to create load more posts in wordpress using jQuery Ajax

Step 1: Put the following javascript in the section.
<script type="text/javascript">
jQuery(document).ready(function($) {
  var page = 1; // What page we are on.
  var ppp = 3; // Post per page
                var posts = 3;
                var author_posts = parseInt(<?php echo get_the_author_posts(); ?> ); // Get all posts
              $("#load_more_posts").click(function() {
               if ((author_posts - posts ) < 0) {
                    $("#load_more_posts").attr('disabled');
                    $("#load_more_posts").css({'cursor': 'default','opacity': '0.61'});
                    $("#load_more_posts").text('No more posts!');
                }else {
                    OffSet = (page * ppp);
                    $.ajax({
                    type: "GET",
                    url: "/WordPress/wp-admin/admin-ajax.php",
                    dataType: 'html',
                    data: ({ action: 'loadMore', offset:OffSet , ppp: ppp}),
                    success: function(data){    
                    //$('#load_posts').append( $.parseHTML(data));
                    var $items = $($.parseHTML(data));
                    $('#load_posts').append( $items ).isotope( 'appended', $items );
                    // #load_posts is the id of main posts container
                    posts = posts + 3;
                    page++;
                    if ((author_posts - posts ) < 0) {
                        $("#load_more_posts").attr('disabled');
                        $("#load_more_posts").css({'cursor': 'default','opacity': '0.61'});
                        $("#load_more_posts").text('No more posts!');
                        }
                    }
                });
            }
        });
    });
 </script>
Step 2: After that put the following code in function.php file.
<?php
 function loadMore() {
        $offset     = $_GET["offset"];
        $ppp         = $_GET["ppp"];
        $args2         = array( 'posts_per_page' => $ppp, 'offset' => $offset, 'orderby' => 'DESC');
        $custom2     = new WP_Query($args2);
        // the Loop
        while ($custom2->have_posts()) : $custom2->the_post();  ?>
        <div class="item">
        <div class="grid-text">   
        <?php the_content('Read More...');?>
        </div>
        </div>
        <?php
        endwhile;
        // Reset Query
        wp_reset_query();
      
}
add_action('wp_ajax_loadMore', 'loadMore');
add_action('wp_ajax_nopriv_loadMore', 'loadMore'); // not really needed
?>
Step 3: Finally put the following code line in index.php page after closing main div of posts container.
<div id="load_more_posts"> Load More</div>