MWフォーム プルダウンの連動

情報を追記している場合はありますが、古い情報を訂正はしていませんので、公開年月日を参照してください。プラグイン・タグ、いずれもワードプレス・PHPのバージョン等によって動作しない場合もあります。

エリアと店舗のプルダウンを連動させる。エリアはタクソノミーで店舗はそれに属する店舗。選択は必須。
フォームのショートコードは children=”,” post_raw=”true” として必要なidを入れる。

functionsの関数でそれぞれ動的に選択肢を入れる。必須を有効にするために1行目に$children[”] = ‘選択’;

function contact_form_select($children, $atts)
{
 if ($atts['name'] === 'エリア') {
  $children = [];
	 $args = array('hide_empty' => false);
  $terms = get_terms('area',$args); if( $terms && !is_wp_error($terms) ){ $children[''] = '選択';
	  foreach ( $terms as $term ) {
		  $children[$term->slug] = $term->name;
   }
 } }
	 if ($atts['name'] === '店舗') {
  $children = [];
	 $args = array('post_type' => 'shop', 'posts_per_page' => -1); 
		 $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) {
			 $children[''] = '選択';
			 while ( $the_query->have_posts() ) : $the_query->the_post();
			 $title = get_the_title();
			 $children[$title] = $title;
			 endwhile; }
	 }
 return $children;
}
add_filter('mwform_choices_mw-wp-form-xx', 'contact_form_select', 10, 2); 

スクリプトでエリアを選択したときの設定。Allareaはタームを選択させていないので、全投稿を読み込み。

<script type="text/javascript">
var array = new Array();
<?php $args = array('post_type' => 'shop', 'posts_per_page' => -1); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ): ?>
array["allarea"] = new Array(
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  {val:"<?php the_title(); ?>", label:"<?php the_title(); ?>"},
  <?php endwhile; ?>
);<?php endif; wp_reset_postdata(); ?>
<?php $terms = get_terms('area'); if( $terms && !is_wp_error($terms) ){ ?><?php foreach ( $terms as $term ) { ?>
array["<?php echo $term->slug; ?>"] = [
<?php $args = array('post_type' => 'shop', 'posts_per_page' => -1, 'taxonomy' => 'area', 'area' => $term->slug); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  {val:"<?php the_title(); ?>", label:"<?php the_title(); ?>"},
  <?php endwhile; ?>
];<?php endif; wp_reset_postdata(); ?><?php } ?><?php } ?>

document.getElementById('area').onchange = function(){
  shop = document.getElementById("shop");
  shop.options.length = 0
  var changedPref = area.value;
  for (let i = 0; i < array[changedPref].length; i++) {
    var op = document.createElement("option");
    value = array[changedPref][i]
    op.value = value.val;
    op.text = value.label;
    shop.appendChild(op);
  }
}
</script>