在 WordPress 子菜单项后添加 div [英] Adding div after WordPress submenu items

查看:39
本文介绍了在 WordPress 子菜单项后添加 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 WordPress 菜单中的任何子菜单项之后添加一个 div.我正在处理functions.php文件中的以下代码:

add_filter( 'nav_menu_link_attributes', 'SubMenuCheck', 10, 3 );function SubMenuCheck( $atts, $item, $args ) {if (in_array('menu-item-has-children', $item->classes)) {$args->after = '

+

';}返回 $atts;}

上面的代码添加了新的 div <div class="click">+</div> 但在第一个菜单项"之后继续将其应用于所有父项和子项-有孩子的班级:

有人知道为什么会重复吗?...我只希望 div 显示具有 menu-item-has-children 类的项目.

谢谢

解决方案

我不使用 nav_menu_link_attributes 过滤器,添加一个按钮(语义上是正确的)作为切换的热点孩子们,我使用以下内容:

function prefix_add_button_after_menu_item_children( $item_output, $item, $depth, $args ) {if ( $args->theme_location == 'primary' ) {if ( in_array( 'menu-item-has-children', $item->classes ) || in_array( 'page_item_has_children', $item->classes ) ) {$item_output = str_replace( $args->link_after .'</a>', $args->link_after .'</a><button class="sub-menu-toggle" aria-expanded="false" aria-pressed="false"><span class="screen-reader-text">' . _x( 'open dropdown menu', 'verb: open the menu', 'text-domain') .'</span></button>', $item_output );}}返回 $item_output;}add_filter('walker_nav_menu_start_el', 'prefix_add_button_after_menu_item_children', 10, 4);

I am trying to add a div after any submenu items in a WordPress menu. I am working on the following code in the functions.php file:

add_filter( 'nav_menu_link_attributes', 'SubMenuCheck', 10, 3 );
function SubMenuCheck( $atts, $item, $args ) {
  if (in_array('menu-item-has-children', $item->classes)) {
    $args->after = '<div class="click">+</div>';
  }
  return $atts;
}

The code above adds the new div <div class="click">+</div>but keeps applying it to all parent and child items after the first 'menu-item-has-children' class:

Does anyone know why this is repeating?... I only want the div to display for items with the menu-item-has-children class.

Thanks

解决方案

I don't use the nav_menu_link_attributes filter, to add a button (which is semantically correct) to be the hot spot for toggling the children, I use the following:

function prefix_add_button_after_menu_item_children( $item_output, $item, $depth, $args ) {

    if ( $args->theme_location == 'primary' ) {

        if ( in_array( 'menu-item-has-children', $item->classes ) || in_array( 'page_item_has_children', $item->classes ) ) {
            $item_output = str_replace( $args->link_after . '</a>', $args->link_after . '</a><button class="sub-menu-toggle" aria-expanded="false" aria-pressed="false"><span class="screen-reader-text">' . _x( 'open dropdown menu', 'verb: open the menu', 'text-domain' ) . '</span></button>', $item_output );
        }
    }

    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'prefix_add_button_after_menu_item_children', 10, 4 );

这篇关于在 WordPress 子菜单项后添加 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆