给WP评论者信息栏加入twitter账号输入框
之前在某位博友那里看到了显示评论用户twitter账号的功能,这个有点意思……然后就想自己折腾一个出来。其实用插件实现起来很简单,比如Custom Comment之类的,都可以。但是本着不折腾不舒服的原则,还是决定自己实践一把–手工添加上去为好,如此一来装逼的同时省下一个插件,并能输出一篇文章,何乐而不为呢。
1、总述
诸君如果想要手动实现此功能,大致可以分三步:在评论栏里添加输入框=>设置后台保存数据的方法=>前台回显保存的数据
此篇的方法,我主要参照了 此篇文章
2、主题情况
视主题不同,主要分了两种情况,A和B,请对号入座。
查看方式:请打开你的comments.php文件,之后ctrl+F,查找comment_form()这一句代码,如果找到并且不附带任何参数,A;找到并且有参数B;其他情况C。
情况A:此情况主题直接使用了commentform函数。普遍存在于版本较新的通用主题之中。
需要编辑的文件:functions.php。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
//此内容加入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'] .= '<p class="comment-form-author">' . '<label for="twitter">'. __('twitter') . '</label> <input id="twitter" name="twitter" size="30" type="text" /></p>'; 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)。然后会找到评论回调函数。
在你认为最舒服的地方输入以下代码:
1 2 3 |
//加入functions.php里回调函数custom_comments中,合适的地方 $tw = get_comment_meta( get_comment_ID(), 'twitter', true ); echo "<a href='http://twitter.com/#!/$twitter' title='@$twitter'>@$twitter</a>"; |
完工。
情况B:自定义了commentform,通常为自定义程度较高的主题(比如我的这个)。
要编辑的文件:functions.php,comments.php。
请根据参数,找到’author’、’email’、’url’这些东西。然后在下面添加如下内容:
1 2 3 |
//加入functions.php或者comments.php里合适的位置 'twitter' => '<p class="comment-form-twitter">' . '<input id="twitter" name="twitter" type="text" value="" size="30" /><label for="twitter">' . __( 'twitter' ) . '</label></p>', |
我为了防止wordpress官方出什么幺蛾子,比如禁用了某方法、强制使用某函数等情况,用了comment_form()外加一个filter进行更换,本质上跟方法b一样。
4、不足
由于是根据comment_id插入的内容,所以与用户无关,只是comment_meta,因此之前的评论内容都不会出现twitter信息。
PS:很多同学说国内用不到,你不会换成渣浪微博么?
试试
@zwwooooo 原来要输入的……我以为自动就能知道我有twitter那么未来
@zwwooooo 你要在ajax评论提交后的评论显示上也加上,要完美主义!
@zwwooooo 不要!
呃,为毛世界上优秀的网站都离我这么远!
看下效果
先试试效果如何,感谢之至!
测试
这个很有意思啊
挺好的效果
怎么缓存这货啊
@大发 save_comment_meta_data啊~然后跟其他的name、url、email一样调用就可以了。
@axiu 不是,我的意思是浏览器缓存啊。。。我看你这能缓存上啊,我那得重新输入呢。。
@大发 你可以本地测试一下看能不能生成这个字段的cookie,生成了的话就可以采取手段调用,评论框得手动定义一下,比如提取cookie然后填充进去。。具体我也忘了怎么整的了……
@axiu
可以参考 wp_get_current_commenter 方法。
sdfsfsdfdsf