wp_update_comment() WP 2.0.0
Обновляет существующий комментарий в Базе Данных.
Перед обновлением функция проверяет правильное заполнение каждого поля комментария. Если какие-то поля не были указаны, то они будут дополнены из существующего в БД поля.
Функция ожидает экранированные данные. Т.е. передаваемые данные обрабатываются wp_unslash() самой функцией, поэтому не нужно заранее удалять слэши с полученного значения $_POST запроса...
Возвращает
Число/false/WP_Error. 1 при успешном обновлении. false/WP_Error при неудаче.
Использование
<?php wp_update_comment( $commentarr, $wp_error ) ?>
- $commentarr(массив) (обязательный)
- Массив содержащий информацию о комментарии, которую нужно обновить. Ключи массива — это поля таблицы которые будут обновлены. Обязательно нужно указать поле
comment_ID
.
- $wp_error(true/false) (WP 5.5)
- Нужно ли возвращать объект WP_Error при неудаче.
По умолчанию: false
Примеры
#1. Пример того как можно обновить текст комментария 37:
// Создаем массив данных
$commentarr = [
'comment_ID' => 37,
'comment_content' => 'Здесь новый текст комментария',
];
// Обновляем данные в БД
wp_update_comment( $commentarr );
Поля которые можно обновить, следующие:
[comment_post_ID] => 356
[comment_author] => shin
[comment_author_email] => shinreg@gmail.com
[comment_author_url] =>
[comment_author_IP] => 94.181.201.110
[comment_date] => 2011-08-16 00:45:37
[comment_date_gmt] => 2011-08-15 20:45:37
[comment_content] => большое спасибо!
[comment_karma] => 0
[comment_approved] => 1
[comment_agent] => Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 ...
[comment_type] =>
[comment_parent] => 2036
[user_id] => 0
Заметки
- Global. wpdb. $wpdb WordPress database abstraction object.
Список изменений
С версии 2.0.0 |
Введена. |
С версии 4.9.0 |
Add updating comment meta during comment update. |
С версии 5.5.0 |
The $wp_error parameter was added. |
С версии 5.5.0 |
The return values for an invalid comment or post ID were changed to false instead of 0. |
Код wp_update_comment() wp update comment
WP 5.6.2
<?php
function wp_update_comment( $commentarr, $wp_error = false ) {
global $wpdb;
// First, get all of the original fields.
$comment = get_comment( $commentarr['comment_ID'], ARRAY_A );
if ( empty( $comment ) ) {
if ( $wp_error ) {
return new WP_Error( 'invalid_comment_id', __( 'Invalid comment ID.' ) );
} else {
return false;
}
}
// Make sure that the comment post ID is valid (if specified).
if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
if ( $wp_error ) {
return new WP_Error( 'invalid_post_id', __( 'Invalid post ID.' ) );
} else {
return false;
}
}
// Escape data pulled from DB.
$comment = wp_slash( $comment );
$old_status = $comment['comment_approved'];
// Merge old and new fields with new fields overwriting old ones.
$commentarr = array_merge( $comment, $commentarr );
$commentarr = wp_filter_comment( $commentarr );
// Now extract the merged array.
$data = wp_unslash( $commentarr );
/**
* Filters the comment content before it is updated in the database.
*
* @since 1.5.0
*
* @param string $comment_content The comment data.
*/
$data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
$data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
if ( ! isset( $data['comment_approved'] ) ) {
$data['comment_approved'] = 1;
} elseif ( 'hold' === $data['comment_approved'] ) {
$data['comment_approved'] = 0;
} elseif ( 'approve' === $data['comment_approved'] ) {
$data['comment_approved'] = 1;
}
$comment_ID = $data['comment_ID'];
$comment_post_ID = $data['comment_post_ID'];
/**
* Filters the comment data immediately before it is updated in the database.
*
* Note: data being passed to the filter is already unslashed.
*
* @since 4.7.0
* @since 5.5.0 Returning a WP_Error value from the filter will short-circuit comment update
* and allow skipping further processing.
*
* @param array|WP_Error $data The new, processed comment data, or WP_Error.
* @param array $comment The old, unslashed comment data.
* @param array $commentarr The new, raw comment data.
*/
$data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr );
// Do not carry on on failure.
if ( is_wp_error( $data ) ) {
if ( $wp_error ) {
return $data;
} else {
return false;
}
}
$keys = array( 'comment_post_ID', 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_type', 'comment_parent', 'user_id', 'comment_agent', 'comment_author_IP' );
$data = wp_array_slice_assoc( $data, $keys );
$rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
if ( false === $rval ) {
if ( $wp_error ) {
return new WP_Error( 'db_update_error', __( 'Could not update comment in the database.' ), $wpdb->last_error );
} else {
return false;
}
}
// If metadata is provided, store it.
if ( isset( $commentarr['comment_meta'] ) && is_array( $commentarr['comment_meta'] ) ) {
foreach ( $commentarr['comment_meta'] as $meta_key => $meta_value ) {
update_comment_meta( $comment_ID, $meta_key, $meta_value );
}
}
clean_comment_cache( $comment_ID );
wp_update_comment_count( $comment_post_ID );
/**
* Fires immediately after a comment is updated in the database.
*
* The hook also fires immediately before comment status transition hooks are fired.
*
* @since 1.2.0
* @since 4.6.0 Added the `$data` parameter.
*
* @param int $comment_ID The comment ID.
* @param array $data Comment data.
*/
do_action( 'edit_comment', $comment_ID, $data );
$comment = get_comment( $comment_ID );
wp_transition_comment_status( $comment->comment_approved, $old_status, $comment );
return $rval;
}
Cвязанные функции