php - 在 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);
解决方案
关键'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' => '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 );
经过测试并按预期工作。
作者电子邮件和用户 ID需要是一些现有的。
推荐阅读
- solr - Solr 请求未从数据库中获取记录
- r - 在R中将数据帧转换为json
- tsql - 在 where 子句中进行日期时间比较后的 MS SQL 算术溢出
- ruby-on-rails - 未定义的方法`password_confirmation=' rails 5
- django - Django:如何在 Django 查询中获取日期范围内的月份列表
- c# - 消费计划中的 Azure 函数执行相互干扰
- c# - C#:UseLegacyPathHandling 和 BlockLongPaths 的长路径不起作用
- java - 如何使用 TestRestTemplate 测试返回布尔值的休息服务
- ios - iOS Swift:从文件系统加载时区数据时出错
- swift - 登录和注销身份验证按钮在主视图控制器上从“登录”更改为“注销”,寻找最佳实践