How to add a class to submenu items when they are clicked

To add a class to submenu items when they are clicked using jQuery in WordPress, you can use the following code. This assumes that you are using the default WordPress navigation menu structure:

This jQuery code targets all <li> elements within a submenu ('.sub-menu li'). When a submenu item is clicked, it removes the ‘active’ class from all submenu items and adds the ‘active’ class to the clicked item.

Remember to enqueue this script properly in your WordPress theme. You can add it to your theme’s JavaScript file or include it using the wp_enqueue_script function in your theme’s functions.php file.

Make sure to replace get_stylesheet_directory_uri() . '/js/custom-script.js' with the correct path to your JavaScript file.

After enqueuing the script, don’t forget to check your browser’s console for any errors and ensure that jQuery is properly loaded on your site.

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.