I am calling in my WordPress comments from the database and displaying them using a custom query, then using WordPress’ paginate_links()
function to paginate my comments. My code:
<div class="commentsWrap">
<div id="comments" class="commentBoxesWrap">
<?php
global $wpdb;
$querystr = " SELECT comment_content, commentmeta1.meta_value
AS comment_name, commentmeta2.meta_value
AS comment_country
FROM $wpdb->comments, $wpdb->commentmeta
AS commentmeta1, $wpdb->commentmeta
AS commentmeta2
WHERE $wpdb->comments.comment_ID = commentmeta1.comment_id
AND $wpdb->comments.comment_ID = commentmeta2.comment_id
AND commentmeta1.meta_key = 'comment_name'
AND commentmeta2.meta_key = 'comment_country'
AND $wpdb->comments.comment_approved = 1 ";
$total_query = "SELECT COUNT(1) FROM (${querystr}) AS combined_table";
$total = $wpdb->get_var( $total_query );
$items_per_page = 4;
$page = isset( $_GET['paged'] ) ? abs( (int) $_GET['paged'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$comment_info = $wpdb->get_results($querystr . "ORDER BY $wpdb->comments.comment_date DESC LIMIT ${offset}, $items_per_page");
echo '<ul class="commentsList">';
// display the results
foreach($comment_info as $info) {
echo '<li class="commentBox"><p>"' . $info->comment_content . '"</p><h6>' . $info->comment_name . ', ' . $info->comment_country . '</h6></li>';
}
echo '</ul>';
?>
</div> <!-- //commentBoxesWrap -->
<?php
echo '<div class="commentPagination">';
echo paginate_links( array(
'base' => add_query_arg( 'paged', '%#%' ),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'total' => ceil($total / $items_per_page),
'current' => $page
));
echo '</div>';
?>
</div> <!-- //commentsWrap -->
This works fine and outputs a numbered pagination, however, I need to ajax the comments when I click the pagination. With a bit of research I managed to come up with this js code:
$('.commentsWrap').on('click', '.commentPagination a', function(event) {
event.preventDefault();
var link = $(this).attr('href');
$('.commentsWrap').load(link + '.commentsWrap');
});
What this does though is load the entire page by ajax rather than the comments section! Can anybody help me please??
Thanks.
Try this for the pagination of comments. I have used jquery for this. You will need to change the url of ajax page url and loader image source. Try to add this below you code. This code will only work if your pagination is right and working.
You are missing a space before selector. This must be: