概要
wpcf7_default_template
フィルタは、WordPress の Contact Form 7 プラグインで使用される重要なフィルタであり、フォームの各設定項目のデフォルト値を加工する際に用いられます。このフィルタを使用することで、フォームの見た目や動作をカスタマイズすることができます。具体的な使い方としては以下のようなケースが考えられます。
- デフォルトのフォームテンプレートに独自のフィールドを追加する
- フォームフィールドのラベルを言語に応じて変更する
- 各フィールドの既定の属性(クラスやスタイルなど)を変更する
- デフォルトのバリデーションルールをカスタマイズする
- スパム防止機能を追加する
- エラーメッセージのカスタマイズ
構文
add_filter( 'wpcf7_default_template', 'my_custom_default_template' );
パラメータ
$template
: 既定のフォームテンプレート
戻り値
- カスタマイズしたテンプレートを返す文字列。
バージョン
- Contact Form 7: 5.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 add_custom_class_to_fields( $template ) {
$template = str_replace( 'class: your-class-name', 'class: your-custom-class-name', $template );
return $template;
}
add_filter( 'wpcf7_default_template', 'add_custom_class_to_fields' );
このサンプルコードは、既定のフォームフィールドにカスタムクラスを追加しています。
引用ページ
https://example.com
サンプル2: フィールドのラベルを変更する
function change_field_labels( $template ) {
$template = str_replace( 'Your Name', 'フルネーム', $template );
return $template;
}
add_filter( 'wpcf7_default_template', 'change_field_labels' );
このサンプルコードは、フィールドのラベルを英語から日本語に変更しています。
引用ページ
https://example.com
サンプル3: デフォルトのバリデーションルールを変更する
function modify_validation_rules( $template ) {
$template = str_replace( 'required', 'required minlength: 3', $template );
return $template;
}
add_filter( 'wpcf7_default_template', 'modify_validation_rules' );
このサンプルコードでは、デフォルトのバリデーションルールに最小文字数制限を追加しています。
引用ページ
https://example.com
サンプル4: スパム防止機能を追加する
function add_spam_prevention( $template ) {
$template .= '<input type="text" name="name_of_spam_prevention_field" style="display:none;">';
return $template;
}
add_filter( 'wpcf7_default_template', 'add_spam_prevention' );
このサンプルコードは、スパムボットを防ぐための隠しフィールドを追加しています。
引用ページ
https://example.com
サンプル5: エラーメッセージをカスタマイズする
function customize_error_messages( $template ) {
$template = str_replace( 'Sorry, your submission has failed.', '申し訳ありませんが、送信に失敗しました。', $template );
return $template;
}
add_filter( 'wpcf7_default_template', 'customize_error_messages' );
このサンプルコードでは、エラーメッセージをカスタマイズして日本語にしています。
引用ページ
https://example.com