概要
wpcf7_mail_tag_replaced
フィルタは、Contact Form 7 プラグインを使用して作成されたフォームから送信されるメールの内容を操作する際に使用されます。このフィルタは、メールに出力する要素を加工するために非常に便利です。たとえば、特定のメールタグの内容を変更したり、新しい情報を追加したりできます。よく使われるケースには以下のようなものがあります。
- メール本文の特定の部分をカスタマイズする
- 送信者からの情報をフォーマットする
- 特定の条件に基づいてメールの内容を変更する
- メール送信後に特別な通知を追加する
- フォームのフィールド値を加工する
- タグを使って動的に値を生成する
構文
add_filter('wpcf7_mail_tag_replaced', 'custom_mail_tag_replaced', 10, 3);
パラメータ
string $text
: 置き換えられたメールタグのテキストstring $tag
: 置き換え対象のメールタグの名前WPCF7_ContactForm $contact_form
: 現在のフォームのインスタンス
戻り値
string
: 変更されたメールタグのテキスト
使用可能なバージョン
- Contact Form 7 バージョン : 5.0 以降
- WordPress バージョン : 4.9 以降
サンプルコード
サンプル1
add_filter('wpcf7_mail_tag_replaced', 'custom_subject_mail_tag', 10, 3);
function custom_subject_mail_tag($text, $tag, $contact_form) {
if ($tag === 'custom_subject') {
return 'カスタム件名:' . $text;
}
return $text;
}
このサンプルコードは、custom_subject
というメールタグが置き換えられる際に、カスタム件名を追加します。
サンプル2
add_filter('wpcf7_mail_tag_replaced', 'format_phone_number', 10, 3);
function format_phone_number($text, $tag, $contact_form) {
if ($tag === 'phone') {
return preg_replace('/(d{3})(d{3})(d{4})/', '($1) $2-$3', $text);
}
return $text;
}
このコードは、電話番号を特定のフォーマット(例:'(123) 456-7890’)に変更します。
サンプル3
add_filter('wpcf7_mail_tag_replaced', 'append_signature_mail_tag', 10, 3);
function append_signature_mail_tag($text, $tag, $contact_form) {
if ($tag === 'message') {
return $text . "nn---n送信者による署名";
}
return $text;
}
このコードは、メッセージの最後に署名を追加します。
サンプル4
add_filter('wpcf7_mail_tag_replaced', 'conditional_content_mail_tag', 10, 3);
function conditional_content_mail_tag($text, $tag, $contact_form) {
if ($tag === 'special_offer' && some_condition()) {
return '特別オファー!';
}
return $text;
}
このサンプルでは、特定の条件に基づいてオファーをメールに追加します。
サンプル5
add_filter('wpcf7_mail_tag_replaced', 'dynamic_value_mail_tag', 10, 3);
function dynamic_value_mail_tag($text, $tag, $contact_form) {
if ($tag === 'today_date') {
return date('Y-m-d');
}
return $text;
}
このコードは、today_date
タグが置き換えられる際に現在の日付を追加します。
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |
以上が wpcf7_mail_tag_replaced
フィルタの詳細な解説とサンプルコードです。上記のコードはすべて著作権フリーのものです。また、サンプルコードの内容は、Contact Form 7 プラグインのニーズに応じて簡単にカスタマイズできます。