函数文档

wp_untrash_post_comments()

💡 云策文档标注

概述

wp_untrash_post_comments() 函数用于从回收站恢复指定文章的所有评论。它通过更新评论状态并清理缓存来实现,适用于 WordPress 开发者在处理评论恢复操作时调用。

关键要点

  • 函数接受一个可选参数 $post,可以是文章 ID、WP_Post 对象或 null(默认使用全局 $post)。
  • 恢复评论前会触发 'untrash_post_comments' 钩子,恢复后触发 'untrashed_post_comments' 钩子。
  • 函数内部使用 _wp_trash_meta_comments_status 元数据来存储评论原始状态,恢复后删除该元数据。
  • 返回 true 或 void:如果成功恢复评论或无操作则返回 true,如果文章不存在则返回 void。

代码示例

// 恢复当前文章的评论
wp_untrash_post_comments();

// 恢复指定文章 ID 的评论
wp_untrash_post_comments( 123 );

注意事项

  • 确保传入有效的文章 ID 或对象,否则函数可能提前返回。
  • 恢复操作涉及数据库查询和缓存清理,建议在适当钩子或上下文中使用。
  • 函数自 WordPress 2.9.0 版本引入,兼容性需考虑。

📄 原文内容

Restores comments for a post from the Trash.

Parameters

$postint|WP_Post|nulloptional
Post ID or post object. Defaults to global $post.

Default:null

Return

true|void

Source

function wp_untrash_post_comments( $post = null ) {
	global $wpdb;

	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	$post_id = $post->ID;

	$statuses = get_post_meta( $post_id, '_wp_trash_meta_comments_status', true );

	if ( ! $statuses ) {
		return true;
	}

	/**
	 * Fires before comments are restored for a post from the Trash.
	 *
	 * @since 2.9.0
	 *
	 * @param int $post_id Post ID.
	 */
	do_action( 'untrash_post_comments', $post_id );

	// Restore each comment to its original status.
	$group_by_status = array();
	foreach ( $statuses as $comment_id => $comment_status ) {
		$group_by_status[ $comment_status ][] = $comment_id;
	}

	foreach ( $group_by_status as $status => $comments ) {
		// Confidence check. This shouldn't happen.
		if ( 'post-trashed' === $status ) {
			$status = '0';
		}
		$comments_in = implode( ', ', array_map( 'intval', $comments ) );
		$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
	}

	clean_comment_cache( array_keys( $statuses ) );

	delete_post_meta( $post_id, '_wp_trash_meta_comments_status' );

	/**
	 * Fires after comments are restored for a post from the Trash.
	 *
	 * @since 2.9.0
	 *
	 * @param int $post_id Post ID.
	 */
	do_action( 'untrashed_post_comments', $post_id );
}

Hooks

do_action( ‘untrashed_post_comments’, int $post_id )

Fires after comments are restored for a post from the Trash.

do_action( ‘untrash_post_comments’, int $post_id )

Fires before comments are restored for a post from the Trash.

Changelog

Version Description
2.9.0 Introduced.