skip to Main Content

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


  1. I guess you need to add specific behavior to some menu or submenu li.

    This can be easily achieved by going to

    WP backend -> menus -> click on an item and below label you will have CSS Classes (optional) – here you can add class and write its respective css.

    To have this, go to screen options and enable css classes – Refer to attached images

    enter image description here

    enter image description here

    Another option how to add data attribute to a <li> element in wordpress nav menu

    Login or Signup to reply.
  2. Try to give your "li" some ID and instead of:

    $find = $dom->getElementsByTagName('li');   
    

    Try:

    $find = $dom->getElementsById('#youridname'); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search