Skip to content

Instantly share code, notes, and snippets.

@cameronjonesweb
Last active June 26, 2023 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronjonesweb/0f6bd237543b056dd5fe607e7eef8331 to your computer and use it in GitHub Desktop.
Save cameronjonesweb/0f6bd237543b056dd5fe607e7eef8331 to your computer and use it in GitHub Desktop.
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/blog/how-to-move-the-custom-menu-item-classes-to-the-anchor-element/
* @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/blog/how-to-move-the-custom-menu-item-classes-to-the-anchor-element/
* @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