# wp_new_comment()

URL: https://chugunov.pro/api-wordpress/functions/wp_new_comment/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 5.5.0.

## Сигнатура

```php
wp_new_comment( array $commentdata, bool $wp_error = false ): int|false|WP_Error
```

## Описание

Фильтрует новый комментарий, чтобы убедиться, что поля очищены и корректны, перед вставкой комментария в базу данных. Вызывает действие 'comment_post' с идентификатором комментария и признаком того, одобрен ли комментарий WordPress. Также имеет фильтр 'preprocess_comment' для обработки данных комментария до того, как их обработает функция.
Здесь мы используем REMOTE_ADDR напрямую. Если вы находитесь за прокси, вам следует убедиться, что он корректно задан для вашего окружения, например в wp-config.php.
См. https://core.trac.wordpress.org/ticket/9235
См. alsowp_insert_comment()

## Параметры

- `$commentdata` `array` — обязательный. Данные комментария.
  
  comment_author stringИмя автора комментария.
  
  comment_author_email stringАдрес электронной почты автора комментария.
  
  comment_author_url stringURL автора комментария.
  
  comment_content stringСодержимое комментария.
  
  comment_date stringДата отправки комментария. По умолчанию — текущее время.
  
  comment_date_gmt stringДата отправки комментария в часовом поясе GMT.
  
  По умолчанию — $comment_date в часовом поясе GMT.
  
  comment_type stringТип комментария. По умолчанию 'comment'.
  
  comment_parent intИдентификатор родителя этого комментария, если есть. По умолчанию 0.
  
  comment_post_ID intИдентификатор записи, к которой относится комментарий.
  
  user_id intИдентификатор пользователя, отправившего комментарий. По умолчанию 0.
  
  user_ID intСохранён для обратной совместимости. Используйте вместо него $user_id.
  
  comment_agent stringUser agent автора комментария. По умолчанию — значение 'HTTP_USER_AGENT' в суперглобальном массиве $_SERVER, отправленном в исходном запросе.
  
  comment_author_IP stringIP-адрес автора комментария в формате IPv4. По умолчанию — значение 'REMOTE_ADDR' в суперглобальном массиве $_SERVER, отправленном в исходном запросе.
- `$wp_error` `bool` — необязательный, по умолчанию `false`. Следует ли возвращать ошибки в виде объектов WP_Error вместо выполнения wp_die()?

## Возвращаемое значение

`int|false|WP_Error` — WP_Error

## Исходный код

Файл: `wp-includes/comment.php:2314`

```php
function wp_new_comment( $commentdata, $wp_error = false ) {
	global $wpdb;

	/*
	 * Normalize `user_ID` to `user_id`, but pass the old key
	 * to the `preprocess_comment` filter for backward compatibility.
	 */
	if ( isset( $commentdata['user_ID'] ) ) {
		$commentdata['user_ID'] = (int) $commentdata['user_ID'];
		$commentdata['user_id'] = $commentdata['user_ID'];
	} elseif ( isset( $commentdata['user_id'] ) ) {
		$commentdata['user_id'] = (int) $commentdata['user_id'];
		$commentdata['user_ID'] = $commentdata['user_id'];
	}

	$prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;

	if ( ! isset( $commentdata['comment_author_IP'] ) ) {
		$commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
	}

	if ( ! isset( $commentdata['comment_agent'] ) ) {
		$commentdata['comment_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
	}

	/**
	 * Filters a comment's data before it is sanitized and inserted into the database.
	 *
	 * @since 1.5.0
	 * @since 5.6.0 Comment data includes the `comment_agent` and `comment_author_IP` values.
	 *
	 * @param array $commentdata Comment data.
	 */
	$commentdata = apply_filters( 'preprocess_comment', $commentdata );

	$commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];

	// Normalize `user_ID` to `user_id` again, after the filter.
	if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
		$commentdata['user_ID'] = (int) $commentdata['user_ID'];
		$commentdata['user_id'] = $commentdata['user_ID'];
	} elseif ( isset( $commentdata['user_id'] ) ) {
		$commentdata['user_id'] = (int) $commentdata['user_id'];
		$commentdata['user_ID'] = $commentdata['user_id'];
	}

	$commentdata['comment_parent'] = isset( $commentdata['comment_parent'] ) ? absint( $commentdata['comment_parent'] ) : 0;

	$parent_status = ( $commentdata['comment_parent'] > 0 ) ? wp_get_comment_status( $commentdata['comment_parent'] ) : '';

	$commentdata['comment_parent'] = ( 'approved' === $parent_status || 'unapproved' === $parent_status ) ? $commentdata['comment_parent'] : 0;

	$commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );

	$commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );

	if ( empty( $commentdata['comment_date'] ) ) {
		$commentdata['comment_date'] = current_time( 'mysql' );
	}

	if ( empty( $commentdata['comment_date_gmt'] ) ) {
		$commentdata['comment_date_gmt'] = current_time( 'mysql', true );
	}

	if ( empty( $commentdata['comment_type'] ) ) {
		$commentdata['comment_type'] = 'comment';
	}

	$commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error );

	if ( is_wp_error( $commentdata['comment_approved'] ) ) {
		return $commentdata['comment_approved'];
	}

	$commentdata = wp_filter_comment( $commentdata );

	if ( ! in_array( $commentdata['comment_approved'], array( 'trash', 'spam' ), true ) ) {
		// Validate the comment again after filters are applied to comment data.
		$commentdata['comment_approved'] = wp_check_comment_data( $commentdata );
	}

	if ( is_wp_error( $commentdata['comment_approved'] ) ) {
		return $commentdata['comment_approved'];
	}

	$comment_id = wp_insert_comment( $commentdata );

	if ( ! $comment_id ) {
		$fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );

		foreach ( $fields as $field ) {
			if ( isset( $commentdata[ $field ] ) ) {
				$commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
			}
		}

		$commentdata = wp_filter_comment( $commentdata );

		$commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error );
		if ( is_wp_error( $commentdata['comment_approved'] ) ) {
			return $commentdata['comment_approved'];
		}

		$comment_id = wp_insert_comment( $commentdata );
		if ( ! $comment_id ) {
			return false;
		}
	}

	/**
	 * Fires immediately after a comment is inserted into the database.
	 *
	 * @since 1.2.0
	 * @since 4.5.0 The `$commentdata` parameter was added.
	 *
	 * @param int        $comment_id       The comment ID.
	 * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
	 * @param array      $commentdata      Comment data.
	 */
	do_action( 'comment_post', $comment_id, $commentdata['comment_approved'], $commentdata );

	return $comment_id;
}
```

## История изменений

- 5.5.0 — Introduced the comment_type argument.
- 4.7.0 — The $avoid_die parameter was added, allowing the function to return a WP_Error object instead of dying.
- 4.3.0 — Introduced the comment_agent and comment_author_IP arguments.
- 1.5.0 — Introduced.

## Связанные

Использует: [`wp_check_comment_data`](https://chugunov.pro/api-wordpress/functions/wp_check_comment_data/), `wpdb::strip_invalid_text_for_column`, [`current_time`](https://chugunov.pro/api-wordpress/functions/current_time/), [`wp_get_comment_status`](https://chugunov.pro/api-wordpress/functions/wp_get_comment_status/), [`wp_filter_comment`](https://chugunov.pro/api-wordpress/functions/wp_filter_comment/), [`wp_insert_comment`](https://chugunov.pro/api-wordpress/functions/wp_insert_comment/), [`wp_allow_comment`](https://chugunov.pro/api-wordpress/functions/wp_allow_comment/), [`absint`](https://chugunov.pro/api-wordpress/functions/absint/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/), [`do_action`](https://chugunov.pro/api-wordpress/functions/do_action/), [`is_wp_error`](https://chugunov.pro/api-wordpress/functions/is_wp_error/).
Используется в: [`wp_handle_comment_submission`](https://chugunov.pro/api-wordpress/functions/wp_handle_comment_submission/), [`wp_ajax_replyto_comment`](https://chugunov.pro/api-wordpress/functions/wp_ajax_replyto_comment/), `wp_xmlrpc_server::pingback_ping`, `wp_xmlrpc_server::wp_newComment`.

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/wp_new_comment/
