Ad

Timber Library Doesn't Support "nav_menu_link_attributes" Filter?

- 1 answer

I'm trying to use nav_menu_link_attributes to append something else to the "href" of a single menu item. Seems to me Timber library doesn't supports this filter?

My code works as expected with twentytwenty, however it does not takes effect to change the attribute when I switch the theme to Gesso-WP, that depends on Timber library. Also I cannot find any other filter than "nav_menu_css_class" inside the MenuItem class https://github.com/timber/timber/blob/master/lib/MenuItem.php

function filter_menu_item_href( $atts ) {
    if ( strpos( $atts['href'], 'site/SPageNavigator/my_account.html' ) !== false ) {
        $atts['href'] .= '?NEXTURL=' . home_url();
    }

    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'filter_menu_item_href' );

What are the filtering options on Timber to change this single attribute value?

Ad

Answer

I finally handled this by using "wp_nav_menu_objects". This filter is present in the Menu class from the Timber library plugin: https://github.com/timber/timber/blob/master/lib/Menu.php

function filter_menu_item_href( $menu ) {
    foreach ( $menu as $item ) {
        if ( strpos( $item->url, 'site/SPageNavigator/my_account.html' ) !== false ) {
            $item->url .= '?NEXTURL=' . home_url();
        }
    }

    return $menu;
}
add_filter( 'wp_nav_menu_objects', 'filter_menu_item_href' );
Ad
source: stackoverflow.com
Ad