2016-09-28 89 views
2

我試圖檢查優惠券是否仍然有效(尚未達到其使用限制)並在此條件下顯示內容。WooCommerce:檢查優惠券是否有效

原因是我希望能夠向特定訪客發放優惠券代碼,但顯然不想分發已經達到其使用限制的優惠券。

我想用PHP來實現這一點,想象中的代碼是這樣的:

<?php if (coupon('mycouponcode') isvalid) { 
    echo "Coupon Valid" 
} else { 
    echo "Coupon Usage Limit Reached" 
} ?> 

:)

+0

優惠券取決於很多標準,所以您只需要使用限制? –

+0

@RaunakGupta是的,使用限制是我感興趣的唯一標準:) – NuclearApe

回答

3
$code = 'test123'; 

$coupon = new WC_Coupon($code); 
$coupon_post = get_post($coupon->id); 
$coupon_data = array(
    'id' => $coupon->id, 
    'code' => $coupon->code, 
    'type' => $coupon->type, 
    'created_at' => $coupon_post->post_date_gmt, 
    'updated_at' => $coupon_post->post_modified_gmt, 
    'amount' => wc_format_decimal($coupon->coupon_amount, 2), 
    'individual_use' => ('yes' === $coupon->individual_use), 
    'product_ids' => array_map('absint', (array) $coupon->product_ids), 
    'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids), 
    'usage_limit' => (!empty($coupon->usage_limit)) ? $coupon->usage_limit : null, 
    'usage_count' => (int) $coupon->usage_count, 
    'expiry_date' => (!empty($coupon->expiry_date)) ? date('Y-m-d', $coupon->expiry_date) : null, 
    'enable_free_shipping' => $coupon->enable_free_shipping(), 
    'product_category_ids' => array_map('absint', (array) $coupon->product_categories), 
    'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories), 
    'exclude_sale_items' => $coupon->exclude_sale_items(), 
    'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2), 
    'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2), 
    'customer_emails' => $coupon->customer_email, 
    'description' => $coupon_post->post_excerpt, 
); 

$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count']; 

if ($usage_left > 0) { 
    echo 'Coupon Valid'; 
} 
else { 
    echo 'Coupon Usage Limit Reached'; 
} 

的代碼測試完全在這裏的任何幫助將是巨大的功能。

參考

+0

這總是返回「優惠券使用限制達到」。我已經用無數優惠券(有效,過期,用完,剩餘使用等)替換test123,但沒有快樂:( – NuclearApe

+0

@NuclearApe:有任何有效的優惠券打印'$ coupon_data ['usage_limit']','$ coupon_data ['usage_count ']'和'$ coupon_data ['expiry_date']'看看他們回來了什麼。 –

+0

只是爲了說明:WC_Coupon類('is_valid()'和'is_valid_for_cart()')有兩個相關的方法。不幸的是,他們不工作... **有一個** bug **,因爲他們**總是返回false **。所以我發佈了一個線程在WordPress> Woocommerce支持線程:https://wordpress.org/支持/主題/ wc_coupon-is_valid-method-always-return-false/ – LoicTheAztec

0

可以使用this插件你的目的。

+0

[應避免鏈接回答](http://stackoverflow.com/help/how-to-answer):「鼓勵鏈接到外部資源,但請在鏈接周圍添加上下文,以便您的其他用戶擁有一些想法是什麼以及它爲什麼在那裏。如果目標網站無法訪問或永久離線,請始終引用重要鏈接中最相關的部分 – indextwo