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' );
function func_preview_post_link() {
  // TODO: Read from URL definition in a theme option setting
  $frontendUrl = "http://localhost:3000/";
  $frontendRoute = "api/preview/";

  $slug = basename(get_permalink());
  return $frontendUrl . $frontendRoute . $slug;
}

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.