Load more on page scroll (with button and no plugin)

enter image description here

I have a custom taxonomy in WordPress called Case studies.

Home.php is a page. Within home.php I have ran a loop to get all the case studies:

<?php
// only display 5 posts at first, then load 5 more on button click
$args = array('post_type' => 'case-studies', 'posts_per_page' => 5 );
$the_query = new WP_Query($args);

if ( $the_query->have_posts() ) { 
    echo "<div id='customers' class='case-studies-container'>"; // If there are results, create a single div in which all case studies will sit.
    // run a loop to get data from all the posts that exist
    while ($the_query->have_posts() ) { 
        $the_query->the_post();
        tp_get_part( 'templates/snippets/case-study-card',
        array(
            'heading'           => get_the_title(),                         
            'subheading'        => get_field( 'case_study_subheading'), 

        )
    );
    }
    echo "<div><input type='button' id='loadmore' value='Load more'/></div>
    </div>" // case-studies-container closed;
    wp_reset_postdata();
} else {
    // no posts found
}
?>

On #loadmore button click, I want it to load 5 more posts from the DB and display them. To accomodate this, I have the following JS within *home.php*

<script type="text/javascript">
    $(document).ready(function(){
        $('#loadmore').click(function(){
            // alert('Hello world');
            // load more case studies here
                jQuery(function($){

                    var column_width = $(this).data('column-width'); 
                    var max_num_pages = $(this).data('max-num-pages');
                    var ignore = $(this).data('featured');
                    var post_type = $(this).data('type');

                    var button = $(this), 
                      data = {
                        action:'loadmore',
                        query: loadmore_params.posts, // that's how we get params from wp_localize_script() function
                        page : loadmore_params.current_page,
                        security : loadmore_params.security,
                        columns : column_width,
                        exclude : ignore,
                        max_num_pages : max_num_pages,
                        post_type : post_type
                        };

                    $.ajax({
                        url : loadmore_params.ajaxurl, // AJAX handler
                        data : data,
                        type : 'POST',
                        beforeSend : function ( xhr ) {
                            button.text('Loading...'); // change the button text, you can also add a preloader image
                        },
                        success : function( data ){
                            if( data ) {
                                button.text( 'Load More' ).prev().before(data); // insert new posts
                                loadmore_params.current_page++;

                                $('.case-studies-container').find('.case-card').last().after( data ); // where to insert posts

                                if ( loadmore_params.current_page == max_num_pages )
                                    button.remove(); // if last page, remove the button

                                // you can also fire the "post-load" event here if you use a plugin that requires it
                                // $( document.body ).trigger( 'post-load' );
                            } else {
                                button.remove(); // if no data, remove the button as well
                            }
                        },
                        error : function(error){ console.log(error) }
                    });

                });

        });
    });
</script>

And the following AJAX written in ajax-loaders.php:

<?php
function ajax_handler(){

  check_ajax_referer('load_more', 'security');
    // prepare our arguments for the query
    $args = json_decode( stripslashes( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
    $args['post_status'] = 'publish';
  $args['post__not_in'] = explode(',',$_POST['exclude']);
  $args['max_num_pages'] = $_POST['max_num_pages'];
  $cols = $_POST['columns'];
  $type = $_POST['post_type'];

    query_posts($args );
    if( have_posts() ) :
        // run the loop
        while( have_posts() ): the_post(); ?>

        <div class="<?php echo ($cols ? 'col-'.$cols : 'col-3') .' '. ($type === 'case-study' ? 'case-studies' : 'article__item'); ?>  grid__item" id="<?php echo get_the_id(); ?>">
            <?php
            tp_get_part( 'templates/snippets/case-study-card',
              array(
                'filterable' => true,
                'post'       => $post,
                'type'       => get_cpt_term(get_the_id(), 'case-studies')
              )
            );
            ?>
        </div>

        <?php
    endwhile;
    endif;
    die;
}
add_action('wp_ajax_loadmore', 'ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'ajax_handler'); // wp_ajax_nopriv_{action}
?>

With all these files set up, on button click, nothing happens? If I uncomment out the alert, the alert occurs which means the trigger is occurring, but unsure on where my load more functionality is going wrong?

Read more here:: Load more on page scroll (with button and no plugin)

Leave a Reply

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