钩子文档

comment_post

💡 云策文档标注

概述

comment_post 是一个 WordPress 动作钩子,在评论被插入数据库后立即触发。它允许开发者在评论提交时执行自定义代码,常用于处理评论状态、发送通知等场景。

关键要点

  • 触发时机:评论插入数据库后立即执行
  • 参数:$comment_id(评论ID)、$comment_approved(批准状态,可为1、0、'spam'或'trash')、$commentdata(评论数据数组)
  • 用途:用于在评论发布后添加自定义功能,如状态检查、邮件通知等
  • 版本变化:WordPress 4.5.0 添加了 $commentdata 参数

代码示例

function show_message_function( $comment_ID, $comment_approved ) {
    if( 1 === $comment_approved ){
        //function logic goes here
    }
}
add_action( 'comment_post', 'show_message_function', 10, 2 );

注意事项

  • 使用 add_action 时需指定参数数量(如 , 10, 2),否则只能访问第一个参数
  • $comment_approved 可能为 'trash',表示评论因设置中的禁用关键词被自动移至垃圾箱

📄 原文内容

Fires immediately after a comment is inserted into the database.

Parameters

$comment_idint
The comment ID.
$comment_approvedint|string
1 if the comment is approved, 0 if not, 'spam' if spam.
$commentdataarray
Comment data.

Source

do_action( 'comment_post', $comment_id, $commentdata['comment_approved'], $commentdata );

Changelog

Version Description
4.5.0 The $commentdata parameter was added.
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    The following example uses the comment_post hook to run a function immediately after a comment is posted. The function checks whether the comment is approved and, if so, executes the code specified.

    function show_message_function( $comment_ID, $comment_approved ) {
    	if( 1 === $comment_approved ){
    		//function logic goes here
    	}
    }
    add_action( 'comment_post', 'show_message_function', 10, 2 );

    Note that the add_action line includes the priority and the number of parameters (, 10, 2). If we leave the number of parameters out, we will only be able to access to the first parameter ($comment_ID) in our function. We will not be able to access the second parameter ($comment_approved).

  2. Skip to note 6 content

    Get notified via email when a user posts a comment on your site’s blog.

    function wpdocs_notify_my_mail( $comment_id, $comment_approved ) {
    	if ( ! $comment_approved ) {
    		$comment = get_comment( $comment_id );
    		$mail = 'test@example.org';
    		$subject = sprintf( 'New Comment by: %s', $comment->comment_author );
    		$message = $comment->comment_content;
    
    		wp_mail( $mail, $subject, $message );
    	}
    }
    add_action( 'comment_post', 'wpdocs_notify_my_mail', 10, 2 );