在WordPress中创建自定义评论功能
本文将教你如何在WordPress中创建自定义评论功能,以便为访客提供更丰富的互动体验。
-
玖比肆 评论步骤1:创建自定义评论模板
首先,创建一个自定义评论模板。在你的主题文件夹中创建一个新的文件夹,名为“comments”。在该文件夹中创建一个名为“comments.php”的文件。
该文件应包括以下内容:
```
' . get_the_title() . '' );
} else {
printf(
/* translators: 1: number of comments, 2: post title */
esc_html( _nx( '%1$s thought on “%2$s”', '%1$s thoughts on “%2$s”', $comments_number, 'comments title', 'text-domain' ) ),
number_format_i18n( $comments_number ),
'' . get_the_title() . ''
);
}
?>
'
',
'title_reply_after' => '',
) );
?>```
步骤2:添加自定义评论字段
接下来,你可以添加自定义评论字段以便让访客提供更多信息。在“functions.php”文件中添加以下代码:
```
function custom_comment_fields( $fields ) {
$fields['website'] = '';
return $fields;
}
add_filter( 'comment_form_default_fields', 'custom_comment_fields' );
```此代码将为评论表单添加一个网站字段。
步骤3:保存和显示评论字段
接下来,你需要保存和显示自定义评论字段。在“functions.php”文件中添加以下代码:
```
function save_comment_meta_data( $comment_id ) {
if ( ( isset( $_POST['website'] ) ) && ( $_POST['website'] != '') ) {
$website = wp_kses_post( $_POST['website'] );
add_comment_meta( $comment_id, 'website', $website );
}
}
add_action( 'comment_post', 'save_comment_meta_data' );function show_comment_meta_data( $comment_id ) {
$website = get_comment_meta( $comment_id, 'website', true );
if ( ! empty( $website ) ) {
printf( '%s: %s
', __( 'Website', 'text-domain' ), $website );
}
}
add_filter( 'comment_text', 'show_comment_meta_data' );
```此代码将保存和显示评论中的网站字段。
步骤4:添加回复链接
最后,你可以为你的评论添加回复链接。在“functions.php”文件中添加以下代码:
```
function add_reply_link( $comment_text, $comment ) {
$comment_text .= '';
return $comment_text;
}
add_filter( 'comment_text', 'add_reply_link', 10, 2 );
```此代码将在每个评论下添加一个回复链接。
现在你已经创建了自定义评论功能,为你的WordPress网站提供了更丰富的互动体验。
2023年 4月 25日 上午4:26

'short_ping' => true,
'avatar_size'=> 42
) );
?>