WordPress函数:wp_delete_comment 删除评论

追格官方小助手/ 2023年03月01日/ WordPress/ 浏览 2052

WordPress 为删除评论,专门提供了一个函数:wp_delete_comment 。


除非垃圾箱已禁用、项目已在垃圾箱中或 $force_delete 为 true,否则注释将移至垃圾箱,而不是永久删除。如果评论获得批准并具有可用的帖子ID,则将更新文章评论计数。


函数原型:


wp_delete_comment( int|WP_Comment $comment_id, bool $force_delete = false ): bool


使用也很简单,如下:


wp_delete_comment(100, true);


使用 wp_delete_comment 删除评论和使用 $wpdb 直接从数据库删除有什么区别呢?


看看 wp_delete_comment 函数的源码就知道了。


function wp_delete_comment( $comment_id, $force_delete = false ) {
	global $wpdb;

	$comment = get_comment( $comment_id );
	if ( ! $comment ) {
		return false;
	}

	if ( ! $force_delete && EMPTY_TRASH_DAYS && ! in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ), true ) ) {
		return wp_trash_comment( $comment_id );
	}

	/**
	 * Fires immediately before a comment is deleted from the database.
	 *
	 * @since 1.2.0
	 * @since 4.9.0 Added the `$comment` parameter.
	 *
	 * @param string     $comment_id The comment ID as a numeric string.
	 * @param WP_Comment $comment    The comment to be deleted.
	 */
	do_action( 'delete_comment', $comment->comment_ID, $comment );

	// Move children up a level.
	$children = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID ) );
	if ( ! empty( $children ) ) {
		$wpdb->update( $wpdb->comments, array( 'comment_parent' => $comment->comment_parent ), array( 'comment_parent' => $comment->comment_ID ) );
		clean_comment_cache( $children );
	}

	// Delete metadata.
	$meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) );
	foreach ( $meta_ids as $mid ) {
		delete_metadata_by_mid( 'comment', $mid );
	}

	if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) ) {
		return false;
	}

	/**
	 * Fires immediately after a comment is deleted from the database.
	 *
	 * @since 2.9.0
	 * @since 4.9.0 Added the `$comment` parameter.
	 *
	 * @param string     $comment_id The comment ID as a numeric string.
	 * @param WP_Comment $comment    The deleted comment.
	 */
	do_action( 'deleted_comment', $comment->comment_ID, $comment );

	$post_id = $comment->comment_post_ID;
	if ( $post_id && 1 == $comment->comment_approved ) {
		wp_update_comment_count( $post_id );
	}

	clean_comment_cache( $comment->comment_ID );

	/** This action is documented in wp-includes/comment.php */
	do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );

	wp_transition_comment_status( 'delete', $comment->comment_approved, $comment );

	return true;
}


没想到,仅仅删除一条评论,就涉及到这么多操作。如果直接从数据库删除,这些钩子及其他关联问题就都无法妥善处理了。所以,最好还是使用 WordPress 提供的函数 wp_delete_comment 删除评论。


发表评论

暂无评论,抢个沙发...

客服 工单