我想将自定义字段添加到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上编写此代码来实现所需的功能为止.
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'] ) );
}
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'] ) );
}
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钩子,但是在我的情况下,我已经编写了该代码:
回声get_review_title($comment-> comment_ID);
刚过
do_action(‘woocommerce_review_before_comment_Meta’,$comment);
希望对您有所帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。