Categories
WordPress

WordPress Menus with URLs That Don’t Break

WordPress has a handy Menus feature in the Appearance area of the admin. You can link to Pages and Post Categories and these will migrate fine as you move your site from a development to production environments and the site URL changes.

Sometimes though you may need to refer to internal URLs not supported by Menus natively  using the Custom URL feature. The problem is that specifying the absolute URL here will break when the site is deployed.

A simple solution is to add a filter and use a placeholder value in Custom URLs added to a menu.

wordpress-menu-custom-urls

Then add a filter in your themes functions.php file, or as a must-use plugin as a more robust solution:

<?php 
/**
* Replace (site_url) placeholder in navigation menus
* Helps keep menus portable between dev/staging/production environments
*/
add_filter(
	'wp_nav_menu', 
	function($menu) {
		$menu = str_replace('(site_url)', home_url(), $menu);
		return preg_replace('~https?\:\/\/(https?\:\/\/)~', '$1', $menu);
	},
20
);

Note: this code uses an Anonymous function which requires PHP5.3+.
For older versions define this as a regular function and pass in its name as a string to add_filter()

Leave a Reply

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