preprocess_comment
Filters comment data before it is sanitized and added to the database. The filter fires at the very beginning of wp_new_comment(), which adds a new comment.
Usage
add_filter( 'preprocess_comment', 'wp_kama_preprocess_comment_filter' );
/**
* Function for `preprocess_comment` filter-hook.
*
* @param array $commentdata Comment data.
*
* @return array
*/
function wp_kama_preprocess_comment_filter( $commentdata ){
// filter...
return $commentdata;
}
- $commentdata(array)
The data of the comment being added. It looks approximately like this:
Array( [comment_post_ID] => 4929 [comment_author] => Kama [comment_author_email] => [email protected] [comment_author_url] => [comment_content] => Comment text [comment_type] => [comment_parent] => 0 [user_ID] => 1 [comment_author_IP] => 123.123.123.123 [comment_agent] => Mozilla/5.0 (Windows NT 6.1; Win64; ... )
Examples
#1 Set a custom comment type
Suppose the site has a custom post type and its comments must also have a custom type. The comment type is stored in the comment_type field of the wp_comments table.
This example sets the comment type to for_book when a comment is submitted for the book post type:
// Set the for_book comment type when adding a comment
add_filter( 'preprocess_comment', 'set_for_book_comment_type' );
function set_for_book_comment_type( $commentdata ){
$post = get_post( $commentdata['comment_post_ID'] );
if( $post->post_type == 'book' )
$commentdata['comment_type'] = 'for_book';
return $commentdata;
}Changelog
| Since 1.5.0 | Introduced. |
| Since 5.6.0 | Comment data includes the comment_agent and comment_author_IP values. |
Where the hook is called
preprocess_comment
wp-includes/comment.php 2405
$commentdata = apply_filters( 'preprocess_comment', $commentdata );