钩子文档

preprocess_comment

💡 云策文档标注

概述

preprocess_comment 是一个 WordPress 过滤器,用于在评论数据被清理并插入数据库之前进行修改。它允许开发者干预评论提交过程,调整或验证评论内容。

关键要点

  • 过滤器钩子名称为 preprocess_comment,通过 apply_filters 调用。
  • 参数 $commentdata 是一个数组,包含评论的关键数据,如 comment_post_ID、comment_author、comment_content 等。
  • 可用于修改评论数据,例如移除 URL、格式化内容或添加自定义验证。
  • 在 wp_new_comment() 函数中使用,影响新评论的数据库插入。
  • 自 WordPress 1.5.0 引入,5.6.0 版本后 $commentdata 包含 comment_agent 和 comment_author_IP 值。

代码示例

add_filter( 'preprocess_comment', 'preprocess_comment_remove_url' );

function preprocess_comment_remove_url( $commentdata ) {
    // 移除评论作者 URL
    $commentdata['comment_author_url'] = '';
    // 如果评论内容全为大写,则转换为首字母大写
    if ( strtoupper( $commentdata['comment_content'] ) === $commentdata['comment_content'] ) {
        $commentdata['comment_content'] = ucwords( strtolower( $commentdata['comment_content'] ) );
    }
    return $commentdata;
}

📄 原文内容

Filters a comment’s data before it is sanitized and inserted into the database.

Parameters

$commentdataarray
Comment data.

More Information

The $commentdata array contains the following indices:
<br>
'comment_post_ID' - The post to which the comment will apply<br>
'comment_author' - (may be empty)<br>
'comment_author_email' - (may be empty)<br>
'comment_author_url' - (may be empty)<br>
'comment_content' - The text of the proposed comment<br>
'comment_type' - 'pingback', 'trackback', or empty for regular comments<br>
'user_ID' - (empty if not logged in)<br>

Source

$commentdata = apply_filters( 'preprocess_comment', $commentdata );

Changelog

Version Description
5.6.0 Comment data includes the comment_agent and comment_author_IP values.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    The example below remove the URL from the comment author text (comment_author_url) and changes the first character of each word of the comment content to upper case if it’s in all upper case.

    add_filter( 'preprocess_comment' , 'preprocess_comment_remove_url' );