WooCommerce中的优惠券每日时间范围



我想在Wooccommerce中启用优惠券,但没有成功。

基于Wooccommerce中基于每日时间范围的特定产品折扣答案,我的代码是:

// Utility function that gives the discount daily period
function get_discount_period_rate(){
// Set the correct time zone  (http://php.net/manual/en/timezones.php)
date_default_timezone_set('Europe/Paris');

// Set the start time and the end time
$start_time = mktime( 08, 00, 00, date("m")  , date("d"), date("Y") );
$end_time   = mktime( 09, 00, 00, date("m")  , date("d"), date("Y") );
$time_now   = strtotime("now");
}
// Set the coupon Ids that will be discounted
$wc_coupon = new WC_Coupon('integralia10'); // get intance of wc_coupon which code is "integralia10"
if (!$wc_coupon || !$wc_coupon->is_valid()) {
return;
}
$coupon_code = $wc_coupon->get_code();
if (!$coupon_code) {
return;
}

此外,当有人试图在时间范围外使用优惠券代码时,我想使用wc_print_notices函数来显示消息。

有建议吗?

使用以下代码,在特定时间范围内的所有优惠券都将有效,否则将显示错误消息。

请设置:

  • 正确的时区
  • 开始和结束时间
function time_range() {
// Set the correct time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set( 'Europe/Brussels' );
// Set the start time and the end time to be valid
$start_time = mktime( 11, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
$end_time   = mktime( 18, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
$time_now   = strtotime( 'now' );

// Return true or false
return $start_time <= $time_now && $end_time >= $time_now ? true : false;
}
// Is valid
function filter_woocommerce_coupon_is_valid( $valid, $coupon, $discount ) {
// Call function, return true or false
$valid = time_range();
// NOT valid
if ( ! $valid ) {
throw new Exception( __( 'My custom error message.', 'woocommerce' ), 109 );
}
return $valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );

更新:要应用相同的,但仅适用于某些优惠券ID,请改用此。

function time_range_coupon_id( $coupon_id ) {
// For specific coupon ID's only, several could be added, separated by a comma
$specific_coupons_ids = array( 107, 108 );

// Coupon ID in array, so check
if ( in_array( $coupon_id, $specific_coupons_ids ) ) {
// Set the correct time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set( 'Europe/Brussels' );
// Set the start time and the end time to be valid
$start_time = mktime( 12, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
$end_time   = mktime( 17, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
$time_now   = strtotime( 'now' );

// Return true or false
return $start_time <= $time_now && $end_time >= $time_now ? true : false;
}

// Default
return true;
}
// Is valid
function filter_woocommerce_coupon_is_valid( $valid, $coupon, $discount ) {
// Get coupon ID
$coupon_id = $coupon->get_id();

// Call function, return true or false
$valid = time_range_coupon_id( $coupon_id );
// NOT valid
if ( ! $valid ) {
throw new Exception( __( 'My error message', 'woocommerce' ), 109 );
}
return $valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );

最新更新