获取评论者的IP归属地及运营商信息。本文还会用到百度opendata的ip查询api。


//后台显示评论者IP归属地

add_action('admin_comment_types_dropdown','comment_ip_lookup');
function comment_ip_lookup($a){
//if()
?>
<script>
jQuery(document).ready(function() {
ipList = new Array();
locList = {};
authcol = jQuery("[data-colname='作者']");
authcol.each(function() {
ipWrapper = jQuery(this).children("a").last();
ip = ipWrapper.html();
ipList.push(ip);
ipWrapper.after('</br><span addr="' + ip + '" style="display:none;"></span>');
});
ipList = uniqueArr(ipList);
i = 0;
intv = setInterval(function() {
if (i == ipList.length - 1) window.clearInterval(intv);
jQuery.getScript("http://opendata.baidu.com/api.php?query=" + ipList[i] + "&co=&resource_id=6006&ie=utf8&oe=gbk&cb=displayLoc&format=json");
i++;
},
150);
});
function uniqueArr(array) {
var r = [];
for (var i = 0,
l = array.length; i < l; i++) {
for (var j = i + 1; j < l; j++) if (array[i] === array[j]) j = ++i;
r.push(array[i]);
}
return r;
}
function displayLoc(result) {
var location = result['data'][0]['location'];
var ip = result['data'][0]['OriginQuery'];
jQuery("[addr='" + ip + "']").html(location).fadeIn("slow");
}
</script>
<?php
} 

admin_comment_types_dropdown钩子在打开评论管理页面(edit-comments.php)时触发,通过jquery遍历本页面所有评论者ip地址,在ip地址后加一个span用来显示归属地信息。将所有ip地址放入ipList数组并去重后通过api逐一查询归属地。通过jsonp的回调函数显示归属地信息。

这里查询ipList归属地的时候没有直接使用ipList.each而是使用了setInterval,为了避免同时进行过多查询被api限制(taobao的api显示每秒10个,百度的未知)。