How do I Add “onClick action” To My WordPress Menu?

Written by on April 25, 2013

When you have been doing WordPress design for as long as we have you are pretty much bound to pick up a few neat tricks along the way. The WordPress menu system for example – this is a great tool for practically everything you’ll ever need. However, one thing WordPress menus wont do is let you add any JavaScript like: onclick="window.open And that is when you need a WordPress design expert to work with you. Granted, this may not be the most requested tweak in world. Yet, still plenty of things I can think to use it for. Besides, the fact that you are here reading this post means that you might already be feeling the heat. In this short tutorial you will learn how to add a JavaScript into a custom link inside the WordPress navigation menu.

popup demo

To add an onClick action inside your WordPress menu, simply open your functions.php file and paste the following function:

add_filter( 'wp_nav_menu_items', 'add_popup_link', 10, 2 );
function add_popup_link($items, $args) {
  
       
            // Here you can replace our menu-item class with your own custom menu class 
            $class = 'class="menu-item"'; 
            $homeMenuItem =
                '<li ' . $class . '>' .
                $args->before .
                // Here we add the url of the popup window and also set dimensions and the like 
                '<a href="#" onclick="window.open(\'http://yourwebsite.com/\', \'popupwindow\', \'scrollbars=yes,width=550,height=700\');return true">' .
                // Here we give our link a title  
                $args->link_before . 'Click to see my popup' . $args->link_after .
                '</a>' .
                $args->after .
                '</li>';
        
        // Here we append our new tab to the main menu      
        $items = $homeMenuItem.$items ;
  
    return $items;
}

I’m not providing any other explanation since all the code is commented. Looking forward to your comments.

Dave Collado
Web designer and developer from San Jose, California with over 12 years experience in the industry. You can find him on and twitter.

Did you like this post? Here is what you need to do next:

Subscribe it's FREE

Please enter your email to activate your subscription immediately.