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!