将菜单<a>标记替换为<按钮>标记

时间:2021-12-01 作者:Sam

我有以下菜单设置通过标题。php:

<?php
wp_nav_menu(
    array(
        \'container\' => false,
        \'theme_location\' => \'primary\',
        \'items_wrap\' => \'<ul class="header__nav-items">%3$s</ul>\',
    )
);
这将在前端显示以下内容:

<ul class="header__nav-items">
    <li class="header__nav-item menu-item-has-children">
        <a href="#" class="header__nav-anchor">Parent</a><!-- I\'d like to replace this <a> tag with a <button> tag. -->
        <ul class="header__sub-menu">
            <li class="header__nav-item"><a href="child-page-one" class="header__nav-anchor">Child Page One</a></li>
            <li class="header__nav-item"><a href="child-page-two" class="header__nav-anchor">Child Page Two</a></li>
            <li class="header__nav-item"><a href="child-page-three" class="header__nav-anchor">Child Page Three</a></li>
            <li class="header__nav-item"><a href="child-page-four" class="header__nav-anchor">Child Page Four</a></li>
        </ul>
    </li>
</ul>
我实现了一个自定义字段(with ACF) 以便管理员可以通过WP admin选择菜单项是否为下拉菜单。

ACF WP menu radio button

然后,我有以下via功能。php:

<?php
function edit_menu_item( $items, $args ) {
    foreach( $items as $item ) {
        if ( get_field( \'dropdown\', $item) == \'yes\' ) {
            echo \'<button class="nav__button>\'.$item->title.\'</button>\';
        }
    }
    return $items;  
}
add_filter(\'wp_nav_menu_objects\', \'edit_menu_item\', 10, 2);
我希望上面的内容在前端输出以下内容:

<ul class="header__nav-items">
    <li class="header__nav-item menu-item-has-children">
        <button class="header__button">Parent</button>
        <ul class="header__sub-menu">
            <li class="header__nav-item"><a href="child-page-one" class="header__nav-anchor">Child Page One</a></li>
            <li class="header__nav-item"><a href="child-page-two" class="header__nav-anchor">Child Page Two</a></li>
            <li class="header__nav-item"><a href="child-page-three" class="header__nav-anchor">Child Page Three</a></li>
            <li class="header__nav-item"><a href="child-page-four" class="header__nav-anchor">Child Page Four</a></li>
        </ul>
    </li>
</ul>
相反,按钮被放置在菜单之外,如下所示:

<button class="header__button">Parent</button><!-- Button appearing here -->
<ul class="header__nav-items">
<!-- Rest of the markup -->
我做错了什么?

1 个回复
最合适的回答,由SO网友:Sam 整理而成

看起来上面这些都可以通过walker_nav_menu_start_el 过滤器(see reference).

<?php
function edit_menu_item($item_output, $item) {
    if ( get_field( \'dropdown\', $item) == \'yes\' ) { 
        return \'<button>\'.$item->title.\'</button>\';
    }
    return $item_output;
}
add_filter(\'walker_nav_menu_start_el\',\'edit_menu_item\', 10, 2);
贷记至@s_ha_dum via this answer.

相关推荐

无法将设置添加到“NAV_MENUS”定制器面板

我试图在自定义程序的“菜单”面板中添加一个复选框,但由于某些原因,它没有显示出来。如果我尝试将其从“nav\\u菜单”更改为“title\\u tagline”或“colors”,复选框会显示得很好。是什么阻止它显示在“菜单”面板上?// add custom options to the Customizer function nssra_customizer_options($wp_customize) { // add \"menu primary flex\" checkb