
WordPress カスタム投稿タイプのタイトル一覧をContact Form 7にドロップダウン形式で表示
WordPressのカスタム投稿タイプを使用してホームページ制作/Web制作をする際、Contact Form 7使用したお問い合わせフォームやオーダーフォーム、その他フォーム内に動的にカスタム投稿タイプのタイトル一覧を表示し、ユーザーに選択させたい場面があるかと思います。
今回はプラグインは使用せず、Contact Form 7内にSELECT(セレクトボックス)を使用したドロップダウン形式でカスタム投稿タイプタイトル一覧の表示の仕方です。
必要な箇所(Contact Form 7の独自のフォームタグ名、投稿タイプスラッグ)を変更し、下記のコードをfunctions.phpに記入します。
function dynamic_field_values ( $tag, $unused ) { if ( $tag['name'] != 'your-form-tag-name' ) // Contact Form 7内に記入するフィールド名(独自のフォームタグ名) return $tag; $args = array ( 'posts_per_page' => -1, // 全件取得(制限が必要な場合は数値を指定) 'post_type' => 'your_custom_post_type', // カスタム投稿タイプ名(投稿タイプスラッグ) 'orderby' => 'title', // タイトルでソート 'order' => 'ASC', // 昇順 ); $custom_posts = get_posts($args); if ( ! $custom_posts ) return $tag; foreach ( $custom_posts as $custom_post ) { $tag['raw_values'][] = $custom_post->post_title; $tag['values'][] = $custom_post->post_title; $tag['labels'][] = $custom_post->post_title; } return $tag; } add_filter( 'wpcf7_form_tag', 'dynamic_field_values', 30, 2);
次にContact Form 7内に独自のフォームタグを選択させたい箇所に記入します。
[select your-form-tag-name]