プラグインWooCommerceのwoocommerce_coupon_messageフィルタの使用方法・解説

概要

woocommerce_coupon_message フィルタは、WooCommerce プラグインにおいてクーポンのメッセージを変更するために使用されます。主にオンラインショップでのプロモーション活動において利用されるこのフィルタは、クーポンが適用された際に表示されるメッセージ文言をカスタマイズすることで、ユーザーに対してより効果的なアプローチを可能にします。以下のような機能を実装する際によく使われます。

  1. クーポン適用後のメッセージのカスタマイズ
  2. 特定の条件に基づいてメッセージの変更
  3. ブランドや店舗のトーンに合わせたメッセージの調整
  4. ユーザーの関心を引くためのプロモーション文の追加
  5. デフォルトメッセージにプレースホルダーを使っての動的な挿入
  6. エラーメッセージのカスタマイズ

構文

add_filter('woocommerce_coupon_message', 'custom_coupon_message', 10, 3);

パラメータ

  • $msg (string): デフォルトで表示されるクーポンメッセージ。
  • $coupon (WC_Coupon): 使用されるクーポンオブジェクト。
  • $discounting (bool): 通常の割引かどうかを示すブーリアン。

戻り値

変更されたクーポンメッセージ (string)

使用可能なプラグインバージョン

WooCommerce バージョン 3.x 以上

使用可能な WordPress バージョン

WordPress バージョン 5.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_message', 'custom_coupon_success_message', 10, 3);
function custom_coupon_success_message($msg, $coupon, $discounting) {
    return '素晴らしい! クーポン「' . $coupon->get_code() . '」が適用されました。';
}

引用元: https://example.com

サンプル2: 割引額に応じたメッセージの変更

このサンプルは、割引額に応じて異なるメッセージを表示します。

add_filter('woocommerce_coupon_message', 'dynamic_coupon_message', 10, 3);
function dynamic_coupon_message($msg, $coupon, $discounting) {
    if ($coupon->get_discount_type() === 'fixed_cart' && $coupon->get_amount() >= 50) {
        return '大きな割引!' . $coupon->get_code() . 'が50ドル以上の割引を提供します。';
    }
    return $msg;
}

引用元: https://example.com

サンプル3: メッセージにユーザー名を追加

このサンプルコードは、クーポンメッセージにユーザーの名前を追加します。

add_filter('woocommerce_coupon_message', 'add_username_to_coupon_message', 10, 3);
function add_username_to_coupon_message($msg, $coupon, $discounting) {
    $current_user = wp_get_current_user();
    return 'こんにちは、' . esc_html($current_user->display_name) . 'さん!クーポン「' . $coupon->get_code() . '」が適用されました。';
}

引用元: https://example.com

サンプル4: クーポンが無効な場合のメッセージカスタマイズ

このサンプルは、無効なクーポンメッセージをカスタマイズします。

add_filter('woocommerce_coupon_message', 'custom_invalid_coupon_message', 10, 3);
function custom_invalid_coupon_message($msg, $coupon, $discounting) {
    if (!$discounting) {
        return '申し訳ありません、クーポン「' . $coupon->get_code() . '」は無効です。';
    }
    return $msg;
}

引用元: https://example.com

サンプル5: 独自のスタイルを追加

このサンプルは、クーポンメッセージに独自のスタイルを追加します。

add_filter('woocommerce_coupon_message', 'styled_coupon_message', 10, 3);
function styled_coupon_message($msg, $coupon, $discounting) {
    return '<span style="color: green; font-weight: bold;">クーポン「' . $coupon->get_code() . '」が適用されました!</span>';
}

引用元: https://example.com

この関数について質問する


上の計算式の答えを入力してください