TODO: To change the header's content go to Dr.Explain menu Options : Project Settings : HTML (CHM) Export : Setup HTML Template and Layout
×
Menu
Index

Hiển thị menus con theo menu kế cận

 
Hiển thị menus con theo menu kế cận.
Tạo menu hiển thị dựa trên parent menu hoặc mọi menu kế cận (sibling).
Hãy học đoạn code sau:
<?php
 
// add hook
add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );
 
// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {
  if ( isset( $args->sub_menu ) ) {
    $root_id = 0;
   
    // find the current menu item
    foreach ( $sorted_menu_items as $menu_item ) {
      if ( $menu_item->current ) {
        // set the root id based on whether the current menu item has a parent or not
        $root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
        break;
      }
    }
   
    // find the top level parent
    if ( ! isset( $args->direct_parent ) ) {
      $prev_root_id = $root_id;
      while ( $prev_root_id != 0 ) {
        foreach ( $sorted_menu_items as $menu_item ) {
          if ( $menu_item->ID == $prev_root_id ) {
            $prev_root_id = $menu_item->menu_item_parent;
            // don't set the root_id to 0 if we've reached the top of the menu
            if ( $prev_root_id != 0 ) $root_id = $menu_item->menu_item_parent;
            break;
          }
        }
      }
    }
 
    $menu_item_parents = array();
    foreach ( $sorted_menu_items as $key => $item ) {
      // init menu_item_parents
      if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;
 
      if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
        // part of sub-tree: keep!
        $menu_item_parents[] = $item->ID;
      } else if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) {
        // not part of sub-tree: away with it!
        unset( $sorted_menu_items[$key] );
      }
    }
   
    return $sorted_menu_items;
  } else {
    return $sorted_menu_items;
  }
}
 
Ví dụ bạn tưởng tượng menu có nội dung như trong hình:
 
Sử dụng:
Quy ước: Mục bôi mầu chữ vàng là item được chọn.
 
Bật tính năng hiển thị submenu theo trang menu được chọn bạn khai báo thêm trường tham số ‘sub_menu’=>true.
<?php
wp_nav_menu( array(
  'theme_location' => 'primary',
  'sub_menu' => true
) );
 
- Bỏ qua menu mẹ:
thêm giá trị ‘direct_parent’=>true.
wp_nav_menu( array(
  'theme_location' => 'primary',
  'sub_menu' => true,
  'direct_parent' => true
) );
Kết quả:
 
- Hiển thị menu mẹ và toàn bộ menu cùng level với menu mẹ ở up-level 1:
Thêm thuộc tính ‘show_parent’=>true.
Kết quả:
 
- Hiển thị các submenu và menu mẹ của chúng:
wp_nav_menu(array(
   'theme_location' => 'primary',
   'sub_menu' => true,
   'direct_parent' => true,
   'show_parent' => true
));
Kết quả:
Made with help of Dr.Explain

Unregistered version