我想在 WooCommerce 上的评论表单中添加一个自定义字段,就像这张图片一样:
我只知道如何通过添加以下代码在 single-product-reviews.php 文件上创建一个新字段:
$comment_form['comment_field'] .= '<p class="comment-form-title"><label for="title">' . esc_html__( 'Review title', 'woocommerce' ) . ' <span class="required">*</span></label><input id="title" name="title" type="text" aria-required="true" required></input></p>';
但是,我怎样才能把这个保存到数据库中,我怎样才能把这个标题输出到评论内容之上呢?
编辑: 我尝试了很多方法,直到通过在我的子主题的 functions.php 上编写这段代码来实现我想要的一些东西。
1) 在评论评论表单中添加自定义字段“评论标题”:
function add_review_title_field_on_comment_form() {
echo '<p class="comment-form-title uk-margin-top"><label for="title">' . __( 'Review title', 'text-domain' ) . '</label><input class="uk-input uk-width-large uk-display-block" type="text" name="title" id="title"/></p>';
}
add_action( 'comment_form_logged_in_after', 'add_review_title_field_on_comment_form' );
add_action( 'comment_form_after_fields', 'add_review_title_field_on_comment_form' );
2) 将该字段值保存在数据库的 wp_commentmeta 表中:
add_action( 'comment_post', 'instacraftcbd_review_title_save_comment' );
function instacraftcbd_review_title_save_comment( $comment_id ){
if( isset( $_POST['title'] ) )
update_comment_meta( $comment_id, 'title', esc_attr( $_POST['title'] ) );
}
3) 使用此方法检索该字段输出值:
var $title = get_comment_meta( $comment->comment_ID, "title", true );
echo $title;
现在唯一缺少的是,我怎样才能将该字段的输出放在评论文本或评论文本之前?
最佳答案
自己找到解决方案太好了,这是我正在寻找的答案,也许可以帮助你!
1) 转到父主题或子主题上的 functions.php,然后粘贴下面的代码以在评论评论表单上添加自定义字段“评论标题”:
function add_review_title_field_on_comment_form() {
echo '<p class="comment-form-title uk-margin-top"><label for="title">' . __( 'Review title', 'text-domain' ) . '</label><input class="uk-input uk-width-large uk-display-block" type="text" name="title" id="title"/></p>';
}
add_action( 'comment_form_logged_in_after', 'add_review_title_field_on_comment_form' );
add_action( 'comment_form_after_fields', 'add_review_title_field_on_comment_form' );
2) 通过在我们最后的代码上方添加此代码,将该字段值保存在数据库的 wp_commentmeta 表中:
add_action( 'comment_post', 'save_comment_review_title_field' );
function save_comment_review_title_field( $comment_id ){
if( isset( $_POST['title'] ) )
update_comment_meta( $comment_id, 'title', esc_attr( $_POST['title'] ) );
}
3) 如果您想检索该字段输出值,请使用以下代码:
var $title = get_comment_meta( $comment->comment_ID, "title", true );
echo $title;
注意:它仅适用于评论循环!
4) 要在每个评论文本之前添加该字段输出,您必须像这样在 functions.php 上创建一个新函数:
function get_review_title( $id ) {
$val = get_comment_meta( $id, "title", true );
$title = $val ? '<strong class="review-title">' . $val . '</strong>' : '';
return $title;
}
然后确保将下面的代码添加到该 WooCommerce 模板文件 review.php 或者您可以使用 woocommerce_review_before_comment_meta Hook ,但就我而言,我已经写了该代码:
echo get_review_title( $comment->comment_ID );
就在
do_action( 'woocommerce_review_before_comment_meta', $comment );
希望对你有帮助!
关于php - 如何在 WooCommerce 评论表单上添加 "Review title"字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633080/