之前在某位博友那里看到了显示评论用户twitter账号的功能,这个有点意思……然后就想自己折腾一个出来。其实用插件实现起来很简单,比如Custom Comment之类的,都可以。但是本着不折腾不舒服的原则,还是决定自己实践一把–手工添加上去为好,如此一来装逼的同时省下一个插件,并能输出一篇文章,何乐而不为呢。
1、总述
诸君如果想要手动实现此功能,大致可以分三步:在评论栏里添加输入框=>设置后台保存数据的方法=>前台回显保存的数据
此篇的方法,我主要参照了 此篇文章
2、主题情况
视主题不同,主要分了两种情况,A和B,请对号入座。
查看方式:请打开你的comments.php文件,之后ctrl+F,查找comment_form()这一句代码,如果找到并且不附带任何参数,A;找到并且有参数B;其他情况C。
**情况A:**此情况主题直接使用了commentform函数。普遍存在于版本较新的通用主题之中。
需要编辑的文件:functions.php。
//此内容加入functions.php里合适的地方 add_filter( 'comment_form_defaults', 'change_comment_form_defaults');
function change_comment_form_defaults($default) {
$commenter = wp\_get\_current\_commenter();
$default\['fields'\]\['url'\] .= '
' . ''. __('twitter') . '
';
return $default;
} add_action( 'comment_post','save_comment_meta_data' ); function save_comment_meta_data( $comment_id ) { add_comment_meta( $comment_id, 'twitter', $_POST['twitter'] ); }
//下面是回调函数,如果不想它直接跟在author_link(评论中,用户的链接)后面,那么用下面A1代替(主题需要有评论回调函数) add_filter( 'get_comment_author_link', 'attach_twitter_to_author' ); function attach_twitter_to_author( $author ) { $tw= get_comment_meta( get_comment_ID(), 'twitter', true ); if ( $tw) $author .= " ($tw)"; return $author; }
_A1方法:_请打开comments.php,ctrl+F查找wp_list_comments,如果后面跟着(‘type=comment&callback=custom_comments‘)这样,那么请继续,否则请直接alt+F4。
现在继续:
打开functions.php,找到如上callback后面跟的字母(此处为custom_comments)。然后会找到评论回调函数。
在你认为最舒服的地方输入以下代码:
//加入functions.php里回调函数custom_comments中,合适的地方 $tw = get_comment_meta( get_comment_ID(), 'twitter', true ); echo "@$twitter";
完工。
**情况B:**自定义了commentform,通常为自定义程度较高的主题(比如我的这个)。
要编辑的文件:functions.php,comments.php。
请根据参数,找到’author’、’email’、’url’这些东西。然后在下面添加如下内容:
//加入functions.php或者comments.php里合适的位置 'twitter' => '
' . '' . __( 'twitter' ) . '
',
我为了防止wordpress官方出什么幺蛾子,比如禁用了某方法、强制使用某函数等情况,用了comment_form()外加一个filter进行更换,本质上跟方法b一样。
4、不足
由于是根据comment_id插入的内容,所以与用户无关,只是comment_meta,因此之前的评论内容都不会出现twitter信息。
PS:很多同学说国内用不到,你不会换成渣浪微博么?