I'm trying to display all of the posts from the current month with a 'Previous month' button. Clicking the 'Previous month' button will change the displayed posts to those from the previous month without refreshing the page (i.e. if the page is currently showing September's posts, clicking the button will replace them with August's).
I've been trying to use AJAX to achieve this but i've not been able to get it to work thus far.
posts.php
<div class="post-body">
<?php
$year = date('Y', current_time('timestamp'));
$month = date('m', current_time('timestamp'));
get_posts($month, $year);?>
</div>
ajax-pagination.js
(function($) {
$(document.body).on('click', '#previous', function(e) {
e.preventDefault();
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination'
},
success:function( result) {
alert( result);
}
})
});
})(jQuery);
functions.php
function get_posts($month,$year) {
query_posts("year=$year&monthnum=$month");
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F');
echo "<h1>"$monthName" ",$year,"</h1>\n\n";
if(have_posts()) : while(have_posts()) : the_post();
?>
<div class="post-excerpt">
<p class="date"><?php echo get_the_date(); ?></p>
<div class="title"><h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></div>
<div class="excerpt"><?php the_excerpt(__('(more…)')); ?></div>
</div>
<?php endwhile; else : ?>
<div class="title"><h3><?php esc_html_e( 'There are no posts.' ); ?></h3></div>
<?php endif; wp_reset_query();}
function my_ajax_pagination() {
die();
}
Effectively, I want the $month and $year variables to reduce by 1 each time the button is clicked and for the new variables to be passed to the get_posts function. Is it possible to have Javascript and PHP to communicate in this way or should I try a different approach?