LoginSignup
ponpon23
@ponpon23

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

wordpressでAjaxを使った絞り込み検索をしたい。

解決したいこと

参考にしたサイトはこちらです
https://webfun-style.com/wordpress-custom-search/
これに全てを選択チェックボックスを用意しましたが、挙動がうまくいきません。
実装したいことは以下です。

  • 全てを選択チェックボックスを用意し、それをチェックしたら全てチェックされ、且つ全てが表示された絞り込み検索を実装したい
  • 全てを選択チェックボックスが外れたら、全てのチェックボックスが外れます
  • 全てを選択チェックボックス選択されてる時、他のチェックボックスが外れたら、全てを選択チェックボックスも外したい
  • いずれも全てAjaxが動く事が前提です

発生している問題・エラー

現在は1箇所でもすべてを選択チェック以外のチェックボックスをいれたら、全てを選択チェックボックスが動きません

該当するソースコード

main.js
jQuery(function($){
    function customSearch(){
        // 1. フォームのデータを生成
        var form = $('#search-result form').get()[0];
        var formData = new FormData(form);
        formData.append('action', 'custom_search');

        // 2. Ajaxを行う
        $.ajax({
            type: 'POST',
            url: ajaxurl,
            data: formData,
            processData: false,
            contentType: false,
            success: function(data){
                $('#search-result').prop('outerHTML', data);
                $('.submit-button').attr('type', 'button');
            }
        });
        return false;
    };

    // 3. クリックイベントの設定
    $(document).on('change', 'input[name="search_price[]"], input[name="search_area[]"], input[name="search_area_all[]"]', function(){
        // チェックの状態に関係なく customSearch() を呼び出す
        customSearch();
    });

    // 個々のチェックボックスの変更イベントを設定
    $('input[name="search_price[]"], input[name="search_area[]"], input[name="search_area_all[]"]').on('change', function(){
        // 全てのチェックボックスの数
        var totalCheckboxes = $('input[name="search_price[]"], input[name="search_area[]"], input[name="search_area_all[]"]').length;
        // チェックされたチェックボックスの数
        var checkedCheckboxes = $('input[name="search_price[]"]:checked, input[name="search_area[]"]:checked, input[name="search_area_all[]"]:checked').length;
        // 全てを選択するチェックボックスの状態を設定
        $('#select-all-checkbox').prop('checked', totalCheckboxes === checkedCheckboxes);
        // Ajaxを実行
        customSearch();
    });
});



// 全てを選択するチェックボックス
let selectAllCheckbox = document.getElementById('industry_checkAll');

// 他の全てのチェックボックス
let otherCheckboxes = document.querySelectorAll('.check-industry');

// 全てを選択するチェックボックスの状態が変わったときの処理
selectAllCheckbox.addEventListener('change', function() {
for(let checkbox of otherCheckboxes) {
checkbox.checked = this.checked;
}
});

// 他のチェックボックスの状態が変わったときの処理
for(let checkbox of otherCheckboxes) {
checkbox.addEventListener('change', function() {
if(!this.checked) {
selectAllCheckbox.checked = false;
} else {
let allChecked = true;
for(let checkbox of otherCheckboxes) {
if(!checkbox.checked) {
allChecked = false;
break;
}
}
selectAllCheckbox.checked = allChecked;
}
});
}
custom-search.php
<!-- 1. 検索条件の取得と変数の設定 -->
<?php
  $args = array(
    'post_type' => 'design',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'orderby' => 'date',
    'order' => 'DESC'
  );

  if(!empty($_POST['search_area'])) {
    foreach($_POST['search_area'] as $value) {
      $search_area[] = htmlspecialchars($value, ENT_QUOTES);
    }
    $tax_query_args[] = array(
                           'taxonomy' => 'area',
                           'terms' => $search_area,
                           'field' => 'slug',
                           'operator' => 'IN'
                        );
  }

  if(!empty($_POST['search_price'])) {
    foreach($_POST['search_price'] as $value) {
      $search_price[] = htmlspecialchars($value, ENT_QUOTES);
    }

    $tax_query_args[] = array(
                           'taxonomy' => 'work',
                           'terms' => $search_price,
                           'field' => 'slug',
                           'operator' => 'IN'
                        );
  }

  if(!empty($_POST['search_area']) || !empty($_POST['search_price'])) {
    $args += array('tax_query' => array($tax_query_args));
  }
?>

<!-- 2. 検索フォームの表示 -->
<!-- (追記1)Ajaxの結果を表示する領域を設定 -->
<div id="search-result">
<div class="search">
<form method="post" action="<?php echo esc_url(home_url() . $_SERVER['REQUEST_URI']); ?>">
<div class="checkbox">

<div class="condition-title">エリア</div>
<div class="condition">
  <label class=""><input id="industry_checkAll" class="" type="checkbox" name="industry" value="">すべて</label><!-- /.search-check -->
  <?php
    $areas = get_terms('area', Array('hide_empty' => false));
    foreach($areas as $area):
      $checked = "";
      if(in_array($area->slug, $search_area)) $checked = " checked";
  ?>
  <label class="search-check">
  <input class="search-check-input check-industry" type="checkbox" name="search_area[]" value="<?php echo esc_attr($area->slug); ?>"<?php echo $checked; ?>>
  <?php echo esc_html($area->name); ?>
  </label>
  <?php endforeach; ?>
</div>

<div class="condition-title">価格帯</div>
<div class="condition">
  <?php
    $prices = get_terms('work', Array('hide_empty' => false, 'orderby' => 'slug'));
    foreach($prices as $price):
      $checked = "";
      if(in_array($price->slug, $search_price)) $checked = " checked";
  ?>
  <label>
  <input type="checkbox" name="search_price[]" value="<?php echo esc_attr($price->slug); ?>"<?php echo $checked; ?>>
  <?php echo esc_html($price->name); ?>
  </label>
  <?php endforeach; ?>
</div>
		

	
</div>

<input type="submit" value="検索" class="submit-button">

<!-- (追記2)nonceのhiddenタグを生成 -->
<?php wp_nonce_field('my-ajax-nonce', 'nonce'); ?>
</form>

<?php
  $the_query = new WP_Query($args);
  if($the_query->have_posts()) :
?>	
<div class="result">
<?php
  while($the_query->have_posts()) :
    $the_query->the_post();
?>			
<div class="article">
  <a href="<?php the_permalink(); ?>">
  <?php the_post_thumbnail('medium'); ?>
  <div><?php the_title(); ?></div>
  </a>
</div>
<?php endwhile; wp_reset_postdata(); ?>
</div>
<?php else : ?>
<p>該当する物件はありませんでした。</p>
<?php endif; ?>

</div>

<!-- (追記3)Ajaxで使う変数の設定とスクリプトを読み込み -->
<script>
    var ajaxurl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
</script>
<script src="<?php echo esc_url(get_stylesheet_directory_uri() . '/js/main.js'); ?>"></script>

</div>
functions.php
// Ajaxで検索結果を表示する関数
function custom_search() {
    $nonce = $_REQUEST['nonce'];
    if(wp_verify_nonce($nonce, 'my-ajax-nonce')) {
        get_template_part('custom-search');
    }
    die();
}
add_action('wp_ajax_custom_search', 'custom_search');
add_action('wp_ajax_nopriv_custom_search', 'custom_search');

例)

自分で試したこと

ここに問題・エラーに対して試したことを独自に調べたりChatGPTにも訪ねましたが、だめでした。
現在のmain.jsはChatGPTの答えです。

よろしくお願いいたします。

0

Your answer might help someone💌