0

I'm using Foundation as a base and starter theme. 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)

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.

1

Please add this function into the functions.php file in your theme:

function add_attribute( $items, $args ) {
    $dom = new DOMDocument();
    $dom->loadHTML($items);
    $find = $dom->getElementsByTagName('li');

    foreach ($find as $item ) :
        $item->setAttribute('data-magellan-arrival','21');
    endforeach;

    return $dom->saveHTML();

}
add_filter('wp_nav_menu_items', 'add_attribute', 10, 2);
0

Actually you can Achieve something similar pretty easy,but also for me was not that easy find an answer. I needed a similar thing for fullpage.js navigation.So i achived like this : i used an alreday existing wordpress menu field that i was not using and i've used its value to fullfil my needs

function add_specific_menu_atts( $atts, $item, $args ) {

  $atts['data-menuanchor'] = $item->attr_title;


return $atts;

}

add_filter( 'nav_menu_link_attributes', 'add_specific_menu_atts', 10, 3 );

inspired by https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes

-2

This looks like this would get you pointed in the right direction.

  • Answers should not rely on external links. This is rather a comment than an answer. Please file an edit and post the relevant info inside your answer, keeping the link as reference only – Pieter Goosen Dec 19 '14 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.