Contactform7のセレクトの選択肢を、カスタム投稿で投稿した記事のタイトル一覧にしたい場合
以下の方法で動的にプルダウンを生成できる
2つの方法
①一つ目
→しかしこの方法はcontactform7で申し込み完了にならなかったり、プラグインが更新できなくなるなど不具合があった
function.phpに以下を記載
<?php
//コンタクトフォームのセレクトのプルダウン項目を動的に表示
function add_menu_name(){
ob_start();
$args = array(
'post_type' => 'menu', //menuというカスタム投稿をもとに動的にプルダウンを生成
'order' => 'ASC',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'orijinal_menu', //タクソノミーを指定
'field' => 'slug', //ターム名をスラッグで指定する
'terms' => 'gardenview', //表示したいレスランをスラッグで指定
'operator' => 'IN'
),
),
);
?>
<select name="menu_name" id="menu-select">
<?php
$the_query = new WP_Query($args);
$i = 0;
if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post();
?>
<option value="<?php echo $i; ?>"><?php the_title(); ?><option>
<?php
$i++;
endwhile;
endif;
return ob_get_clean();
}
?>
</select>
<?php
wpcf7_add_form_tag('menu_name', 'add_menu_name');
// この場合「menu_name」がショートコード名
contactform7内でselectを設置したい箇所に [menu_name] を書くと上記雨function.phpの記述が表示される
②二つ目
こちらは問題なく稼働した
function.phpに以下を記載
<?php
function filter_wpcf7_form_tag( $scanned_tag, $replace ) {
if(!empty($scanned_tag)){
//nameで判別
if($scanned_tag['name'] == 'menu_name'){
//カスタム投稿タイプの取得
global $post;
$args = array(
'posts_per_page' => -1,
'post_type' => 'menu',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'orijinal_themes_cat', //タクソノミーを指定
'field' => 'slug', //ターム名をスラッグで指定する
'terms' => 'gardenview', //表示したいタームをスラッグで指定
'operator' => 'IN'
),
),
);
$customPosts = get_posts($args);
if($customPosts){
foreach($customPosts as $post){
setup_postdata( $post );
$title = get_the_title();
//$scanned_tagに情報を追加
$scanned_tag['values'][] = $title;
$scanned_tag['labels'][] = $title;
}
}
wp_reset_postdata();
}
}
return $scanned_tag;
};
add_filter( 'wpcf7_form_tag', 'filter_wpcf7_form_tag', 11, 2 );
?>
contactform7内でselectを設置したい箇所に [select* menu_name] を書くと上記雨function.phpの記述が表示される

