Skip to content

Instantly share code, notes, and snippets.

@fahrradflucht
Last active March 6, 2021 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahrradflucht/9a6853f6b3754499fd0905ac90644d0a to your computer and use it in GitHub Desktop.
Save fahrradflucht/9a6853f6b3754499fd0905ac90644d0a to your computer and use it in GitHub Desktop.
Add the "missing" `item_class`, `item_link_class` and `current_item_link_class` arguments to `wp_nav_menu`.
<?php
/**
* Adds support for passing `item_class` to `wp_nav_menu`.
*/
add_filter('nav_menu_css_class', function ($class_names, $item, $args) {
if (property_exists($args, 'item_class')) {
return array_merge($class_names, explode(' ', $args->item_class));
}
return $class_names;
}, 10, 3);
/**
* Adds support for passing `item_link_class` and `current_item_link_class` to
* `wp_nav_menu`.
*/
add_filter('nav_menu_link_attributes', function ($atts, $item, $args, $depth) {
$classes = array();
if (property_exists($args, 'item_link_class')) {
array_push($classes, $args->item_link_class);
}
if (property_exists($args, 'current_item_link_class')
&& in_array('current-menu-item', $item->classes)) {
array_push($classes, $args->current_item_link_class);
}
if (!empty($classes)) {
$atts['class'] = implode(' ', $classes);
}
return $atts;
}, 10, 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment