问题描述
用 wp 的友友门都知道,wordpress评论表单的字段都只有4个,昵称、邮箱、网址、内容;评论是存在wp_comments表中的,如果要加上其它额外字段就得另寻它法了,例如:tel电话字段。
解决思路
Wp_comments 也有一个与之对应的meta表,叫wp_commentmeta,Posts文章表可以用postmeta存储一些额外的信息,那么comment也可以用commentmeta存储额外的评论字段。如果你装了多说评论插件,那么你再看看wp_commentmeta表,多说也是这么存储内容的,这个表一共有四个字段:meta_id、comment_id、meta_key、meta_value,看下面的截图:
![20140509001202](http://www.web-fish.com/wp-content/uploads/2014/05/20140509001202.jpg)
存储的形式就是上面那样的,duoshuo_post_id 就是字段的名称,meta_value存储的就是内容。
如何向评论表单添加自定义字段
1、 在comments.php评论表单中添加自己想要的字段,如:
2 | < input type = "text" name = "tel" id = "tel" size = "22" tabindex = "4" /> |
3 | < label for = "tel" >电话</ label > |
tabindex 这个属性按照从小到大排,为什么要这样?你可以自己试试….
2、如果评论表单是使用系统自带的,那么请用以下方法添加表单字段,如果不是,请略过
1 | add_filter( 'comment_form_default_fields' , 'comment_form_add_ewai' ); |
2 | function comment_form_add_ewai( $fields ) { |
3 | $label1 = __( '国家/地区' ); |
4 | $label2 = __( 'Skype账号' ); |
8 | $value1 = isset( $_POST [ 'guojia' ]) ? $_POST [ 'guojia' ] : false; |
9 | $value2 = isset( $_POST [ 'skype' ]) ? $_POST [ 'skype' ] : false; |
10 | $value3 = isset( $_POST [ 'tel' ]) ? $_POST [ 'tel' ] : false; |
11 | $value4 = isset( $_POST [ 'fax' ]) ? $_POST [ 'fax' ] : false; |
12 | $value5 = isset( $_POST [ 'address' ]) ? $_POST [ 'address' ] : false; |
13 | $fields [ 'guojia' ] =<<<HTML |
15 | <label for = "guojia" >{ $label1 }</label> |
16 | <input id= "guojia" name= "guojia" type= "text" value= "{$value1}" size= "30" /> |
3、 接收表单字段并写入数据库
在主题目录的 functions.php添加以下代码
1 | add_action( 'wp_insert_comment' , 'wp_insert_tel' ,10,2); |
2 | function wp_insert_tel( $comment_ID , $commmentdata ) { |
3 | $tel = isset( $_POST [ 'tel' ]) ? $_POST [ 'tel' ] : false; |
5 | update_comment_meta( $comment_ID , '_tel' , $tel ); |
这两步就可以将数据写入数据库了,不信你试试看
add_action()参数中的10和2分别表示该函数执行的优先级是10(默认值,值越小优先级越高),该函数接受2个参数。
4、在后台显示额外字段
前面两步只是接收和写入到数据库,那么要怎么在后台评论列表中显示呢?将以下代码复制到主题目录的functions.php 中:
1 | add_filter( 'manage_edit-comments_columns' , 'my_comments_columns' ); |
2 | add_action( 'manage_comments_custom_column' , 'output_my_comments_columns' , 10, 2 ); |
3 | function my_comments_columns( $columns ){ |
4 | $columns [ '_tel' ] = __( '电话' ); |
7 | function output_my_comments_columns( $column_name , $comment_id ){ |
8 | switch ( $column_name ) { |
10 | echo get_comment_meta( $comment_id , '_tel' , true ); |
如果要在前台的留言列表中调用,就用以下代码,_tel就是你在数据库中存储的字段名字
2 | $tel = get_comment_meta( $comment ->comment_ID, '_tel' ,true); |
5、 大功告成,看看后台的评论列表,是不是多了一列电话,那样的话就没错了。
![20140509003942](http://www.web-fish.com/wp-content/uploads/2014/05/20140509003942.jpg)
6、如果要移除某一个自带的表单字段,可以使用以下代码
1 | function tel_filtered( $fields ){ |
2 | if (isset( $fields [ 'tel' ])) |
6 | add_filter( 'comment_form_default_fields' , 'tel_filtered' ); |