Add a product review with ratings programmatically in Woocommerce

泄露秘密 提交于 2019-12-07 07:33:26

With the key 'comment_post_ID' is where your comment will be shown, so desired product ID

Then you can use update_comment_meta() dedicated WordPress function to add a rating, like:

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

So your code will be like (where $product_id is the targeted product Id for this review):

$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 );

Tested and works as intended.

The author email and the user ID need to be some existing ones.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!