comment_exists()
云策文档标注
概述
comment_exists() 函数用于根据评论作者和日期检查评论是否存在。为获得最佳性能,建议使用 $timezone = 'gmt' 参数,因为它查询已建立索引的字段。
关键要点
- 函数基于 $comment_author 和 $comment_date 参数判断评论是否存在。
- $timezone 参数接受 'blog' 或 'gmt' 值,默认值为 'blog',但推荐使用 'gmt' 以优化查询性能。
- 返回值为评论的 post ID(成功时)或 null。
- 函数内部使用 $wpdb->get_var() 和 $wpdb->prepare() 进行安全的数据库查询。
代码示例
function comment_exists( $comment_author, $comment_date, $timezone = 'blog' ) {
global $wpdb;
$date_field = 'comment_date';
if ( 'gmt' === $timezone ) {
$date_field = 'comment_date_gmt';
}
return $wpdb->get_var(
$wpdb->prepare(
"SELECT comment_post_ID FROM $wpdb->comments
WHERE comment_author = %s AND $date_field = %s",
stripslashes( $comment_author ),
stripslashes( $comment_date )
)
);
}注意事项
- 从版本 4.4.0 开始添加了 $timezone 参数,以支持更灵活的时区处理。
- 函数自 2.0.0 版本引入,是 WordPress 核心功能的一部分。
原文内容
Determines if a comment exists based on author and date.
Description
For best performance, use $timezone = 'gmt', which queries a field that is properly indexed. The default value for $timezone is ‘blog’ for legacy reasons.
Parameters
$comment_authorstringrequired-
Author of the comment.
$comment_datestringrequired-
Date of the comment.
$timezonestringrequired-
Timezone. Accepts
'blog'or'gmt'. Default'blog'.
Source
function comment_exists( $comment_author, $comment_date, $timezone = 'blog' ) {
global $wpdb;
$date_field = 'comment_date';
if ( 'gmt' === $timezone ) {
$date_field = 'comment_date_gmt';
}
return $wpdb->get_var(
$wpdb->prepare(
"SELECT comment_post_ID FROM $wpdb->comments
WHERE comment_author = %s AND $date_field = %s",
stripslashes( $comment_author ),
stripslashes( $comment_date )
)
);
}