WordPress扩展评论字段
WordPress的默认评论字段只有姓名(author),邮箱(email),网址(url),评论内容(comment).这对于一些企业网站,显然是不够的,WP的扩展性是很强的,扩展评论字段也非常简单.
首先把需要添加的评论字段加入评论表单:
function add_comment_location_field( $comment_fields ) {
$comment_fields['comment_location'] = '<p class="comment-form-location"><label for="location">' . __( 'Location' ) . '</label><input id="location" name="location" type="text" size="30" /></p>';
return $comment_fields;
}
add_filter( 'comment_form_fields', 'add_comment_location_field' );
仅仅这样做是不够的,在保存评论的时候我们需要把自定义评论字段也保存起来:
function save_comment_location( $comment_id ) {
if ( isset( $_POST['location'] ) )
$location = wp_filter_nohtml_kses( $_POST['location'] );
add_comment_meta( $comment_id, 'location', $location );
}
add_action( 'comment_post', 'save_comment_location' );
恩,差不多了,显示自定义评论字段也非常简单:
$location = get_comment_meta( get_comment_ID(), 'location', true );
echo '<p>Location: ' . $location . '</p>';
看起来已经可以了,但是还有一个问题是怎样在后台的评论列表中显示自定字段呢:
function add_comment_location_column($columns) {
$columns['location'] = __('区域', 'theme_name');
return $columns;
}
add_filter('manage_edit-comments_columns', 'add_comment_location_column');
function add_comment_location_value($column_name, $comment_ID) {
if ($column_name === 'location') {
$comment_location = get_comment_meta($comment_ID, 'location', true);
echo $comment_location;
}
}
add_action('manage_comments_custom_column', 'add_comment_location_value', 10, 2);
以上就是wordpress添加自定义评论字段的方法.如果你对代码不熟悉,可以选择使用插件来扩展评论字段,也是非常简单的.
发表回复