Add value to new attribute inside WordPress menu items

I have this code in my functions.php to add new attribute data-content=”” to all my items in the wordpress menu. The value of each data-content has to be different: I would like that each value corresponds to the inside text (in slug format) of the tag.

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

foreach ($find as $item ) :
$item->setAttribute(‘data-content’,”);

endforeach;

return $dom->saveHTML();

}
add_filter(‘wp_nav_menu_items’, ‘add_attribute’, 10, 2);

Here’s how the final result (in html) should be:

<ul>
<li class=”menu-item” data-content=”about”>
<a href=”#”>About</a>
</li>

<li class=”menu-item” data-content=”my-services”>
<a href=”#”>My services</a>
</li>

<li class=”menu-item” data-content=”contact-me”>
<a href=”#”>Contact me</a>
</li>
</ul>

For the moment the PHP code just creates the attribute but does not add any value inside data-content. I’m struggling to find the way how do it… Any help is much appreciated, thanks!

Read more here:: items” rel=nofollow>Add value to new attribute inside WordPress menu

  • items

  • Leave a Reply

    Your email address will not be published. Required fields are marked *