当您使用默认的评论功能进行评论时,您可以自己完成所有操作。关于如何做到这一点的大致想法如下:
步骤1:创建表单并显示
创建自己的表单并在帖子模板上排队
// Clear up the alert parameters.
$_SERVER[\'REQUEST_URI\'] = remove_query_arg( \'success\', $_SERVER[\'REQUEST_URI\'] );
<form method="post" action="<?php echo esc_url( $_SERVER[\'REQUEST_URI\'] ); ?>">
<label for="review-content"><?php _e( \'Your Review\' ); ?></label>
<textarea name="review_content" id="review-content" cols="30" rows="4"></textarea>
<?php wp_nonce_field( \'my-review-nonce\' ); ?>
<button type="submit" name="my_review_form"><?php _e( \'Save\' ); ?></button>
</form>
步骤2:获取表单数据截取表单提交并清理输入字段
使用wp_new_comment()
, 通过将“comment\\u type”设置为所需的注释类型(例如“review”)。您可以使用add_comment_meta()
有关其他信息:
<?php
/**
* Insert Review.
*
* Insert the Review intercepting my review form.
*/
function wpse366293_insert_review() {
if ( ! isset( $_POST[\'my_review_form\'] ) ) {
return;
}
if ( isset( $_POST[\'_wpnonce\'] ) && ! wp_verify_nonce( $_POST[\'_wpnonce\'], \'my-review-nonce\' ) ) {
return;
}
global $current_user;
// WARNING: Make sure the inputs are properly sanitized.
$review_id = wp_new_comment(
array(
\'comment_post_ID\' => absint( $post->ID ), // The post on which the reviews are being recorded.
\'comment_author\' => wp_strip_all_tags( $current_user->display_name ),
\'comment_author_email\' => sanitize_email( $current_user->user_email ),
\'comment_author_url\' => esc_url( $current_user->user_url ),
\'comment_content\' => $response_msg, // Sanitize as per your requirement. You can use wp_kses().
\'comment_type\' => \'review\', // Or, your custom comment type.
\'comment_parent\' => 0,
\'user_id\' => absint( $current_user->ID ),
)
);
// If error, return with the error message.
if ( is_wp_error( $review_id ) ) {
return $review_id->get_error_message();
}
// You can use add_comment_meta() for additional information.
// add_comment_meta( $review_id, \'my_meta_key\', $the_value_i_want );
// Redirect with a success hint.
wp_redirect( add_query_arg( \'success\', 1, get_the_permalink( $post->ID ) ) );
exit();
}
add_action( \'template_redirect\', \'wpse366293_insert_review\' );
步骤4:要显示评论,请查询评论并使用循环显示评论
WP_Comment_Query()
类或
get_comments()
功能:
$reviews = get_comments(
array(
\'post_type\' => \'post\', // Could be your CPT.
\'status\' => \'approve\',
\'orderby\' => \'comment_date\',
\'order\' => \'ASC\',
\'type\' => \'review\' // Your comment type.
)
);
if ( $reviews ) :
foreach ( $reviews as $review ) :
// Do whatever you want.
echo wpautop( $review->comment_content );
// Grab the meta data and display.
// echo get_comment_meta( $review->comment_ID, \'my_meta_key\', true );
endforeach;
endif;