Adding a custom WooCommerce variable product isn’t something that’s terribly difficult given the hooks that WooCommerce provides, but there’s always a bit of context that helps when giving an example like this, right?
Last week, I shared a small bit of a code that shows how to add a custom input field to a WooCommerce product. And in that post, one of the things I shared what how I like how easy it is to create UI elements using server-side logic.
And working with variable products is no different. It is, however, a matter of using a different hook.
Add a WooCommerce Variable Product
First, I think it helps to understand what variable products are when working with WooCommerce. The truth is, when I started working this project, I wasn’t sure how WooCommerce defined a variable product.
It’s easy enough to understand, though:
Variable products are a product type in WooCommerce that lets you offer a set of variations on a product, with control over prices, stock, image and more for each variation. They can be used for a product like a shirt, where you can offer a large, medium and small and in different colors.
Though this doesn’t necessarily impact how you develop this functionality, it helps to understand part of the problem domain on which you’re going to be working.
Adding support for custom product variations, requires two things:
- Adding the UI element for the variation,
- Saving the data from the UI.
If you’ve read the previous post, then step two is pretty easy. If not, no big deal. I’ll cover it below.
1. Initializing The Hooks
First, I define an
init function that’s responsible for registering the hooks.
Notice that these function calls set both a priority and the number of arguments the functions should expect.
2. Rendering The UI
Note that everything is abstracted in the
woocommerce_wp_text_input function for rendering the information. That’s, as they say, is where the magic happens.
3. Saving The Data
And finally, we need to make sure the information is sent to the database.
Note that the
value attribute also retrieves the post metadata if it exists (otherwise, an empty string is populated). This makes the user experience nice as it saves the data
Notice that the function’s I’ve provided are in the context of
public functions and that refer to
$this within their code. This is because it’s being used in the context of a class.
If you opt to go the procedural route, then you won’t use visibility modifiers nor will you need to refer to
$this. Instead, you’ll just need to prefix your functions.
With that said, don’t hesitate to read through the WooCommerce documentation as it’s replete with everything that’s gone into the product and is worth always keeping open when working on your projects.