文章评论过多会把文章页面拉伸得很长,影响整个页面的美观同时不利于用户体验,因此大部分wordpress博客选择对文章评论进行分页,尚未对文章过多的评论分页的博主可参考《WordPress非插件实现文章评论分页功能》实现分页效果。评论分页后,每次翻页会刷新整个文章页面,显然也是降低了用户体验的得分了,而通过Ajax技术的评论分页局部刷新的效果则显得更友好,为了博客的用户体验,跟着下面的步骤操作吧。
实现Ajax无刷新评论翻页效果:
加载jQuery库,在主题的header.php文件的
前面添加以下代码:进入“wordpress后台——设置——讨论”,在“其他评论设置”中勾选分页显示评论,并设置评论数目(注:回复评论不在数目计算范围内);
如果当前主题comments.php文件中已存在以下代码,则忽略此步,如果不存在,在其中需要添加分页的地方加入以下调用代码:
在当前主题的header.php文件中原有的 meta 标签下加入以下代码,禁止分页的页面被搜索引擎收录,防止内容重复,避免降权,有利于网站SEO优化:
if( function_exists('get_query_var') ) {
$cpage = intval(get_query_var('cpage'));
$commentPage = intval(get_query_var('comment-page'));
}
if( !empty($cpage) || !empty($commentPage) ) {
echo '';
echo "\n";
}
}
?>
在评论列表前加入一个元素,用于在显示新一页评论列表时表示列表正在加载。假设主题模板 comments.php 的评论模块结构如下:
在你的 js 文件中加入以下 js 代码实现评论分页:
// 评论分页
$body=(window.opera)?(document.compatMode=="CSS1Compat"?$('html'):$('body')):$('html,body');
// 点击分页导航链接时触发分页
$('#comments-navi a').live('click', function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: $(this).attr('href'),
beforeSend: function(){
$('#comments-navi').remove();
$('.comment_list').remove();
$('#loading-comments').slideDown();
$body.animate({scrollTop: $('#comments-list-title').offset().top - 65}, 800 );
},
dataType: "html",
success: function(out){
result = $(out).find('.comment_list');
nextlink = $(out).find('#comments-navi');
$('#loading-comments').slideUp('fast');
$('#loading-comments').after(result.fadeIn(500));
$('.comment_list').after(nextlink);
}
});
});
加载条的 css 样式效果(可根据自己的需要调整):
#loading-comments {display: none; width: 100%; height: 45px; background: #a0d536; text-align: center; color: #fff; font-size: 22px; line-height: 45px; }
更新:
jQuery.js在1.7以后少了live多了on,但不能直接把live改成on,否则只能加载一页,更改后的js代码如下:
// 评论分页
$body=(window.opera)?(document.compatMode=="CSS1Compat"?$('html'):$('body')):$('html,body');
// 点击分页导航链接时触发分页
$('body').on('click', '#comments-navi a', function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: $(this).attr('href'),
beforeSend: function(){
$('#comments-navi').remove();
$('.comment_list').remove();
$('#loading-comments').slideDown();
$body.animate({scrollTop: $('#comments-list-title').offset().top - 65}, 800 );
},
dataType: "html",
success: function(out){
result = $(out).find('.comment_list');
nextlink = $(out).find('#comments-navi');
$('#loading-comments').slideUp('fast');
$('#loading-comments').after(result.fadeIn(500));
$('.comment_list').after(nextlink);
}
});
});
代码转自:Kayo
Comments
1
...