I’m trying to find a way to change the href of a nav menu page link from the parent theme’s default, which goes to its relative page, to another url. For example, I have a menu link “Our Philosophy” that links to the “Our Philosophy” page, but desire for it to go to timecube.com (rip).
It seems perhaps using a filter (nav_menu_link_attributes?) might be a simple way to achieve this. However, I’ve been unable to wrap my head around using filters to get this working.
I would think I’d need something like:
function change_nav_url( $atts, $item ) {
// modify $item href?
}
add_filter ( 'nav_menu_link_attributes', 'change_nav_url');
My initial thought would be I would need to call this function somewhere–with apply_filters()
maybe–and would need to get $atts
and $item
manually from somewhere and pass them into it. But that creates the problem–how do I get them, and from what (a menu object?). And thinking about it, if I do have to retrieve them manually, I don’t really see the point of using a filter v. a plain function, so maybe I have to put it into the plugin folder and it’ll automatically give me access to $atts
or something? (That didn’t work). Either way, I’m clearly not understanding something.
I appreciate any help bringing light to my newb ignorance.
2 Answers
You are on right track, with few minor kinks.
- You need to modify
$atts
and return it. Any arguments after the first one are provided for information and should not be changed. - You need to tell
add_filter()
that you expect more than one argument.
The example with some debug code would be along the lines of:
add_filter( 'nav_menu_link_attributes', function ( $atts, $item, $args, $depth ) {
var_dump( $atts, $item ); // a lot of stuff we can use
var_dump( $atts['href'] ); // string(36) "http://dev.rarst.net/our-philosophy/"
var_dump( get_the_title( $item->object_id ) ); // string(14) "Our Philosophy", note $item itself is NOT a page
if ( get_the_title( $item->object_id ) === 'Our Philosophy' ) { // for example
$atts['href'] = 'https://example.com/';
}
return $atts;
}, 10, 4 ); // 4 so we get all arguments