我正在使用自定义$wpdb
查询来获取我的数据库中的所有评论。
<?php
$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 O
RDER BY $wpdb->comments.comment_date DESC";
$comment_info = $wpdb->get_results($querystr, OBJECT);
echo '<ul>';
// 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>';
?>
这很好用,并且可以完全按照我的需要显示数据,但是,我还需要在注释中添加分页。我目前使用的代码:
<?php
$total = $wpdb->get_var(" SELECT COUNT(comment_ID)
FROM $wpdb->comments WHERE comment_approved = 1 ");
$comments_per_page = 4;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'total' => ceil($total / $comments_per_page),
'current' => $page
));
?>
虽然分页链接确实显示,但$comments_per_page
变量集无效,因为所有注释仍显示在一个页面上。我在自定义页面模板上运行此代码。
我哪里错了?
答案 0 :(得分:0)
因此,通过一些研究和大量的反复试验,我设法对其进行了排序。通过一些代码重新洗牌,我还必须设置一个偏移量变量并将其传递给我的LIMIT
数据库查询。最终工作代码如下。希望这也可以帮助其他人。
<?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>';
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>';
?>