Set a coupon description in WooCommerce

大兔子大兔子 提交于 2019-12-01 13:05:18

The coupon description has to be added in the post data as post_excerpt key (but not in post meta data)

So your code should be instead:

$percent = 25;//DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; //Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$description = __('This is an example description used for the example coupon');

//ASSIGN COUPON AND DISCOUNT PERCENTAGE

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_excerpt' => $description, // <== HERE goes the description
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

## … / … and so on

Or instead, since WooCommerce 3, you can use any related method on a WC_Coupon Object. In your case you will use setter methods to set the data (as getter methods are used to get the data on an existing coupon object):

// Get an instance of the WC_Coupon object
$wc_coupon = new WC_Coupon($coupon_code);

// Some data
$percent = 25; // DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; // Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$description = __('This is an example description used for the example coupon'); // Description

// Set the coupon data
$wc_coupon->set_code($coupon_code);
$wc_coupon->set_description($description);
$wc_coupon->set_discount_type($discount_type);
$wc_coupon->set_amount( floatval($percent) );
$wc_coupon->set_individual_use( true );
$wc_coupon->set_usage_limit( 1 );
$wc_coupon->set_date_expires( strtotime("+6 months") );
## $wc_coupon->apply_before_tax( true ); // ==> Deprecated in WC 3+ with no replacement alternatie
$wc_coupon->set_free_shipping( false );

// Test raw data output before save
var_dump($wc_coupon);

// SAVE the coupon
$wc_coupon->save();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!