Skip to content

Instantly share code, notes, and snippets.

@renventura
Last active December 8, 2022 16:50
Show Gist options
  • Save renventura/51247f87a2d8d68c4183 to your computer and use it in GitHub Desktop.
Save renventura/51247f87a2d8d68c4183 to your computer and use it in GitHub Desktop.
Add Font Awesome icons to WordPress menu anchor text
<?php //* Mind this opening PHP tag
/**
* Append Font Awesome icons to menu-item anchor text
* Requires the "fa" and "fa-{icon_key}" classes to be added to the menu item
*
* @author Ren Ventura <EngageWP.com>
* @link http://www.engagewp.com/add-font-awesome-icons-to-wordpress-menu-anchor-text/
*
* @param $item Menu-item object
* @return $item Modified menu-item object
*/
add_filter( 'wp_setup_nav_menu_item', 'rv_wp_setup_nav_menu_item' );
function rv_wp_setup_nav_menu_item( $item ) {
// If not in the admin and 'fa' is an included class
if ( ! is_admin() && in_array( 'fa', $item->classes ) ) {
// Create an array for the Font Awesome classes
$font_awesome_classes = array( 'fa' );
foreach( $item->classes as $key => $class ) {
// Start removing the F.A. classes from the parent li tag, otherwise icons display twice
if ( $class === 'fa' )
unset( $item->classes[$key] );
// If the class is a font-awesome icon
if ( substr( $class, 0, 3 ) === 'fa-' ) {
// Throw the icon class into the array
$font_awesome_classes[] = $class;
// Finish removing the F.A. classes from parent li
unset( $item->classes[$key] );
// Use only one icon if multiple icons are present
break;
}
}
// Create the icon markup
$icon_tag = sprintf( '<span class="link-icon"><i class="%s"></i></span>', implode( ' ', $font_awesome_classes ) );
// Prepend the icon markup to the anchor text
$item->title = $icon_tag . $item->title;
}
return $item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment