概要
woocommerce_new_coupon
アクションは、WooCommerce で新しいクーポンが作成されたときにトリガーされるフックです。このアクションを使用することで、クーポンの作成時に特定の処理を実行することができます。主に以下のような機能を実装する際に使われることが多いです。
- クーポンが作成された際の通知システムの構築
- 追加のメタデータや情報をクーポンに関連付ける
- 外部サービスとの統合(例: マーケティングツールや分析システム)
- クーポンの利用回数や総額のトラッキング
- カスタムロジック(条件に応じた動作の実装)
- ユーザーに対する特別オファーの生成
構文
add_action('woocommerce_new_coupon', 'your_function_name', 10, 1);
パラメータ
$coupon_id
(int): 作成されたクーポンのID。
戻り値
このアクションには明確な戻り値はありませんが、通常は何らかの処理を実行します。
使用可能なプラグインバージョン
- 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: クーポン作成時に管理者に通知を送信
このコードは、新しいクーポンが作成されたときにサイトの管理者にメールを送信します。
function notify_admin_on_coupon_creation($coupon_id) {
$coupon = new WC_Coupon($coupon_id);
$to = get_option('admin_email');
$subject = '新しいクーポンが作成されました';
$message = 'クーポンコード: ' . $coupon->get_code();
wp_mail($to, $subject, $message);
}
add_action('woocommerce_new_coupon', 'notify_admin_on_coupon_creation');
引用元: https://developer.wordpress.org/reference/hooks/
サンプル2: クーポンにカスタムメタデータを追加
このサンプルコードは、新しく作成されたクーポンにカスタムメタデータを追加します。
function add_custom_meta_to_coupon($coupon_id) {
$meta_value = 'カスタムデータ';
update_post_meta($coupon_id, '_custom_meta_key', $meta_value);
}
add_action('woocommerce_new_coupon', 'add_custom_meta_to_coupon');
引用元: https://developer.woocommerce.com/
サンプル3: クーポンの作成時にログを記録する
このコードは、クーポンが作成されるたびにログを記録します。
function log_coupon_creation($coupon_id) {
error_log('新しいクーポンが作成されました。クーポンID: ' . $coupon_id);
}
add_action('woocommerce_new_coupon', 'log_coupon_creation');
引用元: https://wordpress.org/support/article/writing-a-plugin/
サンプル4: 新しいクーポンを作成するための条件付け
このコードは、条件を設定して特定の条件を満たす場合にのみクーポンを作成します。
function conditional_coupon_creation($coupon_id) {
$coupon = new WC_Coupon($coupon_id);
if ($coupon->get_discount_type() == 'fixed_cart') {
// 固定カート割引の場合の特別処理
// 例: 特定のメタデータを追加
update_post_meta($coupon_id, '_special_meta_key', '特別な値');
}
}
add_action('woocommerce_new_coupon', 'conditional_coupon_creation');
引用元: https://woocommerce.com/document/woocommerce-coupons/
サンプル5: 外部サービスにクーポン情報を送信
このサンプルコードは、作成されたクーポン情報を外部サービスに送信します。
function send_coupon_to_external_service($coupon_id) {
$coupon = new WC_Coupon($coupon_id);
$data = array(
'code' => $coupon->get_code(),
'discount' => $coupon->get_discount_type(),
);
$args = array(
'body' => json_encode($data),
'headers' => array('Content-Type' => 'application/json')
);
wp_remote_post('https://example.com/api/coupons', $args);
}
add_action('woocommerce_new_coupon', 'send_coupon_to_external_service');
引用元: https://developer.wordpress.org/reference/functions/wp_remote_post/