Make WordPress Nav Dropdown Menus Non-Clickable
For dropdown items in WordPress, you may not always want the dropdown parent itself to link to a page. You may just want them to function as a dropdown.
That's what I do on my site. Try clicking one of the dropdowns in the menu on this site. See? It didn't do anything, which is what I intended.
This code will replace all instances of "/#" in WordPress menu items and replace them with:
- javascript:void(0);
In my opinion, this is a much better option. Using a /# hash instead has the unintended consequence of making users scroll to the very top of the page when the link is clicked. So, if you have a dropdown in your sticky nav menu and someone is at the bottom of the page, then they click a nav dropdown with a hash /#, it jumps immediately to the top of the page. This is jarring and bad for user experience. If something isn't made to be clickable, it should do nothing when clicked.
Here's the code that will fix this for you. Simply add it to your functions.php file in your WordPress theme:
/**
* Replace # with javascript:void in the menu bar
*/
add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);
function wpse_226884_replace_hash($menu_item) {
if (strpos($menu_item, 'href="#"') !== false) {
$menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
}
return $menu_item;
}
Now you can use a hash (#) as the URL for any nav item that you want to be non-clickable. Like this:
Even though you used a hash in the WordPress admin, this new code will replace it on the front-end of the website with the appropriate code to use javascript:void(0); instead:
We use this one all the time for client sites, it comes in handy!
What do you think? Any questions for me? Leave me a comment and I'll get back to you quickly!
September 28, 2024
How do you usually handle dropdowns where, you know, only some of the parent items are clickable?
October 07, 2024
Hey Latesha! You've got a great question there!
You might find it pretty helpful to give some parent items in dropdowns a specific class or style to make them clickable. I like to add a little icon next to the clickable ones - it kind of helps them stand out a bit more. This way your users won't be left wondering what's clickable.
You might also want to create a separate link within the dropdown for items that need a direct action. Have you tried adding a hover effect to set them apart? It's something I've found quite helpful.
Hope this gives you some ideas! Let me know if you're looking for more help! 😊