为 wordpress 菜单添加顺序编号(仅限深度 0)

Add sequential numbering for wordpress menu (only depth 0)

我试图在 wordpress 的菜单中的每个 link 之后添加顺序编号。它们应该在标签中并作为文本。所以我可以设计风格。

尝试了下面这个,但因为它 CSS,我无法设置这些数字的样式。

How to add sequential numbering for wordpress menu

我对 JS 一无所知。所以我在 navwalker.php

中做了这个
            if(! empty( $item->attr_title )){
            $item_output .= '<a'. $attributes .'><i class="' . esc_attr( $item->attr_title ) . '"></i>&nbsp;';
        } else {
            $item_output .= '<a'. $attributes .'>';
        }
        
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= ($args->has_children && $depth == 0) ? ' <span class="caret"></span></a>' : '</a>';
        $item_output .= $args->after . '<span class="navnum">' . str_pad(esc_attr( $item->menu_order ), 2, "0", STR_PAD_LEFT) . '.</span>';

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
}

并且有效。 唯一的问题是它计算可折叠菜单中的子菜单(子菜单),所以它创建了这样的东西:

01
03
04
07
08

知道如何只编号 parents 吗?

(如果解决方案是JS,如果你解释得非常简单,我将不胜感激)

如果您要做的只是对顶级菜单进行编号,您可以只测试深度。

变化:

    $item_output .= $args->after . '<span class="navnum">' . str_pad(esc_attr( $item->menu_order ), 2, "0", STR_PAD_LEFT) . '.</span>';

至:

    $item_output .= $args->after . ($depth == 0 ? '<span class="navnum">' . str_pad(esc_attr( $item->menu_order ), 2, "0", STR_PAD_LEFT) : '') . '.</span>';

要按顺序对菜单项进行编号,请在新关卡开始时设置您自己的全局计数器:

public function start_lvl( &$output, $depth = 0, $args = array() ) {
    if (!isset($_GLOBALS['menu_counter'])) {
        $GLOBALS['menu_counter'] = array();
    }
    $GLOBALS['menu_counter'][$depth] = 0;
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"sub-menu\">\n";
}

然后在start_el:

public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
    global $menu_counter;
    ....

并且在您在问题中给出的代码示例中:

$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= ($args->has_children && $depth == 0) ? ' <span class="caret"></span></a>' : '</a>';
$item_output .= $args->after . '<span class="navnum">' . str_pad(++$menu_order[$depth], 2, "0", STR_PAD_LEFT) . '.</span>';

这是在设置新级别时设置一个从零开始的变量。然后,对于该级别的每个项目,它将向该变量加一并将结果用作菜单项的编号。