Add Relative Links to WordPress Menus
by Guillermo A. FisherReally quick, here’s a function and corresponding hook that will loop through the links in your menu, figure 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;
}
}
Your Feedback Civil & constructive, please.
WP automatically prepends ‘http://’ to all custom links if they don’t allready have it. That’s why your code is not working for me.
It also destroys Umlauts in the current menu.
I’m usually able to remove the “http://” it prepends right from the Menus screen. Is it not letting you do that?