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


Add sequential numbering for wordpress menu (only depth 0)

我正试图在wordpress中的菜单中的每个链接后面添加顺序编号。它们应该在标签中并作为文本。这样我就可以设计风格了。

试过下面的这个,但由于它是CSS,我无法为这些数字设置样式。

如何为wordpress菜单添加顺序编号

我对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

知道如何只给父母编号吗?

(如果解决方案是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>';

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