WooCommerce单产品页面自动获取ID的评论短代码故障求助
修复WooCommerce产品评论短代码(自动获取当前产品ID)
你的代码存在几个关键问题导致无法正常运行,下面是修正后的版本,同时优化了逻辑和样式兼容性:
原代码的问题点:
$html变量未初始化,直接拼接会触发PHP未定义变量报错get_comments使用了字符串格式参数,正确写法应传入数组,且未筛选评论状态(会取出含未审核在内的所有状态评论)- 冗余的全局
$product处理,在产品页直接用get_the_id()就能拿到当前产品ID,无需额外判断 - HTML类名和WooCommerce默认结构不一致,可能导致样式错乱
修正后的完整代码:
add_shortcode( 'product_reviews', 'display_product_reviews' ); function display_product_reviews( $atts ){ // 自动获取当前产品ID,无需手动传入 $product_id = get_the_id(); // 只获取已审核的产品评论 $comments = get_comments( array( 'post_id' => $product_id, 'status' => 'approve', 'type' => 'review' // 指定仅获取产品评论类型 ) ); // 初始化HTML变量 $html = ''; if ( empty( $comments ) ) { return '<p class="woocommerce-noreviews">暂无评论</p>'; } // 沿用WooCommerce默认评论区的HTML结构和类名,保证样式兼容 $html .= '<div class="woocommerce-tabs"><div id="reviews" class="woocommerce-Reviews">'; $html .= '<ol class="commentlist woocommerce-Comments">'; foreach ( $comments as $comment ) { $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) ); $html .= '<li class="comment even thread-even depth-1" id="li-comment-' . $comment->comment_ID . '">'; $html .= get_avatar( $comment, '60', '', '', array( 'class' => 'woocommerce-review__avatar' ) ); $html .= '<div class="comment-text woocommerce-review__text">'; if ( $rating ) { $html .= '<div class="woocommerce-review__rating">' . wc_get_rating_html( $rating ) . '</div>'; } $html .= '<p class="meta"><strong class="woocommerce-review__author">' . get_comment_author( $comment ) . '</strong>'; $html .= '<span class="woocommerce-review__dash"> — </span>'; $html .= '<time class="woocommerce-review__published-date" datetime="' . get_comment_date( 'c', $comment ) . '">' . get_comment_date( '', $comment ) . '</time></p>'; $html .= '<div class="description woocommerce-review__description">'; $html .= wpautop( $comment->comment_content ); // 自动处理评论内容的段落换行 $html .= '</div></div></li>'; } $html .= '</ol></div></div>'; return $html; }
关键优化说明:
- 自动获取产品ID:直接调用
get_the_id(),在单个产品页该函数会自动返回当前产品ID,完全满足你的需求 - 评论筛选:通过
status => 'approve'和type => 'review'确保仅展示已审核的有效产品评论 - 样式兼容:使用WooCommerce默认评论区类名,主题样式会自动适配,无需额外编写CSS
- 内容格式化:用
wpautop()处理评论内容,保证段落和换行正常显示 - 无评论提示:无评论时返回友好提示,而非空内容
使用方法:
在单个产品页面的编辑器(或产品描述框)中添加短代码 [product_reviews] 即可,评论会自动显示在你放置短代码的位置。
内容的提问来源于stack exchange,提问作者Lars
相关产品推荐
相关产品推荐

