ショートコード属性からデフォルト値を取得する

[contact-form-7 ...] ショートコードの属性値をフォームで使えたら便利なのに、と思うことがあるかもしれません。

そんな時はフォームタグのオプションとして default:shortcode_attr をセットしましょう。ショートコードの属性からデフォルト値を取得するようになります。

例として、宛先メールアドレスのための “destination-email” という名前の入力項目があるとしましょう:

[email* destination-email]

ショートコードの属性からデフォルト値を得るために、このフォームタグに default:shortcode_attr オプションを追加します:

[email* destination-email default:shortcode_attr]

それから、入力項目と同じ名前(この場合は “destination-email”)の属性をコンタクトフォームのショートコードに追加します:

[contact-form-7 id="123" title="Contact Form" destination-email="xxxxxx@example.com"]

これで全部? 残念ながらもう一つ必要なステップがあります。

通常、WordPress のショートコードはあらかじめ定義された属性しか取らないようになっています。なので前もって使用する属性を登録する必要があります。

次のコードを使用しているテーマの functions.php ファイルに追加してください:

add_filter( 'shortcode_atts_wpcf7', 'custom_shortcode_atts_wpcf7_filter', 10, 3 );

function custom_shortcode_atts_wpcf7_filter( $out, $pairs, $atts ) {
	$my_attr = 'destination-email';

	if ( isset( $atts[$my_attr] ) ) {
		$out[$my_attr] = $atts[$my_attr];
	}

	return $out;
}

これで全部です! 項目に “xxxxxx@example.com” が入力されているのが確認できるはずです。

WordPress のお問い合わせフォームプラグイン。シンプル、でも柔軟。