In this tutorial we are going to dive deep into creating an order on your WooCommerce store completely via code. I already have a similar tutorial on my blog where we created a product programmatically.
First things first, you should know a very simple thing – yeah, orders is a WordPress custom post type and no, we can not use
wp_insert_post() to create them. We have to use a CRUD layer for that. If it says nothing to you, please be patient, we’re going to dive into it in just a little bit.
In this simple guide I will show how to check in WooCommerce if a product with specific ID is in cart programmatically. We are also going to do it for different types of products and take a look at products with custom cart item data.
In the previous tutorial we already discussed how to check if a specific coupon is applied to cart or to an order. But in this tutorial I will show you a different thing – how to find out programmatically if coupon with a specific code is actually created in WooCommerce admin.
The inspiration for this tutorial was another tutorial I found where it was recommended to create WooCommerce coupons using
wp_insert_post() function and
update_post_meta(). When working with WooCommerce data since 3.0 version it is always recommended to use CRUD objects. And coupons are not an exception.
In order to create a coupon programmatically in code we have to use
WC_Coupon object. Once the object is created we are able to use its methods for coupon configuration.
Let’s do it and begin with something simple.
In this tutorial I am going to guide you through the process of creating products in WooCommerce in code.
It is the most correct way of creating products in latest WooCommerce versions. So, please forget about
update_post_meta() functions. Yes, I perfectly remember that products are WordPress custom post types and product prices are post meta but it doesn’t allow us to use those functions anyway, because there is a little more than that and it could cause bugs.
In this tutorial we are going to use CRUD objects that were introduced in WooCommerce 3.0 (CRUD is an abbreviation of Create, Read, Update, Delete). The CRUD objects we are interested in right now are:
WC_Product_Simple– for simple products,
WC_Product_External– for external products,
WC_Product_Grouped– for grouped products,
WC_Product_Variable– variable ones.
We are also going to use plenty of methods of these objects, that allow us to configure our product data.