KrisChase.com

Dynamically Add Parameters to the end of all wp_nav_menu()

Posted in Web Development on 06.10.2015 by @chasebadkids

I was working on a client who’s site I was working on where I was required to capture, and hold onto an affiliate tracking variable and value throughout the entire session of a user while browsing their website.  I was able to do this on specific buttons and links throughout the site with issue, but needed an easy way to accomplish this on main pieces of navigation in my header, sidebar, and footer.  To accomplish this, I used the following code:

add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );

function nav_items( $items, $menu, $args )
{
    if( is_admin() )
        return $items;

    $affiliateURL	=	track_affiliate_id();

    foreach( $items as $item )
    {
            $item->url .= $affiliateURL;

    }
    return $items;
}

In my example, I use a custom hook on top of ‘wp_get_nav_menu_items‘.   I then loop through all the menu items, get the urls and append my affiliate tracking code, in my case I use a function to determine the code to use, but you might be able to get away with a hardcoded approach like:

           $item->url .= '?affID=123';

This ended up being really helpful for myself!

 

 

Menu