I am trying to get an AJAX WP Query loop to output 2 posts then use a ‘Load more’ button to load the next page of results. What is the best method to approach as not currently working?
JS
var ajaxRequest=function(){
var filter = $('#filter');
var page = 1; // What page we are on.
var ppp = 3; // Post per page
$.ajax({
url: filter.attr('action'),
data: filter.serialize(),
type: 'POST',
dataType: 'json',
offset: (page * ppp) + 1,
ppp: ppp,
success: function(response) {
page++;
$(".card-wrap").append(response); //Post class
$("#more_posts").attr("disabled",false);
}
});
};
PHP
<?php
header("Content-type: application/json"); //Outputting as JSON for map data.
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
$args = array(
'order' => $_POST['date'],
'post_type' => 'custom',
'posts_per_page' => 2,
'offset' => $offset,
);
[Rest of query]
?>
HTML
<a id="more_posts" href="#">Load More</a>
if you want to use ajax in wordpress you must have to follow these step:
1) first make your js file like main.js.
2) localize it in functions.php with wp_localize_script()
.
wp_enqueue_script( 'main.js', get_template_directory_uri().'/js/main.js', array( 'jquery' ) );
wp_localize_script( 'main.js', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
3) make your javascript or jquery code to run your query with ajax and in ajax data object add a action property like action: ‘load_more_posts’.
This action property will make function with same name to excute our code.
jQuery(function($){
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
$('#load_more_posts').data('offset', parseInt(response.data.offset));
}
});
})
});
4) In functions.php
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'post', 'posts_per_page'=> 2, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+2;
endif;
wp_send_json_success(array('post'=>$rst, 'offset'=>$offset));
}
wp_ajax_nopriv_(action) executes for users that are not logged in.
wp_ajax_(action) executes for users that are logged in.
you can use query response as you like.
Hope this will help!