十一年专注,只做WordPress定制开发一件事

WordPress主题开发中添加新评论到数据库函数:wp_new_comment()

王超
2020-04-03
WP常用函数
3,718 次

最近我们在开发以WordPress作为后端管理的小程序的时候,需要用户在小程序前端提交评论给文章,于是就用到了这个函数wp_new_comment();

其实这个函数和另外一个向WordPress数据库添加新评论函数基本差不多,那就是wp_insert_comment();唯一的区别就是wp_new_comment()会通过过滤器和钩子判断评论数据是否被允许添加到WordPress数据库中,而wp_insert_comment函数则不会检查,直接添加到数据库。

参数说明

wp_new_comment函数参数与wp_insert_comment函数参数差不多,只是多了一个是否返回wp_error错误对象的参数而已。

wp_new_comment( array $commentdata, bool $avoid_die = false )

$commentdata

(array) 评论数组。

  • ‘comment_agent’
    (string) 用户评论时的代理标识,默认空。
  • ‘comment_approved’
    (int|string) 是否有评论已经得到了批准,默认1。
  • ‘comment_author’
    (string) 评论者的名字,默认为空。
  • ‘comment_author_email’
    (string) 评论者的邮箱地址,默认为空。
  • ‘comment_author_IP’
    (string) 评论者的ip,默认为空。
  • ‘comment_author_url’
    (string) 评论者的url地址,默认为空。
  • ‘comment_content’
    (string) 评论内容。
  • ‘comment_date’
    (string) 评论提交的日期,手动指定时必须指定日期时区comment_date_gmt参数,默认当前日期。
  • ‘comment_date_gmt’
    (string) 评论提交时的时区,默认是站点所选时区。
  • ‘comment_karma’
    (int) The karma of the comment. Default 0.这玩意儿看不懂是什么,默认0
  • ‘comment_parent’
    (int) 评论所属父评论id,如果有的话(就是楼主评论id)
  • ‘comment_post_ID’
    (int) 涉及到的评论文章id,默认0。
  • ‘comment_type’
    (string) 评论类型,默认空。
  • ‘comment_meta’
    (array) 键/值对数组存储在commentmeta新评论。
  • ‘user_id’
    (int)评论用户的id,默认0。

$avoid_die

(bool)是否返回wp_error错误对象,默认false,不返回直接输出错误。

简单使用

$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID'); 
$comment_id = wp_new_comment( $commentdata,true);
if(is_wp_error($comment_id)){
    err( '重复评论' );
}
}

如果使用了ajax提交评论,返回wp_error错误对象会导致你的文章布局错乱,正确的ajax评论提交接口应判断是否返回了wp_error错误对象,根据返回不同自定义返回内容。

文章标签:

WordPress日记主要承接WordPress主题定制开发PSD转WordPressWordPress仿站以及以WordPress为管理后端的小程序、APP,我们一直秉持“做一个项目,交一个朋友”的理念,希望您是我们下一个朋友。如果您有WordPress主题开发需求,可随时联系QQ:919985494 微信:18539976310

搜索

嘿,有问题找我来帮您!