I add coupons at woocommerce with this code programmatically.
if(empty($coupon_post)){
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
update_post_meta( $new_coupon_id, 'exclude_sale_items', 'no' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
update_post_meta( $new_coupon_id, 'product_categories', '' );
update_post_meta( $new_coupon_id, 'exclude_product_categories', '' );
update_post_meta( $new_coupon_id, 'minimum_amount', '' );
update_post_meta( $new_coupon_id, 'customer_email', '' );
}
But it says always the usage_limit = 1.
I add additional this code to update:
add_action( 'save_post_shop_coupon', 'my_child_after_coupon_save', 10, 3 );
function my_child_after_coupon_save( $post_id, $post, $update ) {
update_post_meta( $post_id, 'usage_limit', '');
}
But it doesn't work first.But if I open the coupon in the backend and update without any changes. The usage limit is set to unlimited.
How can trigger this, that I needn't to open all coupons.
Since WooCommerce 3, your code is a bit outdated as for example
apply_before_tax
is not used anymore. You should better use all availableWC_Coupon
setter methods, for coupon creation.In the code below I just use the necessary setter methods (related to your code):
Now to update coupons you can use the following hooked function with any setter method like:
Code goes in functions.php file of the active child theme (or active theme).