post_preview() WordPress Function

The post_preview() function allows you to view a post before it is published. This is useful for making sure that your post looks the way you want it to before making it public. To use this function, simply click on the "Preview" button while editing a post.

post_preview() #

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


Return

(string) URL to redirect to show the preview.


Top ↑

Source

File: wp-admin/includes/post.php

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() == $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 );
}


Top ↑

Changelog

Changelog
VersionDescription
2.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More