【问题标题】:Display menu label twice in wp_nav_walker menu WordPress在 wp_nav_walker 菜单 WordPress 中显示菜单标签两次
【发布时间】:2020-10-14 23:22:23
【问题描述】:

我想在 WordPress 菜单中有两个 <span> 标签,如下面的代码所示:

<ul>
    <li><a href="#!"><span>Home</span><span>Home</span></a></li>
    <li><a href="#!"><span>About</span><span>About</span></a></li>
    <li><a href="#!"><span>Contact</span><span>Contact</span></a></li>
</ul>

【问题讨论】:

    标签: wordpress wp-nav-walker


    【解决方案1】:

    首先,您可以使用 Walker。 创建新类,您需要一个名为 start_el 的函数(您可以在 wp-includes/class-walker-nav-menu.php 中找到它)。最简单的方法就是复制它。您需要更改 $item_output

    class Your_Walker extends Walker_Nav_Menu {
    public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
    // Code here
            $item_output  = $args->before;
            $item_output .= '<a' . $attributes . '>';
            $item_output .= $args->link_before . $title . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;
    }
    }
    

    您可以提及锚标记及其内部的 $title(链接标题)。您可以将 $title 包装到 span 中并将其加倍,如下所示:

    class Your_Walker extends Walker_Nav_Menu {
    public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
    // Code here
            $item_output  = $args->before;
            $item_output .= '<a' . $attributes . '>';
            $item_output .= $args->link_before . '<span>' . $title . '</span>' . $args->link_after;
            $item_output .= $args->link_before . '<span>' . $title . '</span>' . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;
    }
    }
    

    注意 $args->link_before/after 可以通过调用 wp_nav_menu 来使用,不需要额外添加 span(我会在下面解释)。

    第二种方式:有点棘手但更简单,它会起作用。 像这样调用 wp_nav_menu:

    wp_nav_menu(array(
        'theme_location'    => 'your_location',
        'link_before'       => '<span>', // This will wrap your title
        'link_after'        => '</span>',
     ));
    

    在你的functions.php中

    function add_double_span_to_menu( $item_output, $item, $depth, $args ){
        
        // replace closing '</a>' with '<span>Links Title</span></a>'
        $replace = $args->link_before . $item->title . $args->link_after . '</a>';
        $item_output = str_replace('</a>', $replace, $item_output);
    
        return $item_output;
    }
    add_filter('walker_nav_menu_start_el', 'add_double_span_to_menu', 10, 4);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多