给wordpress评论表单增加字段的方法_给WordPress评论表单增加字段的方法

更新时间:2019-06-11    来源:WordPress    手机版     字体:

【www.bbyears.com--WordPress】

问题描述

用 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,看下面的截图:

存储的形式就是上面那样的,duoshuo_post_id 就是字段的名称,meta_value存储的就是内容。
如何向评论表单添加自定义字段
 
1、  在comments.php评论表单中添加自己想要的字段,如:


   
   

tabindex 这个属性按照从小到大排,为什么要这样?你可以自己试试….
 
2、如果评论表单是使用系统自带的,那么请用以下方法添加表单字段,如果不是,请略过


add_filter("comment_form_default_fields","comment_form_add_ewai");
function comment_form_add_ewai($fields) {
    $label1 = __( "国家/地区" );
    $label2 = __( "Skype账号" );
    $label3 = __( "电话" );
    $label4 = __( "传真" );
    $label5 = __( "地址" );
    $value1 = isset($_POST["guojia"]) ? $_POST["guojia"] : false;
    $value2 = isset($_POST["skype"]) ? $_POST["skype"] : false;
    $value3 = isset($_POST["tel"]) ? $_POST["tel"] : false;
    $value4 = isset($_POST["fax"]) ? $_POST["fax"] : false;
    $value5 = isset($_POST["address"]) ? $_POST["address"] : false;
    $fields["guojia"] =<<    


   
   
   


    HTML;
    return $fields;
}
 
3、  接收表单字段并写入数据库

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

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

这两步就可以将数据写入数据库了,不信你试试看
add_action()参数中的10和2分别表示该函数执行的优先级是10(默认值,值越小优先级越高),该函数接受2个参数。
 
4、在后台显示额外字段

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

add_filter( "manage_edit-comments_columns", "my_comments_columns" );
add_action( "manage_comments_custom_column", "output_my_comments_columns", 10, 2 );
function my_comments_columns( $columns ){
    $columns[ "_tel" ] = __( "电话" );        //电话是代表列的名字
    return $columns;
}
function  output_my_comments_columns( $column_name, $comment_id ){
    switch( $column_name ) {
    case "_tel" :
    echo get_comment_meta( $comment_id, "_tel", true );
    break;
}

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

$tel = get_comment_meta($comment->comment_ID,"_tel",true);
if( !empty($tel)){
    echo "电话".$tel;
}
?>
 
5、  大功告成,看看后台的评论列表,是不是多了一列电话,那样的话就没错了。

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

function tel_filtered($fields){
    if(isset($fields["tel"]))
    unset($fields["tel"]);
    return $fields;
}
add_filter("comment_form_default_fields", "tel")

本文来源:http://www.bbyears.com/wangyezhizuo/54132.html