Add data attribute to wp_nav_menu
Asked Answered
B

1

5

I have the following code:

$nav_menu_args = array('fallback_cb' => '','menu' => 'menu', 'menu_class' => 'menu_class');

$x = wp_nav_menu( apply_filters( 'widget_nav_menu_args', $nav_menu_args, 'menu', $args ) );

$pattern = '#<ul([^>]*)>#i'; 

$replacement = '<ul$1 data-attr="abc">';  // this is a wrong

echo preg_replace( $pattern, $replacement, $x );

I am trying to add a data-attr to ul by altering the pattern, and without making changes through Walker_Nav_Menu.

What I want to do is to have a list like this:

<ul class="menu_class" data-attr="abc">
  <li><li>
  <li>
    <ul>
      <li></li>
    </ul>
  <li>
</ul>

But I get also a data-attr on my inner ul like this.

<ul class="menu_class" data-attr="abc">
  <li><li>
  <li>
    <ul data-attr="abc">
      <li></li>
    </ul>
  <li>
</ul>

What am I missing?

Bra answered 4/6, 2015 at 16:41 Comment(4)
Is the problem that it also adds a data-attr to the inner ul ?Italian
Yes. I want to add data-attr to the ul.Bra
Thank you for your help. I managed to solve this issue through $nav_menu_args.Bra
You mean like what I just edited in my answer? Otherwise answer your own question with the solution and mark it as correct so other people can find the same solution.Italian
I
11

You could add the number of objects you want to replace so it only takes the first ul.

echo preg_replace( $pattern, $replacement, $x, 1 ); // 1 at the end to replace only the first occurence

Or just change the items_wrap key of the wp_nav_menu.

$nav_menu_args = array('fallback_cb' => '','menu' => 'menu', 'items_wrap' => '<ul class="menu_class" data-attr="abc">%3$s</ul>');
Italian answered 4/6, 2015 at 16:53 Comment(1)
'Had completely forgot about items_wrap - awesome!Irate

© 2022 - 2024 — McMap. All rights reserved.