概要
wpcf7_mail_tag_replaced_{$type}
フィルタは、Contact Form 7 プラグインにおいて、メールに出力する要素を加工する(type 属性単位)ための柔軟な手段です。このフィルタは、指定したタイプのメールタグが置き換えられる前に、その値を変更することができます。特定の条件に基づいてメールの内容を動的に変更したり、カスタマイズしたりする際に非常に役立ちます。
このフィルタは、多くの場合以下のような機能を実装する際に使用されます。
1. 特定の条件下でメールの内容を変える
2. フォームの応答を基にしたカスタマイズ
3. 値の整形やフォーマットの変更
4. 条件付きで情報を追加
5. デフォルトのメールタグの動作を制御
6. 外部APIから取得したデータの埋め込み
構文
add_filter( 'wpcf7_mail_tag_replaced_{$type}', 'your_function_name', 10, 2 );
パラメータ
{$type}
: 対象となるメールタグのタイプ(例:text
,email
など)。your_function_name
: フィルタを適用するコールバック関数の名前。- 2番目のパラメータには、メールタグの値と送信されたフォームデータが渡されます。
戻り値
- フィルタを適用した後に変更されたメールタグの値を返します。
使用可能なプラグインバージョン
- Contact Form 7 バージョン 5.0以上
使用可能なWordPressのバージョン
- WordPress バージョン 4.9以上
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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( 'wpcf7_mail_tag_replaced_text', 'add_date_to_email', 10, 2 );
function add_date_to_email( $value, $form ) {
return $value . ' - ' . date( 'Y/m/d' );
}
このサンプルコードは、テキストメールタグの値に現在の日付を追加します。
サンプルコード 2: 条件に基づいてメール本文を変更する
add_filter( 'wpcf7_mail_tag_replaced_email', 'conditional_email_content', 10, 2 );
function conditional_email_content( $value, $form ) {
if ( isset( $_POST['your-custom-field'] ) && $_POST['your-custom-field'] === 'yes' ) {
return '特別なオファーがあります!';
}
return $value;
}
このコードは、カスタムフィールドの値に基づいてメールの内容を変更します。
サンプルコード 3: 整形した電話番号を出力する
add_filter( 'wpcf7_mail_tag_replaced_tel', 'format_phone_number', 10, 2 );
function format_phone_number( $value, $form ) {
// 電話番号を整形 (例: 1234567890 → (123) 456-7890)
return '(' . substr( $value, 0, 3 ) . ') ' . substr( $value, 3, 3 ) . '-' . substr( $value, 6 );
}
このコードは、電話番号のフォーマットを整形して出力します。
サンプルコード 4: ユーザーのIPアドレスを追加する
add_filter( 'wpcf7_mail_tag_replaced_text', 'add_user_ip_address', 10, 2 );
function add_user_ip_address( $value, $form ) {
return $value . ' - User IP: ' . $_SERVER['REMOTE_ADDR'];
}
このサンプルは、メール本文に送信者のIPアドレスを追加します。
サンプルコード 5: カスタムユーザーメタをメールに追加する
add_filter( 'wpcf7_mail_tag_replaced_text', 'add_custom_user_meta', 10, 2 );
function add_custom_user_meta( $value, $form ) {
if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
$custom_meta = get_user_meta( $user_id, 'custom_meta_key', true );
return $value . ' - Custom Info: ' . $custom_meta;
}
return $value;
}
このコードは、ログインしたユーザーのカスタムメタデータをメールに追加します。