Step 1: Create a template file and paste below code into file.
<div id="ajax-posts" class="row">
<?php $args = array( 'post_type' => 'post',
'posts_per_page' => 1,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
</div>
<?php endwhile; wp_reset_postdata(); ?>
</div>
<input type="hidden" id="totalpages" value="<?= $loop->max_num_pages ?>">
<div id="more_posts">Load More</div>
Step 2: Localize your script and paste below code into functons.php
/*
* Localize Script
* Put this script into functions.php file
*/
function js_enqueue_scripts() {
wp_register_script("my-ajax-handle", get_stylesheet_directory_uri() . "/assets/js/ajax.js", array('jquery'));
wp_enqueue_script("my-ajax-handle");
//the_ajax_script will use to print admin-ajax url in custom ajax.js
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action("wp_enqueue_scripts", "js_enqueue_scripts");
Step 3: Load More function for load posts
/*
* Load More Post Function
* Put this script into functions.php file
*/
function more_post_ajax() {
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();
$out .= '
<div class="small-12 large-4 columns"><h1>' . get_the_title() . '</h1>' . get_the_content() . '</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Step 4: Call your ajax js into ajax.js file
//ADD THIS INTO AJAX.JS FILE
var ppp = 1; // Post per page
var pageNumber = 2;
var total = jQuery('#totalpages').val();
jQuery("#more_posts").on("click", function ($) { // When btn is pressed.
jQuery("#more_posts").attr("disabled", true); // Disable the button, temp.
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: the_ajax_script.ajaxurl,
data: str,
success: function (data) {
var $data = jQuery(data);
if ($data.length) {
jQuery("#ajax-posts").append($data);
jQuery("#more_posts").attr("disabled", false);
} else {
jQuery("#more_posts").attr("disabled", true);
}
alert(total);
if (total < pageNumber) {
jQuery("#more_posts").hide();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
});