WordPress filter to hook into menu <li> items and add a custom attribute

I have a WordPress template I’m trying to build and I can’t seem to figure out how to hook into the menu that WordPress outputs and add a custom attribute to that menu’s <li> tags. The current menu outputs like this:

<ul id="menu-main-menu-1" class="top-bar-menu right">
<li class="divider"></li>
<li class="menu-item "><a href="#home">Home</a></li>
<li class="divider"></li>
<li class="menu-item"><a href="#about">About</a></li>
<li class="divider"></li>
<li class="menu-item"><a href="#work">My Work</a></li>
<li class="divider"></li>
<li class="menu-item"><a href="#contact">Contact</a></li>
</ul>

(Those links are just there for sample)

Read More

I need WordPress to automatically add the following attribute to the <li> tags: data-magellan-arrival="[target]".

[Target] needs to automatically be populated by the page_ID that the menu item corresponds to. So for example, let’s say that first’s <li><a href="">[PAGE]</a></li> link is Home and Home’s page_ID is “21” (example). I would need data-magellan-arrival="[target]" inside of <li> to be set to data-magellan-arrival="21".

So it would look like: <li class="menu-item" data-magellan-arrival="21"><a href="">[PAGE]</a></li>

I’ll be honest with you, I’m not that great at PHP just yet and WordPress filters/hooks much less. Hoping someone can point me in the right direction or show me how to do it.

Thanks!

Related posts

Leave a Reply

1 comment

  1. This should work:

    //add to functions.php
    add_filter('nav_menu_link_attributes', 'magellanlinkfilter');
    function magellanlinkfilter($val)
    {
        $postid = url_to_postid( $val['href'] );
        $val['data-magellan-arrival'] = $postid;
        return $val;
    }
    

    Here’s the complete list of hooks: http://adambrown.info/p/wp_hooks