Andi North Andi North - 1 year ago 191
PHP Question

Issues programmatically creating variable subscription product in WooCommerce

I'm currently developing a website that uses WooCommerce and various extensions (all of which are up to date at the time of writing) to show a range of posts that belong to a custom post type.

These posts are created by website users on the front end of the website using a bespoke ACF form. The front end form creates a new post in the post type "shwimmer-pools" alongside two new products - one for the subscriptions and one for bookings.

The creation of these new posts is handled in our bespoke class ShwimmerFormHandler. This class is fired when the pool creation form is submitted. You can view the class at this Gist:

The issue we're facing is with the Subscriptions product. The product needs to be a variable subscription product as pool creators can set 6 different price bands - adult, child, family & month or year subscriptions.

Currently we're successfully creating the new subscription product with wp_insert_post() [line 285] and we're also creating each of the variations using wp_insert_post() [from line 478]. These are all being successfully registered and are sort of working.

The issue we're facing is when you view the front end subscription purchase form the price is not correct and whenever you select a variation an error message appears: "Sorry, this product is unavailable. Please choose a different combination."

The subscription product works as expected after pressing "Update" in admin. Any ideas on how to fix this issue?

Thanks, Andi

Answer Source

You probably need to trigger the variable product sync.

$subscription_id = wp_insert_post( $args );
$product = wc_get_product( $subscription_id );

Also, as you have discovered (and added here for completeness) the sync function works off of the _price meta. _regular_price and _sale_price are also compared. Subscriptions sets its _subscription_price as the _regular_price and then the _price is either the _regular_price or the _sale_price depending on whether the item is on sale. So, if you are programmatically creating a Subscription, you need to be sure to set the _price and _regular_price meta.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download