wordpress给文章评论表单只提供了四个默认字段,分别是昵称、邮箱、网址以及评论内容,只能满足一般博客网站的需求,如果想要增加更多的评论字段怎么办?可以通过wordpress评论自定义字段实现,类似于文章的自定义字段功能,对应数据表是wp_commentmeta,类似文章的postmeta数据表。
需要注意的是,该操作步骤不适合使用comment_form()函数的wordpress主题。
操作步骤:
1、找到主题的comments.php文件并对其进行编辑,在输入邮箱的字段代码下面添加以下代码:
<code>
<p>
<label for="tel">电话</label>
<input type="text" name="tel" class="text" id="tel" value="<?php echo get_comment_meta($comment->comment_ID,'tel',true); ?>" tabindex="3"/>
</p>
<p>
<label for="qq">QQ号</label>
<input type="text" name="qq" class="text" id="qq" value="<?php echo get_comment_meta($comment->comment_ID,'qq',true); ?>" tabindex="4"/>
</p>
2、在主题的functions.php文件中添加代码:
<code>
add_action('wp_insert_comment','wp_insert_tel',10,2);
function wp_insert_tel($comment_ID,$commmentdata) {
$tel = isset($_POST['tel']) ? $_POST['tel'] : false;
$qq = isset($_POST['qq']) ? $_POST['qq'] : false;
update_comment_meta($comment_ID,'tel',$tel);//tel 是存储在数据库里的字段名字
update_comment_meta($comment_ID,'qq',$qq);//qq 是存储在数据库里的字段名字
}
add_action()参数中的10和2分别表示该函数执行的优先级是10(默认值,值越小优先级越高),该函数接受2个参数。
3、在后台——评论中的列表里显示添加的字段,接着第二步的代码继续添加以下代码:
<code>
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' ] = __( '电话' ); //电话是代表列的名字
$columns[ 'qq' ] = __( 'QQ号' ); //QQ号是代表列的名字
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;
case "qq" :
echo get_comment_meta( $comment_id, 'qq', true );
break;
}
}
保存后,在后台——评论中就会看到添加的电话和QQ号,大功告成!