Skip to content

Instantly share code, notes, and snippets.

@cjkoepke
Last active May 3, 2016 03:07
Show Gist options
  • Save cjkoepke/bbf004053c094259b15b to your computer and use it in GitHub Desktop.
Save cjkoepke/bbf004053c094259b15b to your computer and use it in GitHub Desktop.
Add custom classes set for Menu items set in Appearance > Custom Menu to the anchor tag.
<?php
//* Do NOT copy the opening PHP tag
add_filter( 'nav_menu_link_attributes', 'ck_attributes_nav_link', 10, 3 );
function ck_attributes_nav_link( $atts, $item, $args ) {
if ( ! $args->menu->name == "Primary Navigation" )
return;
$menu = wp_get_nav_menu_items( 'Primary Navigation' );
foreach ( $menu as $menu_object ) {
$menu_classes = [];
foreach ( $menu_object->classes as $menu_object_class ) {
$menu_classes[] = $menu_object_class;
}
$classes = implode( " ", $menu_classes );
if ( $item->ID == $menu_object->ID ) {
$atts['class'] = $classes;
}
}
return $atts;
}
@BMOv2600
Copy link

BMOv2600 commented May 3, 2016

I noticed that on your site, that $menu_item and $menu_object seem to be interchangeable. For example, on lines 16 & 17 of functions.php, you have

foreach ( $menu_object->classes as $menu_object_class ) {
$menu_classes[] = $menu_object_class;

and in the "What’s Going On?" section, it says to use

foreach ( $menu_item->classes as $menu_item_class ) {
$menu_classes[] = $menu_item_class;

So are they interchangeable, or is there a better time to use one than the other?

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment