Make WordPress Nav Dropdown Menus Non-Clickable

Posted 02/06/2024, Updated 02/06/2024 James Parsons by James Parsons 0

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:

Url Hash

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:

Javascript Void

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!

Related Code Snippets

Written by James Parsons

Hi, I'm James Parsons! I founded Content Powered, a content marketing agency where I partner with businesses to help them grow through strategic content. With nearly twenty years of SEO and content marketing experience, I've had the joy of helping companies connect with their audiences in meaningful ways. I started my journey by building and growing several successful eCommerce companies solely through content marketing, and I love to share what I've learned along the way. You'll find my thoughts and insights in publications like Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, and Inc, among others. I've been fortunate to work with wonderful clients ranging from growing businesses to Fortune 500 companies like eBay and Expedia, and helping them shape their content strategies. My focus is on creating optimized content that resonates and converts. I'd love to connect – the best way to contact me is by scheduling a call or by email.