Using filters to change href of nav menu page link

You are on right track, with few minor kinks.

  1. You need to modify $atts and return it. Any arguments after the first one are provided for information and should not be changed.
  2. 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

Leave a Comment