-
-
Save prestarocket/fb63ecdb26f56d81ad40ef31ee33e934 to your computer and use it in GitHub Desktop.
Преобразует дефолтное меню WordPress в меню на основе методологии БЭМ с помощью только фильтров меню
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'after_setup_theme', function () { | |
register_nav_menus( [ | |
'header-menu' => 'Верхняя область', | |
'footer-menu' => 'Нижняя область', | |
] ); | |
} ); | |
// Изменяет основные параметры меню | |
add_filter( 'wp_nav_menu_args', 'filter_wp_menu_args' ); | |
function filter_wp_menu_args( $args ) { | |
if ( $args['theme_location'] === 'header-menu' ) { | |
$args['container'] = false; | |
$args['items_wrap'] = '<ul class="%2$s">%3$s</ul>'; | |
$args['menu_class'] = 'menu menu--main menu-horizontal'; | |
} | |
return $args; | |
} | |
// Изменяем атрибут id у тега li | |
add_filter( 'nav_menu_item_id', 'filter_menu_item_css_id', 10, 4 ); | |
function filter_menu_item_css_id( $menu_id, $item, $args, $depth ) { | |
return $args->theme_location === 'header-menu' ? '' : $menu_id; | |
} | |
// Изменяем атрибут class у тега li | |
add_filter( 'nav_menu_css_class', 'filter_nav_menu_css_classes', 10, 4 ); | |
function filter_nav_menu_css_classes( $classes, $item, $args, $depth ) { | |
if ( $args->theme_location === 'header-menu' ) { | |
$classes = [ | |
'menu-node', | |
'menu-node--main_lvl_' . ( $depth + 1 ) | |
]; | |
if ( $item->current ) { | |
$classes[] = 'menu-node--active'; | |
} | |
} | |
return $classes; | |
} | |
// Изменяет класс у вложенного ul | |
add_filter( 'nav_menu_submenu_css_class', 'filter_nav_menu_submenu_css_class', 10, 3 ); | |
function filter_nav_menu_submenu_css_class( $classes, $args, $depth ) { | |
if ( $args->theme_location === 'header-menu' ) { | |
$classes = [ | |
'menu', | |
'menu--dropdown', | |
'menu--vertical' | |
]; | |
} | |
return $classes; | |
} | |
// ДОбавляем классы ссылкам | |
add_filter( 'nav_menu_link_attributes', 'filter_nav_menu_link_attributes', 10, 4 ); | |
function filter_nav_menu_link_attributes( $atts, $item, $args, $depth ) { | |
if ( $args->theme_location === 'header-menu' ) { | |
$atts['class'] = 'menu-link'; | |
if ( $item->current ) { | |
$atts['class'] .= ' menu-link--active'; | |
} | |
} | |
return $atts; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
wp_nav_menu( [ | |
'theme_location' => 'header-menu', | |
] ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment