AJAX Load More For WordPress posts

Solution:

You need to add an input field for saving the offset, once user click on button, here is the code. NOTE: you should modify it according to you needs.

Add this in the end of loop where you get the data

<div class="col-md-12 col-sm-12 col-xs-12">
    <input type="hidden" id="offset" value="10">
    <a class="btn btn-primary text-white load_more" id="load_using_ajax">Load More</a>
    <p id="test2"></p>
</div>

add this code in js, modify according to your needs



$(document).on('click','#load_using_ajax',function(e){
    e.preventDefault();
    var button = $(this);
    var category = $('.active').data('category');
    var offset = parseInt($("#offset").val());

    $.ajax({
        url: wpAjax.ajaxUrl,
        type: 'post',
        data: {
            category: category,
            offset:offset,
            action: 'load_more_posts',
        },
        error : function(result){
            console.log(result);
        },
        success : function(result){
        if(result){
            $("#offset").val(offset+10);
            $('.append-ajax-release').append(result);
           
        }else{
            $("test2").append = 'No more Data Found';
        }
        }
        
    }); 
});


add this in you theme functions file need to modify according to your needs


add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');
add_action('wp_ajax_load_more_posts', 'load_more_posts');

function load_more_posts()
{
    $offset = $_POST['offset'];
    $category = $_POST["category"];
    $args = array(
        'order' => 'DESC',
        'post_status' => 'publish',
        'post_type' => 'post',
        'posts_per_page' =>  10,
        'offset' => $offset,
    );

    $query = new WP_Query();
    $query->query($args);
    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post(); ?>

        <div class="row col-12 pressreleases-wrapper mt-5 mb-3 ml-0 ">
            <?php the_title(); ?>
        </div>
        <?php
        endwhile;
    endif;
    wp_reset_postdata();

}