在Woocommerce中以编程方式添加评级产品评论

问题描述 投票:1回答:1

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

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

$time = current_time('mysql');

$data = array(
    'comment_post_ID' => 1,
    'comment_author' => 'admin',
    'comment_author_email' => '[email protected]',
    '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);
php wordpress woocommerce comments rating
1个回答
1
投票

使用密钥'comment_post_ID'将显示您的评论,因此需要产品ID

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

update_comment_meta( $comment_id, 'rating', 3 ); // The rating is an integer from 1 to 5

所以你的代码将是这样的(其中$product_id是此评论的目标产品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' => '[email protected]', // <== 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 );

经过测试并按预期工作。

作者电子邮件和用户ID需要是一些现有的。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.