Change WordPress post preview URLs

When creating a headless or decoupled WordPress you may find that you want to display live previews on your chosen frontend.

This code sample can be added to your theme or child theme’s function.php file, or alternatively it may be put into a plugin.

// Change preview url for posts
add_filter( 'preview_post_link', 'func_preview_post_link', 10, 2 );
function func_preview_post_link($preview_link, $post ) {
  // TODO: Read from URL definition in a theme option setting
  $frontendUrl = "http://localhost:3000/";
  $frontendRoute = "api/preview/";

  $postId = "?postId=" . $post->ID;
  $postType = "&postType=" . $post->post_type;

  return $frontendUrl . $frontendRoute . $postId . $postType;
}Code language: PHP (php)

This method is better than a redirect to your frontend, it changes it within WordPress.

This article may be if interest as well, if you’re working with headless WordPress.

Change WordPress wp-admin ‘Visit site’ URL

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.