Skip to content

Instantly share code, notes, and snippets.

@wpspeak
Forked from thomasgriffin/gist:4253190
Last active April 16, 2019 14:18
Show Gist options
  • Save wpspeak/637a1aad1e487b41260b to your computer and use it in GitHub Desktop.
Save wpspeak/637a1aad1e487b41260b to your computer and use it in GitHub Desktop.
How to Add Custom Classes to First and Last Items in WordPress Menu
<?php
add_filter( 'wp_nav_menu_objects', 'afn_custom_menu_class' );
/**
* Filters the first and last nav menu objects in your menus
* to add custom classes.
*
* @since 1.0.0
*
* @param object $objects An array of nav menu objects
* @return object $objects Amended array of nav menu objects with new class
*/
function afn_custom_menu_class( $objects ) {
// Add "first-menu-item" class to the first menu object
$objects[1]->classes[] = 'first-menu-item';
// Add "last-menu-item" class to the last menu object
$objects[count( $objects )]->classes[] = 'last-menu-item';
// Return the menu objects
return $objects;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment