WordPress评论表单增加字段

来源:互联网 发布:dnf强行交易软件 编辑:程序博客网 时间:2024/04/30 12:42

问题描述

用 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

存储的形式就是上面那样的,duoshuo_post_id 就是字段的名称,meta_value存储的就是内容。

如何向评论表单添加自定义字段

 

1、  在comments.php评论表单中添加自己想要的字段,如:

1<p>
2    <input type="text" name="tel" id="tel" size="22" tabindex="4" />
3    <label for="tel">电话</label>
4</p>

tabindex 这个属性按照从小到大排,为什么要这样?你可以自己试试….

 

2、如果评论表单是使用系统自带的,那么请用以下方法添加表单字段,如果不是,请略过

1add_filter('comment_form_default_fields','comment_form_add_ewai');
2function comment_form_add_ewai($fields) {
3    $label1 = __( '国家/地区' );
4    $label2 = __( 'Skype账号' );
5    $label3 = __( '电话' );
6    $label4 = __( '传真' );
7    $label5 = __( '地址' );
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
14    <p>
15    <label for="guojia">{$label1}</label>
16    <input id="guojia" name="guojia" type="text" value="{$value1}" size="30" />
17    </p>
18    HTML;
19    return $fields;
20}

 

3、  接收表单字段并写入数据库

在主题目录的 functions.php添加以下代码

1add_action('wp_insert_comment','wp_insert_tel',10,2);
2function wp_insert_tel($comment_ID,$commmentdata) {
3    $tel = isset($_POST['tel']) ? $_POST['tel'] : false;
4    //_tel 是存储在数据库里的字段名字,取出数据的就会用到
5    update_comment_meta($comment_ID,'_tel',$tel);
6}

这两步就可以将数据写入数据库了,不信你试试看

add_action()参数中的10和2分别表示该函数执行的优先级是10(默认值,值越小优先级越高),该函数接受2个参数。

 

4、在后台显示额外字段

前面两步只是接收和写入到数据库,那么要怎么在后台评论列表中显示呢?将以下代码复制到主题目录的functions.php 中:

1add_filter( 'manage_edit-comments_columns''my_comments_columns' );
2add_action( 'manage_comments_custom_column''output_my_comments_columns', 10, 2 );
3function my_comments_columns( $columns ){
4    $columns'_tel' ] = __( '电话' );        //电话是代表列的名字
5    return $columns;
6}
7function  output_my_comments_columns( $column_name$comment_id ){
8    switch$column_name ) {
9    case "_tel" :
10    echo get_comment_meta( $comment_id'_tel', true );
11    break;
12}

如果要在前台的留言列表中调用,就用以下代码,_tel就是你在数据库中存储的字段名字

1<?php
2$tel = get_comment_meta($comment->comment_ID,'_tel',true);
3if( !empty($tel)){
4    echo "电话".$tel;
5}
6?>

 

5、  大功告成,看看后台的评论列表,是不是多了一列电话,那样的话就没错了。

20140509003942

 

6、如果要移除某一个自带的表单字段,可以使用以下代码

查看源代码
打印帮助
1function tel_filtered($fields){
2    if(isset($fields['tel']))
3    unset($fields['tel']);
4    return $fields;
5}
6add_filter('comment_form_default_fields''tel_filtered');
0 0