How to change URL of “Preview in new tab” in Gutenberg editor

Why need to change preview link

WordPress is providing the REST APIs for everything. These days WordPress is using as a provider/back-end for editors. And it provides the data from REST APIs.

So it means WordPress sites have different domains like cms.example.com. And front-end(renderer) has the main domain like example.com. The front-end renderer can be on different technologies like react, angular, or any other.

In this condition, we need to change our preview link from our WordPress domain to the front-end domain and they then will use our REST APIs to render the preview data.

In my case, I am using revisions to provide the post history of changes in REST APIs.

How we can change preview link

Article Preview

You can write a simple code in your functions.php file and it’s done.

/**
 * Redirect preview link of article to front-end domain.
 */
add_action(
	'init',
	function() {
		if (
			! is_admin() &&
			isset( $_GET['preview'] ) &&
			true == $_GET['preview']
		) {
			if ( isset( $_GET['p'] ) ) {
				$post_id = intval( $_GET['p'] ); // Newly created article with draft status.
			}

			if ( isset( $_GET['preview_id'] ) ) {
				$post_id = intval( $_GET['preview_id'] ); // Published article.
			}

			$post = get_post( $post_id );

			if ( 'article' !== $post->post_type ) {
				return;
			}

			$revisions   = wp_get_post_revisions( $post_id );
			$revision    = reset( $revisions );
			$preview_url ='http://example.com/preview/' . $post_id . '/version/' . $revision->ID;

			wp_redirect( $preview_url );
			exit();
		}
	}
);

I have added a check for the article custom post type. So preview link will remain the same for posts, pages, and other custom post types.

Please follow and like us:
error0
fb-share-icon20
Tweet 20
fb-share-icon20

Leave a comment

Your email address will not be published. Required fields are marked *