Reputation: 734
i'm trying to give an attribute for each item in my wordpress navbar.
what i have now is this:
<ul id="menu-nav-bar" class="menu">
<li><a href="#text">text</a></li>
<li><a href="#carousel">carousel</a></li>
</ul>
and this is what i'm trying to achive:
<ul id="menu-nav-bar" class="menu">
<li><a data-menuanchor="text" href="#text">text</a></li>
<li><a data-menuanchor="text" href="#carousel">carousel</a></li>
</ul>
i used a custom walker to create the menu, so would be cool if i can use a function to get the text inside the < a > tags (which is text and carousel in this case) and make it "print" in data-menuanchor attribute like the example above.
this is a preatty similar case, but it's not working for me:
https://wordpress.stackexchange.com/questions/165294/how-to-add-scroll-ids-to-wordpress-menu-anchors
Upvotes: 0
Views: 197
Reputation: 1
To get a dynamic alternative for 'text' I use
$atts['data-menuanchor'] = sanitize_title($item->title);
worked for me. But I have another Problem: with the attribute "data-menuanchor" is added to the link <a>
. But it should be added to the matching <li>
.
Any Help for that?
Upvotes: 0
Reputation: 31
function my_nav_menu_attribs( $atts, $item, $args )
{
$items = wp_get_nav_menu_items( 'Main', $args );
foreach($items as $my_item)
{
// The ID of the target menu item
$menu_target = $my_item->ID;
// inspect $item
if ($item->ID == $menu_target) {
$atts['data-menuanchor'] = 'text';
}
}
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'my_nav_menu_attribs', 10, 3 );
In above wp_get_nav_menu_items( 'Main',$args)
function call please replace "Main" with your menu name
Upvotes: 1
Reputation: 31
If you dont find plugin useful try this one Filter this, targetting a specific menu id is easy:
Add the following to your functions.php
file.
add_filter( 'nav_menu_link_attributes', 'my_nav_menu_attribs', 10, 3 );
function my_nav_menu_attribs( $atts, $item, $args )
{
// The ID of the target menu item
$menu_target = 365;
// inspect $item
if ($item->ID == $menu_target) {
$atts['data-menuanchor'] = 'text';
}
return $atts;
}
Upvotes: 1
Reputation: 31
Just Try out following plugin:
https://wordpress.org/plugins/sweet-custom-menu/
Upvotes: 0