之前为了让WordPress评论者链接在新窗口中打开,在网上百度了一下方法,找到一个利用add_filter给get_comment_author_link添加过滤的方法。测试了一下可以使用就没有管它了。
代码如下:(有bug,请勿使用)
//Wordpress评论者的链接新窗口打开
function get_comment_author_link_new() {
global $comment;
$url = get_comment_author_url();
$author = get_comment_author();
if ( empty( $url ) || 'http://' == $url )
$return = $author;
else
$return = "$author";
return $return;
}
add_filter('get_comment_author_link', 'get_comment_author_link_new');
如果不细看,还真找不出问题在哪里。可是突然有天发现,WordPress头条的最新评论小工具中的评论人都是一个人。如下图:
大家可以看到很明显的所有评论人都有问题。下面来分析一下原因:
上面的代码中get_comment_author_url和get_comment_author两个函数都没有指定参数。这在文章页是没有问题的。可是放到最新评论小工具中就不行了。没有指定参数是不能找到指定评论的评论人链接和url的。于是我把代码修改了一下:(参考了comment-template.php中的代码)
//Wordpress评论者的链接新窗口打开
function get_comment_author_link_new($return, $author, $comment_ID = 0) {
$comment = get_comment( $comment_ID );
$url = get_comment_author_url( $comment );
$author = get_comment_author( $comment );
if ( empty( $url ) || 'http://' == $url )
$return = $author;
else
$return = "$author";
return $return;
}
add_filter('get_comment_author_link', 'get_comment_author_link_new');
心想这下应该没有问题了吧。可是怎么刷新还是不正确。$author和$comment_ID两个参数始终没值。这让我不得不重新查看一下add_filter函数的使用方法。
add_filter让我们可以给指定的函数添加一个过滤函数。
add_filter总共有4个参数。
第一个参数:指定要添加过滤器函数名字
第二个参数:我们自定义的过滤器函数名字
第三个参数:指定过滤器的优先级
第四个参数:指定过滤器接收的参数个数
问题找到了,就是我们没有指定add_filter指定过滤器接收的参数个数。不指定默认只接收一个参数。于是修改代码如下:
//Wordpress评论者的链接新窗口打开
function get_comment_author_link_new($return, $author, $comment_ID = 0) {
$comment = get_comment( $comment_ID );
$url = get_comment_author_url( $comment );
$author = get_comment_author( $comment );
if ( empty( $url ) || 'http://' == $url )
$return = $author;
else
$return = "$author";
return $return;
}
add_filter('get_comment_author_link', 'get_comment_author_link_new', 10 ,3);
测试一下,完美解决问题。温故而知新啊。
参考函数:
add_filter
apply_filters
remove_filter
这些函数都看看吧。
试试还行