I’ve written a few posts about some of the work I’ve done with WooCommerce over the last couple of months, but one of the things I’ve yet to cover is how to add a custom WooCommerce menu.
Using Google or Stack Exchange or some other bloggers will yield some solid results, but my situation is two-fold:
- Introduce a new video menu item,
- Create and display a custom template for the menu.
The latter is a little more complicated, so I’ll cover it in a follow-up post, but the former is something to be covered in a post all its own.
A Custom WooCommerce Menu
Assume that you need to add an item to your WooCommerce menu – the one that appears on the My Account page – and you want to add it just about the Logout menu item.
WooCommerce provides a hook to add an item – woocommerce_account_menu_items – but it doesn’t give you much control over where the menu item is added. Nor should it. That’s up to us.
If you look at the linked source above, you’ll notice that it passes an array of items into the hooked function. This is where we’re able to take advantage of adding our menu item.
So say, for example, we want to add a menu item, Acme Item, to the My Account page and add it as the second to last item. To do this, we can set up an initialization function:
And then the actual implementation of the hooked function will look like this:
In short, the code will…
- take the incoming items and return a new array without the last item,
- create an array for our custom item,
- take the original items array and grab the last item,
- and then merge them all together into the same array.
The result does what you’ve set out to do and takes all of maybe 25 lines of code if you include a namespace and are liberal with your line spacing. Which I am. 😏
Regardless, this gets you to the point of having a custom WooCommerce menu, but adding a custom template to that programmatically is something else completely. And I’ll cover that in the following post.