留言板是网站制作中的一个常见功能,比如你写了一篇不错的文章,读者想要和你交流一下,就可以直接通过留言板向你发送信息。或者在企业网站中常见的订单功能,也是留言板的一种。Wordpress中使用留言板非常简单。只需要一个函数comment_form()
就可以搞定。
留言板的使用方法
留言板通常放到page
或者是single
页面。 把函数comment_form()
放到单页或者文章的模板就可以。一行代码就可以搞定。
wrdpress 定制化留言板(前台显示)
默认留言板的字段和上面的图片是一样。有时候需要字段做一下修改。修改只有两种,第一删除,第二添加。
修改的方法 (下面的代码写在模板文件中)
function my_fields($fields) {
// 添加一个字段
$fields['tel'] = '<p class="comment-form-tel">' . '<label for="qq">' . "联系电话" . '</label> ' .
'<input id="tel" name="tel" type="text" value="' . esc_attr($commenter['comment_tel']) . '" size="30" /></p>';
unset($fields['url']); // 删除一个字段
//unset($fields['author']); // 删除作者字段
//unset($fields['email']); // 删除邮箱字段
return $fields;
}
// 对留言板字段进行处理
add_filter('comment_form_default_fields', 'my_fields');
// 输出处理后的留言板
comment_form();
修改前的留言板
修改后的留言板
wrdpress 定制化留言板(内容保存)
默认情况新增加的字段并不会自动保存,所有添加保存的代码,代码放到 functions.php
中
add_action('wp_insert_comment', 'wp_insert_my_comment', 10, 2);
function wp_insert_my_comment($comment_ID, $commmentdata) {
$tel = isset($_POST['tel']) ? $_POST['tel'] : false;
update_comment_meta($comment_ID, 'tel', $tel);
}
这段代码就保存了评论中的 tel
字段。
wrdpress 定制化留言板(后台显示)
对于自己添加的字段,默认是后台是不会显示的。所以添加一下代码到 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'] = __('联系电话');
$columns['email'] = __('电子邮箱');
return $columns;
}
# 添加字段的显示内容
function output_my_comments_columns($column_name, $comment_id) {
// die();
switch ($column_name) {
case "tel" :
echo get_comment_meta($comment_id, 'tel', true);
break;
case "email":
echo get_comment_author_email();
}
}
之后的效果图