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ị menu động

Bài tập: Tạo 2 menu, một menu sẽ hiển thị cho logged user và menu kia cho người viếng thăm đọc nội dung thông thường.
add_action( 'after_setup_theme', 'twentytwelve_setup' );
function
register_nav_menus( array(
  'logged-in'  => __( 'Logged-in Menu Area',  'yourtheme' ),
  'visitor' => __( 'Visitor Menu Area', 'yourtheme' ),
));
 
Cách 1: Đơn giản chúng ta sẽ kiểm tra nếu tài khoản người dùng tồn tại thì gọi menu 'logged-in', còn không hiển thị menu còn lại.
if (is_user_logged_in()){
  wp_nav_menu( array(
    'menu'            => 'Logged In Menu',
    'container_class' => 'logged-in-menu',
    'theme_location'  => 'logged-in'
  ));
} else {
  wp_nav_menu( array(
    'menu'            => 'Visitor Menu',
    'container_class' => 'visitor-menu',
    'theme_location'  => 'visitor'
  ));
};
 
Cách 2: Linh hoạt hơn, bằng cách sử dụng hook 'wp_nav_menu_args' căn cứ vào thông số menu hiện tại, nếu tồn tại tên menu/theme location và tồn tại phiên làm việc user chúng ta sẽ cho hiển thị menu tương ứng.
// depending on the current menu arguments, if there exists a _loggedin theme location we're using that when user is logged in.
add_filter('wp_nav_menu_args', 'serve_different_menu');
function serve_different_menu($content){
 
    $loggedin_theme_location = $content['theme_location'] . '_dmlu_loggedin';
    $active_menu_locations = get_nav_menu_locations();
   
    if ( is_user_logged_in() && !empty($content['theme_location']) && $active_menu_locations[$loggedin_theme_location] != 0 && array_key_exists($loggedin_theme_location, $active_menu_locations) ) {
        $content['theme_location'] = $content['theme_location'] . '_dmlu_loggedin';
        return $content;
    } else {
        return $content;
    }
}
Made with help of Dr.Explain

Unregistered version