概要
woocommerce_coupon_get_discount_amount
フィルタは、WooCommerceのクーポン割引金額を計算する際に使用されます。このフィルタを利用することで、クーポン割引の計算ロジックをカスタマイズすることができます。具体的には以下のような機能を実装する際に多く使われます。
- 割引金額の条件付き変更
- 消費税の影響を考慮した割引金額の調整
- 通常のカテゴリに適用されたクーポンの割引金額の変更
- 特定のユーザーグループに対する対象割引の追加
- プロモーションのキャンペーンに合わせた割引ルールの適用
- 最小購入金額に基づく割引金額の計算
構文
add_filter( 'woocommerce_coupon_get_discount_amount', 'custom_discount_amount', 10, 5 );
パラメータ
$discount_amount
(float) – 現在の割引金額$discounting_amount
(float) – 割引対象金額$cart_item
(array) – カートに入っているアイテムの情報$single
(bool) – 単品かどうかのフラグ$coupon
(WC_Coupon) – 使用されているクーポンの情報
戻り値
- (float) – カスタマイズした割引金額
使用可能なWooCommerceのバージョン
- WooCommerce 3.0以上
使用可能なWordPressのバージョン
- WordPress 4.0以上
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード 1: 割引金額の条件付き変更
add_filter( 'woocommerce_coupon_get_discount_amount', 'custom_discount_for_special_items', 10, 5 );
function custom_discount_for_special_items( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) {
if ( in_array( 'special_category', $cart_item['data']->get_category_slugs() ) ) {
return $discount_amount * 1.5; // 特定のカテゴリには1.5倍の割引
}
return $discount_amount;
}
このコードは、特定のカテゴリに属するアイテムに対して割引金額を1.5倍にするカスタマイズを行います。
サンプルコード 2: 消費税の影響を考慮した割引金額の調整
add_filter( 'woocommerce_coupon_get_discount_amount', 'adjust_discount_for_tax', 10, 5 );
function adjust_discount_for_tax( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) {
$tax_rate = 0.1; // 10%の消費税
return $discount_amount / (1 + $tax_rate); // 消費税を考慮した割引金額
}
このコードは、税率を考慮に入れて割引金額を調整するものです。
サンプルコード 3: ユーザーグループに基づく割引の変更
add_filter( 'woocommerce_coupon_get_discount_amount', 'user_group_discount', 10, 5 );
function user_group_discount( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) {
if ( current_user_can( 'premium_member' ) ) {
return $discount_amount + 5; // プレミアムメンバーには追加で5の割引
}
return $discount_amount;
}
このコードは、プレミアムメンバーに追加の割引を提供します。
サンプルコード 4: クーポン使用時の記録を追加
add_filter( 'woocommerce_coupon_get_discount_amount', 'log_coupon_usage', 10, 5 );
function log_coupon_usage( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) {
error_log( 'クーポン ' . $coupon->get_code() . ' を使用しました。割引金額: ' . $discount_amount );
return $discount_amount; // そのまま割引金額を返す
}
このコードは、クーポンの使用時にログを記録する機能を持っています。
サンプルコード 5: 最小購入金額を考慮した割引金額の計算
add_filter( 'woocommerce_coupon_get_discount_amount', 'minimum_purchase_discount', 10, 5 );
function minimum_purchase_discount( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) {
$minimum_amount = 100; // 最小購入金額
if ( WC()->cart->total < $minimum_amount ) {
return 0; // 最小購入金額に満たない場合は割引なし
}
return $discount_amount;
}
このコードは、カートの合計金額が指定の最小購入金額に満たない場合、割引を適用しない設定です。