概要
woocommerce_email
フィルタは、WooCommerceが送信するさまざまなメールテンプレートをカスタマイズするために使用されるフックです。このフックを使うことで、開発者はメールの内容や形式を変更できます。具体的には、次のような機能を実装する際によく使われます。
- メール本文のカスタマイズ
- メールの件名変更
- 送信先アドレスの変更
- メールテンプレートの内容の追加
- HTMLまたはテキスト形式の調整
- 他のプラグインや機能との統合
構文は以下の通りです。
add_filter( 'woocommerce_email', 'your_function_name', 10, 2 );
パラメータ
woocommerce_email
はフィルタ名で、メールの種類(例:新しい注文、顧客の注文確定など)を指定する識別子です。your_function_name
は、フィルタを適用する関数の名前です。- 第二引数は通常、メールオブジェクトとデータが渡されます。
戻り値
- フィルタを通して処理されたメールコンテンツやメタ情報が返されます。
使用可能なWooCommerceのバージョン
- WooCommerce v3.0以降
使用可能なWordPressのバージョン
- WordPress v4.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: メールの本文をカスタマイズ
このサンプルコードは、WooCommerceの注文確認メールの本文に「ありがとう」のメッセージを追加します。
add_filter( 'woocommerce_email_order_details', 'custom_email_order_details', 10, 4 );
function custom_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
echo '<p>ありがとう!あなたの注文を受け付けました。</p>';
}
引用元: https://woocommerce.com/document/managing-emails/
サンプル2: メールの件名を変更
このコードは、顧客への新しい注文メールの件名を変更します。
add_filter( 'woocommerce_email_subject_customer_new_order', 'custom_woocommerce_email_subject', 10, 2 );
function custom_woocommerce_email_subject( $subject, $order ) {
return '新しい注文がありました - ' . $order->get_order_number();
}
引用元: https://woocommerce.com/document/managing-emails/
サンプル3: メールの送信先を変更
このコードスニペットは、管理者に送信される新しい注文メールの宛先をカスタマイズします。
add_filter( 'woocommerce_email Recipient_new_order', 'custom_new_order_recipient', 1, 2 );
function custom_new_order_recipient( $recipient, $order ) {
return 'you@yourdomain.com,another@domain.com';
}
引用元: https://woocommerce.com/document/managing-emails/
サンプル4: メールテンプレートにカスタムフィールドを追加
このコードは、メールにカスタムフィールドの値を追加する例です。
add_filter( 'woocommerce_email_order_meta', 'add_custom_order_meta_to_email', 10, 3 );
function add_custom_order_meta_to_email( $fields, $sent_to_admin, $order ) {
$fields['custom_field'] = get_post_meta( $order->get_id(), '_custom_field', true );
return $fields;
}
引用元: https://woocommerce.com/document/managing-emails/
サンプル5: メールのフォーマットをカスタマイズ
このコードスニペットは、新しい注文メールをテキスト形式にフォーマットします。
add_filter( 'woocommerce_email_content_type', 'set_email_content_type' );
function set_email_content_type() {
return 'text/plain';
}
引用元: https://woocommerce.com/document/managing-emails/
以上のサンプルコードを使用すると、WooCommerceのメールシステムを様々にカスタマイズすることができます。