今天一口气将评论列表进行了大改,分别有无限嵌套、回复添加@评论者、跨页显示@评论对象的评论内容。
前两者挺简单的,本篇主要介绍后者。这个功能在多说上很常见,若要在WP评论系统上实现还需要一定的js基础和wp函数基础。

代码出处:
mg12
原理就不赘述了,具体看mg12大神那里的介绍吧。其中有一个js方法我放上去执行不下去,所以下面的代码是经过自己修改的。
步骤一
首先在functions.php添加一个自定义函数,用于跨页ajax请求时的对象链接参数。
// 悬停@评论者时调用对应评论
add_action('init', 'load_at_comment');
function load_at_comment(){
if($_GET['action'] =='load_at_comment' && $_GET['id'] != ''){
$comment = get_comment($_GET['id']);
if(!$comment) {
fail(printf('Whoops! Can\'t find the comment with id %1$s', $_GET['id']));
}
inlojv_get_comment_list($comment, null,null);
die();
}
}
里面的inlojv_get_comment_list是我自己的评论模板comments.php里的callback函数,改成你自己的。
步骤二
使用JS控制鼠标悬停@的a标签时的一系列动作,基本原理是:以这个a标签的href值作为锚点,连接相应的评论id,显示到你所需要的位置上,若是在本页则直接用html()方法获取该评论id的内容再插入,若是不在本页则用ajax方法请求获取再插入。下面是本站使用的代码,看注释自行修改。
// 悬停@评论者加载对应评论内容
function atreply(){
var id=/^#comment-/;
var at=/^@/;
$('#comment_list li p a').each(function() { // @的a标签
if($(this).attr('href').match(id) && $(this).text().match(at)) { // 检索匹配a标签href指定的值
$(this).addClass('atreply'); // 条件满足则增加atreply类
}
});
$('.atreply').hover(function() {
var target = this;
var _commentId = $(this).attr('href'); // 抓取锚点#comment-xxxx
if($(_commentId).is('.comment')) { // 若锚点id 与comment类 在同一个标签
// #thecomments 是评论列表ul或ol的id选择器
$('<li class="comment at_tip"></li>').hide().html('<div class="arrow"></div><div class="innerbox">' + $(_commentId).html() + '</div>').appendTo($('#thecomments')); // 插入位置
$('.at_tip .children').remove(); // 移除嵌套评论(如果有的话)
$('#thecomments .at_tip').css({ // 相对悬停.atreply的偏移,用target,不要用this
left:$(target).offset().left + $(target).width() + 10, // 左偏移为.atreply的宽度+10px
top:$(target).offset().top - 22 // 上平移.atreply的-22px
}).show(); // 并显示出来
} else {
var id = _commentId.slice(9); // 返回锚点数组第10个元素后的所有元素,也就是#comment-之后的数值
$.ajax({ // 跨页显示,采用ajax方法 获取锚点标签内的html替换tip内的内容
type: 'GET',
url: '?action=load_at_comment&id=' + id, // 加入functions.php的自定义函数 load_at_comment
cache: false,
dataType: 'html',
contentType: 'application/json; charset=utf-8', // 定义编码格式
beforeSend: function(){
$('<li class="comment at_tip"></li>').hide().html('<div class="arrow"></div><div class="innerbox"><p class="at_tip_loading msg">Loading...</p></div>').appendTo($('#thecomments')); // 插入位置
$('#thecomments .at_tip').css({ // 改变css相对偏移,同上
left:$(target).offset().left + $(target).width() + 10,
top:$(target).offset().top - 22}
).show();
},
success: function(data){
var addedComment = $(data + '</li>');
addedComment.hide().appendTo($('#thecomments')); // 载入请求到的数据并隐藏,二次加载就跳转到上面的判断显示,不需要再次请求。
$('#thecomments .at_tip .innerbox').html(addedComment.html()); // 替换加载动画为请求内容
},
error: function(){ // 错误提示
$('#thecomments .at_tip').html('<p class="msg">暂时无法载入回复对象评论,请稍后再试。</p>');
}
});
}
}, function() { // 鼠标移开则淡出
$('#thecomments .at_tip').fadeOut(10, function(){
$(this).remove();
});
});
}
最后是CSS一下。效果请看本文下方评论首页的测试评论,Cheers!
本站文章除注明转载/出处外,均为本站原创或翻译。若要转载但请务必注明出处,尊重他人劳动成果。
转载请注明出处链接 : https://www.inlojv.com/4568.html
