Change WordPress wp-admin ‘Visit site’ URL

When creating a headless or decoupled WordPress you may find that you want to change the Visit site link in the wp-admin bar to 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.

add_action( 'admin_bar_menu', 'func_admin_bar_menu', 80 );
function func_admin_bar_menu( $wp_admin_bar ) {
  // TODO: Read from URL definition in a theme option setting
  $frontendUrl = "http://localhost:3000/";

  // Change the frontend URL
  $siteName = $wp_admin_bar->get_node('site-name');
  $siteName->meta['target'] = '_blank';
  $siteName->href = $frontendUrl;
  $siteName->title = 'Visit the Frontend';

  // Remove the dropdown option for "Visit site", it's redundant
}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 post preview URLs

Leave a Reply

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