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ị submenu của menu mẹ

 
Hiển thị submenu của menu mẹ:
Bạn muốn chỉ hiển thị submenu của một menu như hình dưới.
 
Bằng cách truyền tham số theo định nghĩa của bạn vào hàm wp_nav_menu, chúng ta sẽ chỉ hiển thị những submenu dưới “About Us”.
// Usage:
 
$args = array(
    'menu'    => 'Menu Name',
    'submenu' => 'About Us',
);
 
wp_nav_menu( $args );
 
Sử dụng hook 'wp_nav_menu_objects' lọc items bạn muốn lấy.  Copy đoạn code sau vào functions.php
add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 );
 
function submenu_limit( $items, $args ) {
 
    if ( empty($args->submenu) )
        return $items;
 
    $parent_id = array_pop( wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' ) );
    $children  = submenu_get_children_ids( $parent_id, $items );
 
    foreach ( $items as $key => $item ) {
 
        if ( ! in_array( $item->ID, $children ) )
            unset($items[$key]);
    }
 
    return $items;
}
 
function submenu_get_children_ids( $id, $items ) {
 
    $ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'and', 'ID' );
 
    foreach ( $ids as $id ) {
 
        $ids = array_merge( $ids, submenu_get_children_ids( $id, $items ) );
    }
 
    return $ids;
}
Giải thích:
Hàm wp_filter_object_list dùng để lấy bất kỳ thành phần nào có trong mảng, cấu trúc:
wp_filter_object_list( $list, $args, $operator, $field );
 
Trong đó:
 
 
Lưu ý:
+ Để lấy toàn bộ submenu theo đa tầng, chúng ta tạo hàm lặp submenu_get_children_ids, những items con phát hiện của menu 'About us' được gộp vào biến $ids.
 
 
Made with help of Dr.Explain

Unregistered version