FacetWP checkbox facet select all

<?php

/**
 * Attaches a click event to a div that selects all of a Checkboxes facet's available options and triggers a refresh.
 * Change "my_facet name" to the name of your facet
 * Add this HTML above your facet:
 * <div class="facetwp-checkbox select-all">Select all</div>
 * It creates a div that looks like facet checkboxes. Note that this needs to be outside the facet itself to work.
 * The second part checks the 'Select all' checkbox if the page loads with all choices already selected.
 * See: https://facetwp.com/help-center/facets/facet-types/checkboxes/#how-to-create-a-select-all-checkbox
 */

add_action( 'facetwp_scripts', function() { ?>
  <script>

    (function($) {

      const facet_name = 'my_facet name'; // Replace 'my_facet_name' with the name of your Checkboxes facet
      const select_all_selector = '.facetwp-checkbox.select-all'; // Adapt the CSS selector so it corresponds with your "Select all" HTML element

      $().on('click', select_all_selector, function() {

        if ( $(this).hasClass('checked') ) {
          FWP.reset(facet_name);
        } else {
          var available = [];
          $( '.facetwp-facet-' + facet_name + ' .facetwp-checkbox' ).each( function () {
            available.push( $(this).attr( 'data-value' ) );
          });
          // Use the variable for FWP.facets[]
          FWP.facets[facet_name] = available;
          FWP.is_reset = true; // don't parse facets
          FWP.refresh();
        }
        $(this).toggleClass('checked');

      });

      // Set 'Select all' class to 'checked' if on page load all choices are already selected
      document.addEventListener('facetwp-loaded', function() {

        if ( !FWP.loaded ) { // on first page load

          // Get the total number facet choices in this facet
          const total_choices = $('.facetwp-facet-checkboxes .facetwp-checkbox').nodes.length;

          // Get the number of currently selected choices for this facet
          const currently_selected = FWP.facets[facet_name] ? FWP.facets[facet_name].length : 0;

          // Check if the total available choices match the currently selected choices,
          // also ensure that at least one choice is selected (to avoid checking 'select all' when nothing is selected).
          if (total_choices > 0 && total_choices === currently_selected) {
            $(select_all_selector).addClass('checked');
          } else {
            $(select_all_selector).removeClass('checked');
          }

        }

      });

    })(fUtil);

  </script>
<?php });