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();
$find = $dom->getElementsByTagName(‘li’);

foreach ($find as $item ) :


return $dom->saveHTML();

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

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

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

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

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

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 *