概要
woocommerce_email_recipient_$THIS->ID
フィルタは、WooCommerceのメールシステムにおいて特定のメール通知の受信者アドレスをカスタマイズする際に使用されます。このフィルタは、さまざまな状況においてメール送信先を変更するのに便利であり、以下のような機能を持つ実装でよく使われます。
- 注文確認メールの受信者をカスタマイズ
- カスタム管理者メール通知の追加
- 特定商品購入時の特別なメール送信
- メールアドレスのロギングと監視
- サードパーティサービスとの連携
- 顧客の地域に基づくメールの送信先変更
このフィルタはWooCommerceのバージョンによって異なる場合がありますが、一般的にWooCommerce 2.6以上、WordPressは4.0以上で使用可能です。
フィルタの構文
add_filter('woocommerce_email_recipient_$THIS->ID', 'custom_recipient_email', 10, 2);
パラメータ
$recipient
(string): 送信先のメールアドレス。$order
(WC_Order): 該当するWooCommerceの注文オブジェクト。
戻り値
- 変更された受信者アドレス(string)。
サンプルコード
サンプルコード 1: 注文確認メールに管理者を追加
add_filter('woocommerce_email_recipient_new_order', 'add_admin_to_new_order_email', 10, 2);
function add_admin_to_new_order_email($recipient, $order) {
$recipient .= ', admin@example.com'; // 管理者のメールアドレスを追加
return $recipient;
}
このコードは、新しい注文に関するメールの受信者に管理者のメールアドレスを追加しています。
サンプルコード 2: 特定の商品に基づく受信者の変更
add_filter('woocommerce_email_recipient_new_order', 'custom_recipient_for_specific_product', 10, 2);
function custom_recipient_for_specific_product($recipient, $order) {
foreach ($order->get_items() as $item) {
if ($item->get_product_id() == 123) { // 商品IDが123の場合
$recipient = 'special_recipient@example.com'; // 特定の受信者に変更
break;
}
}
return $recipient;
}
このコードは、特定の商品が注文された場合に、受信者メールアドレスを変更します。
サンプルコード 3: 顧客のメールアドレスをログに記録
add_filter('woocommerce_email_recipient_customer_completed_order', 'log_customer_email', 10, 2);
function log_customer_email($recipient, $order) {
error_log('Customer email: ' . $order->get_billing_email()); // 顧客のメールアドレスをログに記録
return $recipient;
}
このコードは、顧客のメールアドレスをログに記録します。
サンプルコード 4: メールアドレスのドメインをチェック
add_filter('woocommerce_email_recipient_new_order', 'check_email_domain', 10, 2);
function check_email_domain($recipient, $order) {
$domain = substr(strrchr($recipient, "@"), 1);
if ($domain !== 'approved.com') { // 承認されたドメイン以外
$recipient = ''; // 受信者を空にする
}
return $recipient;
}
このコードは、受信者のメールアドレスのドメインを確認し、承認されたドメイン以外であれば受信者を空にします。
サンプルコード 5: 受信者にCCを追加
add_filter('woocommerce_email_recipient_new_order', 'add_cc_to_new_order_email', 10, 2);
function add_cc_to_new_order_email($recipient, $order) {
// CC受信者を追加
add_filter('woocommerce_email_headers', function($headers) {
$headers .= 'Cc: cc@example.com' . "rn"; // CCアドレスの追加
return $headers;
});
return $recipient;
}
このコードは、新しい注文メールの受信者のCCに特定のメールアドレスを追加しています。
この関数のアクションでの使用可能性
アクション | 使用可能 |
---|---|
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 |