【问题标题】:Add sequential numbering for wordpress menu (only depth 0)为 wordpress 菜单添加顺序编号(仅深度 0)
【发布时间】:2015-04-22 00:05:08
【问题描述】:

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

在下面尝试了这个,但由于它的 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

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

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

【问题讨论】:

    标签: php wordpress menu nav


    【解决方案1】:

    如果您只想对顶级菜单进行编号,则只需测试深度即可。

    变化:

        $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>';
    

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

    【讨论】:

    • 这只是从子级别中删除了数字。但只改变了输出。由于它仍然使用来自 $item->menu_order 的编号,它仍然给我类似 01、02、05、06、09 的东西。我需要一个替代方法来使用 menu_order 来为我的列表编号。
    • 我添加到答案中。
    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2018-01-10
    • 2012-02-12
    • 2015-10-13
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多