Ajaxly loadmore posts onClick button

1. Add a localize script variable in functions.php

wp_enqueue_script(‘script-loadmore’, get_template_directory_uri() . ‘/assets/js/loadmore.js’, array(‘jquery’) );

$page_slug = ‘default’;

if (get_queried_object()->post_name) {
$page_slug = get_queried_object()->post_name;
} else if (get_queried_object()->slug) {
$page_slug = get_queried_object()->taxonomy;
} else if (get_queried_object()->user_registered) {
$page_slug = ‘author’;
} else if ($_GET[‘s’]) {
$page_slug = ‘search’;
}

wp_localize_script( ‘script-loadmore’, ‘loadmore_params’, array(
‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),
‘posts’ => json_encode( $wp_query->query_vars ),
‘current_page’ => get_query_var( ‘paged’ ) ? get_query_var(‘paged’) : 1,
‘max_page’ => $wp_query->max_num_pages,
) );
wp_enqueue_script( ‘script-loadmore’ );

2. Add ajax function

First Method:

function loadmore_posts_ajax_handler(){

$args = json_decode( stripslashes( $_POST[‘query’] ), true );
$args[‘paged’] = $_POST[‘page’] + 1;
$args[‘post_status’] = ‘publish’;
$slug = $_POST[‘page_slug’];
$category = ”;

query_posts( $args );

if( have_posts() ) :
while( have_posts() ): the_post(); ?>
<div class=”col-lg-4 col-sm-6 margin-bottom-30″>
<?php
the_title();
?>
</div>
<?php endwhile;
endif;
die;
}

add_action(‘wp_ajax_loadmore’, ‘loadmore_posts_ajax_handler’);
add_action(‘wp_ajax_nopriv_loadmore’, ‘loadmore_posts_ajax_handler’);

Second Method:

function loadmore_posts_ajax_handler(){

$offset = $_POST[“page”];

$args = array(
‘post_type’ => ‘avada_portfolio’,
‘status’ => ‘publish’,
‘posts_per_page’ => 30,
‘orderby’ => ‘date’,
‘order’ => ‘DESC’,
‘offset’ => $offset * 30,
);

$post = new WP_Query($args);
while ($post->have_posts()) { $post->the_post();

single_product();

}

wp_reset_postdata();

die(); // use die instead of exit
}

add_action(‘wp_ajax_loadmore’, ‘loadmore_posts_ajax_handler’);
add_action(‘wp_ajax_nopriv_loadmore’, ‘loadmore_posts_ajax_handler’);

3. Ajax request in javacript for loadmore.js file when click on the loadmore button

jQuery(function($){
$(‘.loadmore-btn’).click(function(){
// console.log(“clicked”);

var button = $(this),
data = {
‘action’: ‘loadmore’,
‘query’: loadmore_params.posts,
‘page’ : loadmore_params.current_page,
// ‘page_slug’ : loadmore_params.page_slug,
};

$.ajax({
url : loadmore_params.ajaxurl,
data : data,
type : ‘POST’,
beforeSend : function ( xhr ) {
button.text(‘Loading…’);
},
success : function( data ){
if( data ) {

button.text(‘Load More’);

$(‘#loader_content’).append(data);
loadmore_params.current_page++;

if ( loadmore_params.current_page == loadmore_params.max_page )
button.remove();
} else {
button.remove();
}
}
});
});
});