Almost drop-in menu effects from codrops.
A client asked me to update her site while still keeping it quite plain. She has been blogging since 2003 and this was only the third theme update (the last one was back in 2006).
I added a menu hover effect that I found in an old codrops article on Creative Link Effects. I used the second example, a 3D effect (with “Ratatouille” as the first link). I added the CSS but the rotated view was blank. I needed to add a ‘data-hover‘ attribute.
Finding the right filter
I dug deep into the wp_nav_menu() code and then into the ‘Walker_Nav_Menu‘ class in /wp-includes/nav-menu-template.php. I eventually found the ‘nav_menu_item_args‘ filter.
As usual I experimented to see what data was coming into the filter function and quickly learned what variables to change. The first parameter is a std_Class of wp_nav_menu() arguments, the second is a WP_Post object of the menu item and the final one is the depth of the current menu item (with 0 for top level items).
When experimenting with Genesis Sample theme I could see that it already included a <span> tag before the menu item text. I wrote code to do a ‘str_replace()‘ to insert the required ‘data-hover‘ attribute into this ‘span’ tag. To distinguish the hover item from the non-hover item I made the hover version lowercase with ‘strtolower()‘.
Support on other themes
While the code worked fine on Genesis Sample it didn’t work on the default WordPress themes. This was because they don’t include the ‘<span>‘ tag so I added this. With this change the code now works with Storefront, Twenty Nineteen, Twenty Seventeen, Twenty Sixteen and Twenty Fifteen themes. It does not, however, work with the GeneratePress theme as it uses a custom ‘walker’ class to create the menu and this does not provide the ‘nav_menu_item_args‘ filter.
You will very likely need to change existing styles so that the menu looks as you want it. For example, in Genesis Sample, the menu item colour is blue. As the example I used has a blue background it makes the menu text hard to read. To keep the CSS as generic as possible I chose to target the ‘nav’ element instead of one specific to Genesis Sample.
The original article uses a custom build of Modernizr to test whether the browser supports 3D CSS transforms and hence includes a .csstransforms3d selector for some of the styles. I commented this out because 3D transform support is very good.
I included an $effect_type member variable to facilitate enhancing the class to delivering different effects. The add_custom_styles() function could be extended to include the styles of additional examples from the Creative Link Effects article and this member variable would be used to output the appropriate CSS.
The $menu_target member variable could be made available to be changed via a filter.
To limit the changes to a specific menu location, another variable or filter could be added to check the $args->theme_location value before changing $args.