概要
woocommerce_coupon_code
アクションは、WooCommerceのクーポンコードが適用される際に実行されるフックです。このアクションは、クーポンコードの適用や検証といった機能をカスタマイズする際に非常に役立ちます。
一般的に、このアクションは次のような機能を実装する際に使用されます:
- クーポンコードの用途に基づく条件付きロジックの追加
- クーポンコードが適用された際のカスタムメッセージの表示
- 特定の条件に基づくクーポンの無効化
- クーポンコードの適用前後でのステータス更新
- チェックアウトステップにおける追加の検証ルールの適用
- デバッグ情報のログ出力
構文
do_action( 'woocommerce_coupon_code', $coupon_code );
パラメータ
$coupon_code
(string): 適用されたクーポンコードの文字列。
戻り値
このアクションには戻り値はありません。各アクション関数は、独自の処理を実行するために使用されます。
WooCommerceおよびWordPressのバージョン
- WooCommerce: バージョン 3.0 以上
- 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_action( 'woocommerce_coupon_code', 'custom_coupon_code_message', 10, 1 );
function custom_coupon_code_message( $coupon_code ) {
if ( $coupon_code === 'MYCOUPON' ) {
wc_add_notice( 'このクーポンは特別な割引を提供します!', 'notice' );
}
}
引用元: https://woocommerce.com/
サンプルコード2: 特定の条件でクーポンを無効化
このコードは、特定の条件に基づいてクーポンコードを無効化します。
add_action( 'woocommerce_coupon_code', 'disable_coupon_for_special_users', 10, 1 );
function disable_coupon_for_special_users( $coupon_code ) {
if ( is_user_logged_in() && current_user_can( 'special_role' ) ) {
remove_coupon( $coupon_code );
wc_add_notice( 'このクーポンはご利用いただけません。', 'error' );
}
}
引用元: https://woocommerce.com/
サンプルコード3: クーポン適用後にカスタム処理を実行
このコードは、クーポンが適用された後の処理を定義します。
add_action( 'woocommerce_coupon_code', 'after_coupon_code_applied', 15, 1 );
function after_coupon_code_applied( $coupon_code ) {
// クーポン適用後のカスタム処理
}
引用元: https://woocommerce.com/
サンプルコード4: デバッグ用の情報をログに出力
このコードは、クーポンコードが適用されたときにデバッグ情報をログに出力します。
add_action( 'woocommerce_coupon_code', 'log_coupon_code_application', 20, 1 );
function log_coupon_code_application( $coupon_code ) {
error_log( 'クーポンコードが適用されました: ' . $coupon_code );
}
引用元: https://woocommerce.com/
サンプルコード5: 費用の観点からクーポンの計算を変更
このコードは、クーポンコードの割引計算を変更します。
add_action( 'woocommerce_coupon_code', 'custom_coupon_discount', 25, 1 );
function custom_coupon_discount( $coupon_code ) {
if ( $coupon_code === 'DISCOUNT50' ) {
// 特定の計算をする
}
}
引用元: https://woocommerce.com/