wp-bootstrap/wp-bootstrap-navwalker

Usage question - change inner ul to div and li to a

pdmwu opened this issue · 1 comments

pdmwu commented

I have the challenge that I need to change

ul.dropdown-menu
li itemscope=...

to

div.dropdown-menu
a.dropdown-item bg-transparent

and don't know how to do it. Does someone know?

PS: Basically I want to create a basic Bootstrap markup https://getbootstrap.com/docs/4.0/components/navbar/ as overall project requirements need the markup to be exactly like this (no css tweaking).

screen

Using ul > li > a is not CSS tweaking. It is perfectly valid Bootstrap markup and imho semantically correct. Bootstrap was using ul > li > a in v2, v3 and is switching back to it in v5. The styling is done by the Bootstrap classes. It doesn't matter whether you add the class to a <div> or <ul>. In the docs for the navbar Bootstrap itself states

And because we use classes for our navs, you can avoid the list-based approach entirely if you like.

Which holds the other way round as well.

If you really really need to do that, just make a couple of changes to the walker class.

Switch from <ul> to <div> here:

$output .= "{$n}{$indent}<ul$class_names $labelledby>{$n}";

Remove the <li> here:

$output .= $indent . '<li ' . $id . $class_names . '>';

and move the $id and $class_namesfrom the <li> to the <a> here:

$item_output .= '<a' . $attributes . '>';

Then you have to add the following methods:

 public function end_lvl( &$output, $depth = 0, $args = null ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent  = str_repeat( $t, $depth );
        $output .= "$indent</div>{$n}";
}

public function end_el( &$output, $item, $depth = 0, $args = null ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $output .= "{$n}";
}

Maybe I missed something (eg adjusting the $t to correct the indentation), but in general that's it.

As it's been more than year now since you have opened the issue, I assume that's not longer relevant to you. If it is and you have further questions, please feel free to re-open the issue.