I’m using wordpress and trying to add a data-attribute to just 1 main menu item. Specifically to a < li> element. I saw this link (how to add data attribute to a <li> element in wordpress nav menu) and I’m trying to narrow it down as it currently (and obviously targets every < li> item).
Here is my code that works just fine, as the correct behaviour is only triggered when the plugins’ associated class is also present (which is only in that 1 item). But I want to learn the more targeted approach.
function booking_menu_atts( $items, $args ) {
$dom = new DOMDocument();
$dom->loadHTML($items);
$find = $dom->getElementsByTagName('li');
foreach ($find as $item ) :
$item->setAttribute('data-agent','any');
$item->setAttribute('data-hide-panel','yes');
endforeach;
return $dom->saveHTML();}
add_filter('wp_nav_menu_items', 'booking_menu_atts', 10, 3);
This works, but how do I target a < li> menu item with either a specific class or a specific < li> menu id
Not sure if the language I’ve used it clear enough, but I want to improve, thanks in advance.
2
Answers
I guess you need to add specific behavior to some menu or submenu li.
This can be easily achieved by going to
To have this, go to screen options and enable css classes – Refer to attached images
Another option how to add data attribute to a <li> element in wordpress nav menu
Try to give your "li" some ID and instead of:
Try: