Add Relative Links to WordPress Menus

by Guillermo A. Fisher

Really quick, here’s a func­tion and cor­re­spond­ing hook that will loop through the links in your menu, fig­ure out which ones don’t begin with a “/” or “http” and prepend them with your site’s URL and a “/”:

add_filter( 'wp_nav_menu_items', 'gria_fix_relative_links', 10, 1 );
if ( ! function_exists( 'gria_fix_relative_links' ) ) {
	function gria_fix_relative_links( $menu ) {
	    $doc = new DOMDocument();
	    $doc->loadHTML( $menu );
	    $list_items = $doc->getElementsByTagName( 'a' );
	    for ($i = 0, $max = $list_items->length; $i < $max; $i++) {
	        $item = $list_items->item( $i );
		$link = $item->getAttribute( 'href' );
		if ($link{0} != '/' && substr($link, 0, 4) != 'http') {
			$link = site_url() . '/' . $link;
	        	$item->setAttribute( 'href', $link );
		}
	    }
	    $output = str_ireplace( array( '<body>', '</body>' ), '', $doc->saveXML( $doc->getElementsByTagName( 'body' )->item( 0 ) ) );
	    return $output;
	}
}

Tagged as the following: .

Your Feedback Civil & constructive, please.

3 Responses to “Add Relative Links to WordPress Menus”

  1. Jan says:

    WP auto­mat­i­cally prepends ‘http://’ to all cus­tom links if they don’t all­ready have it. That’s why your code is not work­ing for me.

  2. Jan says:

    It also destroys Umlauts in the cur­rent menu.

  3. I’m usu­ally able to remove the “http://” it prepends right from the Menus screen. Is it not let­ting you do that?

Leave a Reply