函数文档

post_preview()

💡 云策文档标注

概述

post_preview() 函数用于保存草稿或手动自动保存,以生成文章预览。它处理权限检查、保存逻辑,并返回重定向到预览页面的 URL。

关键要点

  • 函数核心功能:保存草稿或自动保存,用于预览文章。
  • 权限验证:检查当前用户是否有编辑文章的权限。
  • 保存逻辑:根据文章状态和锁定情况,调用 edit_post() 或 wp_create_post_autosave() 进行保存。
  • 错误处理:使用 is_wp_error() 检查保存结果,失败时调用 wp_die() 终止执行。
  • 预览参数:生成包含 preview_id、preview_nonce 等查询参数的 URL 用于重定向。

代码示例

// 示例调用 post_preview() 函数(通常在后台处理 POST 请求)
// 假设 $_POST['post_ID'] 已设置
$preview_url = post_preview(); // 返回重定向 URL
// 实际使用中,函数内部处理保存和重定向逻辑

注意事项

  • 函数依赖于 $_POST 数据,需确保 post_ID 等参数正确传递。
  • 自动保存时,会处理 post_status 从 auto-draft 到 draft 的转换。
  • 使用 wp_create_nonce() 生成预览 nonce 以增强安全性。
  • 相关函数包括 get_preview_post_link()、wp_check_post_lock() 等,用于辅助预览功能。

📄 原文内容

Saves a draft or manually autosaves for the purpose of showing a post preview.

Return

string URL to redirect to show the preview.

Source

function post_preview() {

	$post_id     = (int) $_POST['post_ID'];
	$_POST['ID'] = $post_id;

	$post = get_post( $post_id );

	if ( ! $post ) {
		wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
	}

	if ( ! current_user_can( 'edit_post', $post->ID ) ) {
		wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
	}

	$is_autosave = false;

	if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() === (int) $post->post_author
		&& ( 'draft' === $post->post_status || 'auto-draft' === $post->post_status )
	) {
		$saved_post_id = edit_post();
	} else {
		$is_autosave = true;

		if ( isset( $_POST['post_status'] ) && 'auto-draft' === $_POST['post_status'] ) {
			$_POST['post_status'] = 'draft';
		}

		$saved_post_id = wp_create_post_autosave( $post->ID );
	}

	if ( is_wp_error( $saved_post_id ) ) {
		wp_die( $saved_post_id->get_error_message() );
	}

	$query_args = array();

	if ( $is_autosave && $saved_post_id ) {
		$query_args['preview_id']    = $post->ID;
		$query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );

		if ( isset( $_POST['post_format'] ) ) {
			$query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
		}

		if ( isset( $_POST['_thumbnail_id'] ) ) {
			$query_args['_thumbnail_id'] = ( (int) $_POST['_thumbnail_id'] <= 0 ) ? '-1' : (int) $_POST['_thumbnail_id'];
		}
	}

	return get_preview_post_link( $post, $query_args );
}

Changelog

Version Description
2.7.0 Introduced.