WordPress菜单,仅当当前页面是给定页面的后代时才显示


wordpress menu to display only if current page is descendant of a given page

我尝试开发的网站有两个根页面。作为导航结构:

  • A (级别 0(
    • A1 (级别 1(
      • A1.1 (级别 2(
      • A1.2 (级别 2(
    • A2 (级别 1(
      • A2.1 (级别 2(
      • A2.2 (级别 2(
  • B (0 级(
    • B1 (级别 1(
      • B1.1 (级别 2(
      • B1.2 (级别 2(
    • B2 (级别 1(
      • B2.1 (级别 2(
      • B2.2 (级别 2(

我需要的是,如果当前页面是 A 的后代,则显示 navA,同样,如果当前页面是 B 的后代,则仅显示 navB。

我尝试在wordpress后端创建两个单独的菜单,但只有mainNav会显示。菜单使用 wp_nav_menu($args( 生成为导航,如下所示。

echo "<div class='main_menu' data-selectname='".__('Select a page','avia_framework')."'>";
                        $avia_theme_location = 'avia';
                        $avia_menu_class = $avia_theme_location . '-menu';
                        $args = array(
                            'theme_location'    => $avia_theme_location,
                            'menu_id'           => $avia_menu_class,
                            'container_class'   => $avia_menu_class,
                            'fallback_cb'       => 'avia_fallback_menu',
                            'walker'            => new avia_responsive_mega_menu()
                        );
                        **wp_nav_menu($args);**
   echo "</div>";

有没有办法从后端实现此功能?否则,有什么建议可以走哪条路来做这件事吗?

谢谢!

function menu_set_parent( $sorted_menu_items, $args ) {
    $last_top = 0;
    foreach ( $sorted_menu_items as $key => $obj ) {
        // it is a top lv item?
        if ( 0 == $obj->menu_item_parent ) {
            // set the key of the parent
            $last_top = $key;
        } else {
            $sorted_menu_items[$last_top]->classes['parent'] = 'parent';
        }
    }
    return $sorted_menu_items;
}
add_filter( 'wp_nav_menu_objects', 'menu_set_parent', 10, 2 );

试试这个,它会将父类添加到父类。 将其添加到您的functions.php