Add a Static Menu Item to a WordPress Custom Menu

Add a Static Menu Item to a WordPress Custom Menu

Posted by Rainey

What? two WordPress tips in a row? I know right?  I love me some WordPress and needed to get an extra fix.  Actually, I just ran into this again today and thought this would be a good place to keep this nugget of knowledge, let’s dig in.

The wp_nav_menu() is a really handy addition to WordPress and gives users an easy way to control menus for their website. But, what if you want to add something custom like a View Cart link that has an onClick event to the end of a menu?  Luckily, this can be done pretty painlessly.

First, find and open up the functions.php file and paste in the following code.

// Filter the wp_nav_menu() to add your new menu item
function add_nav_menu_items($items) {
	$cartlink = '<li class="cart"><a href="https://www.myurl.com">' . __('View Cart') . '</a></li>';
	$items = $items . $cartlink ;
	return $items;
}
add_filter( 'wp_nav_menu_items', 'add_nav_menu_items' );

 

That wasn’t so bad was it? To place the new menu item before the menu you would reorder $items to look like this:

// Filter the wp_nav_menu() to add your new menu item
function add_nav_menu_items($items) {
	$cartlink = '<li class="cart"><a href="https://www.myurl.com">' . __('View Cart') . '</a></li>';
	$items = $cartlink . $items;
	return $items;
}
add_filter( 'wp_nav_menu_items', 'add_nav_menu_items' );

 

And finally, in my case I was needing an onClick event in my URL which would look something like this.

// Filter the wp_nav_menu() to add your new menu item
function add_nav_menu_items($items) {
	$cartlink = '<li class="cart"><a href="https://myurl.com/cart" target="abc" class="viewCart" onClick="javascript:return abc(this);">' . __('View Cart') . '</a></li>';
	$items = $items . $cartlink ;
	return $items;
}
add_filter( 'wp_nav_menu_items', 'add_nav_menu_items' );

Like what you are reading? Subscribe to receive monthly tips & updates!

A Monthly Roundup of Articles and a Sweet Deal

Get the latest tips, tricks, tutorials and freebies in your inbox once a monthly.

Join our growing community of front-end web developers and designers. We are constantly publishing new industry tips, tricks and tutorials to help you take your game to the next level. We are also going to include a freebie or deal on something cool each month. Enter your email below and you will only receive this email once a month, nothing else.

Subscribe to our mailing list

* indicates required


    Today in Web Design - Tutorials
    Tagged |

    • Josh K

      Dude, awesome post. This helped me out a ton. Hero.

    • Joshua Mark Modina Jumalon

      Thank you Thank you