First of all –
I tryed to make this work to changing
nav-menu-template.php
Never edit a core file! This is always a bad idea. At best, you will lose your changes when core updates.
To do this, you can use the nav_menu_link_attributes
filter to modify the href
attribute. This filter will be applied to each menu item individually.
In this example, we hook a function to the filter and str_replace
the home_url
with an empty string. So if our home URL is http://example.com
, and the URL is http://example.com/something
, the new value of href
will be /something
. We then return
the modified attributes.
function wpdev_remove_home_url_from_menu_items( $atts, $item, $args ) {
$atts['href'] = str_replace( home_url(), '', $atts['href'] );
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'wpdev_remove_home_url_from_menu_items', 10, 3 );
We only used the $atts
argument in this case, but you’ll note that there are two other arguments- the menu item object and menu args, in case you need to do any checking of specific menu items or menus in order to decide how to modify the attributes.
You can also use this filter to add additional attributes, like data
, rel
, and target
.