Instantly share code, notes, and snippets.

Embed
What would you like to do?
Takes custom classes out of the list item and adds them to the anchor element in WordPress menus. Perfect for font icons
<?php
add_filter( 'nav_menu_link_attributes','cameronjonesweb_move_custom_menu_item_class_to_anchor_element', 10, 4 );
add_filter( 'nav_menu_css_class', 'cameronjonesweb_remove_custom_menu_item_class_from_li_element', 10, 4 );
/**
* Get the custom item menu classes and add them to the anchor element
*
* @link https://cameronjonesweb.com.au
* @param array $atts The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
* @param WP_Post $item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
* @return array
*/
function cameronjonesweb_move_custom_menu_item_class_to_anchor_element( $atts, $item, $args, $depth ) {
$custom_classes = get_post_meta( $item->ID, '_menu_item_classes', true );
if ( ! empty( $custom_classes ) ) {
$atts['class'] = empty( $atts['class'] ) ? '' : $atts['class'];
$atts['class'] .= implode( ' ', $custom_classes );
}
return $atts;
}
/**
* Remove the custom classes from the list element
*
* @link https://cameronjonesweb.com.au
* @param array $classes The CSS classes that are applied to the menu item's `<li>` element.
* @param WP_Post $item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
* @return array
*/
function cameronjonesweb_remove_custom_menu_item_class_from_li_element( $classes, $item, $args, $depth ) {
$custom_classes = get_post_meta( $item->ID, '_menu_item_classes', true );
$classes = array_diff( $classes, $custom_classes );
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment