I’m currently wrapping up a new WooCommerce-powered ecommerce website for a client, and thought that I’d share the code I’m using to add multiple new tabs to the product pages.
When I originally went looking for a solution to this challenge I found a couple blog posts by Sean Barton that pointed me in the right direction: How to remove the WooCommerce 2.0+ Reviews tab and Adding your own tabs to Woocommerce and Woothemes. His posts explain in detail how the WooCommerce tab system works, so I won’t try to duplicate that here in this post.
Unless I missed it, his posts didn’t explain how to add multiple tabs, which is what I needed to do for this project. After coming up with my solution and while writing this post I did notice that he has released a plugin for managing multiple tabs. I haven’t tried it, but it’s there if you’d rather use a plugin instead of working directly with the code.
“Ingredients” and “Benefits” tabs
For this project, the tabs I needed to add were “Ingredients” and “Benefits,” as you can see in the screenshot below. The code I’m posting here uses those two labels, and you’ll need to make adjustments to the code as necessary to suit your project.
Add your metaboxes or custom fields first
There’s more involved here than just adding a tab or two, since you also need a way to add content to those tabs. To do that I’m using Custom Metaboxes and Fields for WordPress. I’m not going to go into detail about how to use CMB as there is documentation for that already available, but I will post the specific code that I’m using along with CMB to add custom metaboxes to the WooCommerce product post types.
The first Gist posted below shows how I add the metaboxes to the product post type. For the sake of making it simpler for my client to create and edit the content for those tabs, I’m using the WYSIWYG metabox. This screenshot shows the metaboxes in place on a product edit page.
Now add the product tabs
The second Gist posted below shows the code to add the tabs to your products on the front end. Some things to note:
- If the custom metabox that populates a tab is empty, then that tab will not be displayed on the front end.
- You can rearrange the tabs by changing their priority.
I’m using several functions to sanitize, format, and display the tab content: esc_textarea, htmlspecialchars_decode, and wpautop. If you know of a better or simpler way to do this that still works on the front end, feel free to let me know in the comments below.
- After a comment and a question (see below), I’ve updated the code to use
apply_filters( 'the_content', $product_ingredients )instead of the previous combination of functions described in step 3.
Where to put this code
Add the code to a core functionality plugin (best choice), its own plugin, or functions.php.