【问题标题】:Add class to Wordpress Menu将类添加到 Wordpress 菜单
【发布时间】:2019-04-06 10:11:07
【问题描述】:

我为每个 Wordpress 菜单项添加了类,但它们没有出现在代码中。

我的菜单:

<?php $wp_custom_nav = array(
        'theme_location'  => 'primary',
    'container'       => 'nav',
        'container_class' => 'nav',
    'echo'            => false,
    'fallback_cb'     => false,
    'items_wrap'      => '%3$s',
    'depth'           => 0
    );
    echo strip_tags(wp_nav_menu( $wp_custom_nav ), '<nav><a>');
    ?>

我的function.php包含

    register_nav_menus( array(
        'primary' => esc_html__( 'Primary', 'yewtree' ),
    ) );

所以我有

<nav>
  <a></a>
  <a></a>
  ...
</nav>

但是没有我在 Wordpress 管理菜单中添加的任何类。这是为什么呢?

【问题讨论】:

标签: php wordpress nav


【解决方案1】:

wp_nav_menu 默认使用Walker_Nav_Menu。这是负责打印类的部分:

    /**
     * Filters the CSS classes applied to a menu item's list item element.
     *
     * @since 3.0.0
     * @since 4.1.0 The `$depth` parameter was added.
     *
     * @param string[] $classes Array of the CSS classes that are applied to the menu item's `<li>` element.
     * @param WP_Post  $item    The current menu item.
     * @param stdClass $args    An object of wp_nav_menu() arguments.
     * @param int      $depth   Depth of menu item. Used for padding.
     */
    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

    /**
     * Filters the ID applied to a menu item's list item element.
     *
     * @since 3.0.1
     * @since 4.1.0 The `$depth` parameter was added.
     *
     * @param string   $menu_id The ID that is applied to the menu item's `<li>` element.
     * @param WP_Post  $item    The current menu item.
     * @param stdClass $args    An object of wp_nav_menu() arguments.
     * @param int      $depth   Depth of menu item. Used for padding.
     */
    $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth );
    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

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

因此,如您所见,这些类应用于&lt;li&gt; 标签而不是&lt;a&gt; 标签。

所以它们被应用了,但是……你这样做:

echo strip_tags(wp_nav_menu( $wp_custom_nav ), '<nav><a>');

所以你去除了除&lt;nav&gt; 和&lt;a&gt; 之外的所有标签——所以&lt;li&gt; 标签被去除了(类也被去除了)。

【讨论】:

    猜你喜欢
    • 2014-01-12
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多