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

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

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=" 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="'', '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 .
        // 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.

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

Subscribe it's FREE

Comments are closed.