I want to paginate my WordPress posts in a custom loop with Ajax, so when I click on load more button posts will appear.
My code:
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<p>
<?php the_content(); ?>
</p>
<?php
endwhile;
echo '<a href="#">Load More</a>';
wp_reset_postdata();
?>
This code does not paginate. Is there a better way to do this?
The
Load More
button needs to send aajax
request to the server and the returned data can be added to the existent content using jQuery or plain javascript. Assuming your using jQuery this would starter code.Custom Ajax Handler (Client-side)
Change to:
Javascript: – Put this at the bottom of the file.
Custom Ajax Handler (Server-side)
PHP – Put this in the functions.php file.