在 Woocommerce 中以编程方式添加带有评分的产品评论

Rob*_*sen 4 php wordpress comments rating woocommerce

标题说明了一切。我知道评论是 Wordpress 中的原生评论帖子类型。我已经包含了添加评论的代码。

然而,问题是我不清楚如何给评论评级以及如何将其与特定产品联系起来。当我使用 comment_post_ID 时,它似乎没有将评论(评论)分配给正确的帖子。

$time = current_time('mysql');

$data = array(
    'comment_post_ID' => 1,
    'comment_author' => 'admin',
    'comment_author_email' => 'admin@admin.com',
    'comment_author_url' => 'http://',
    'comment_content' => 'content here',
    'comment_type' => '',
    'comment_parent' => 0,
    'user_id' => 1,
    'comment_author_IP' => '127.0.0.1',
    'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
    'comment_date' => $time,
    'comment_approved' => 1,
);

wp_insert_comment($data);
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 5

关键'comment_post_ID'是您的评论将显示的位置,因此所需的产品 ID

然后您可以使用update_comment_meta()专用的 WordPress 功能添加评分,例如:

update_comment_meta( $comment_id, 'rating', 3 ); // The rating is an integer from 1 to 5
Run Code Online (Sandbox Code Playgroud)

因此,您的代码将类似于 此评论的目标产品 ID在哪里$product_id ):

$comment_id = wp_insert_comment( array(
    'comment_post_ID'      => 37, // <=== The product ID where the review will show up
    'comment_author'       => 'LoicTheAztec',
    'comment_author_email' => 'loictheaztec@fantastic.com', // <== Important
    'comment_author_url'   => '',
    'comment_content'      => 'content here',
    'comment_type'         => '',
    'comment_parent'       => 0,
    'user_id'              => 5, // <== Important
    'comment_author_IP'    => '',
    'comment_agent'        => '',
    'comment_date'         => date('Y-m-d H:i:s'),
    'comment_approved'     => 1,
) );

// HERE inserting the rating (an integer from 1 to 5)
update_comment_meta( $comment_id, 'rating', 3 );
Run Code Online (Sandbox Code Playgroud)

经过测试并按预期工作。

作者的电子邮件用户ID必须是一些现有的。

在此处输入图片说明


Jon*_*man 5

接受的答案并不完整,因为问题包含如何将其与特定产品联系起来。此外,评论类型填充review。如果评论与产品无关,Yoast 模式和其他不会填充所有变量,Google 会向您发出有关模式标记的警告。

将其添加到已接受的答案中:

'comment_type'          => 'review'
Run Code Online (Sandbox Code Playgroud)

另外,与产品(您的$post_id)相关联,备注布尔值和数组。

if($comment_id) update_comment_meta($comment_id, 'rating', 5);
if($comment_id) update_comment_meta($comment_id, 'verified', 1);
    
if($comment_id) update_post_meta($post_id, '_wc_average_rating', '5.00');
if($comment_id) update_post_meta($post_id, '_wc_review_count', '1');
if($comment_id) update_post_meta($post_id, '_wc_rating_count', array(1));
Run Code Online (Sandbox Code Playgroud)

现在,Google 从 Woocommerce 3 和 2020 年开始接受这一点。@loictheastec,如果您愿意,您可以自行编辑。