javascriptjquerywordpresswoocommercefacetwp

FacetWP: Show labels only if facet has options


I want to show labels only if the facet has any options. Therefore I tried the following code:

<script>
(function($) {
    $(document).on('facetwp-loaded', function() {
        $('.facetwp-facet').each(function() {
            var facet_name = $(this).attr('data-name');
            var facet_label = FWP.settings.labels[facet_name];

            if ($('.facet-label[data-for="' + facet_name + '"]').length < 1 && $(this).children()
                .length > 0) {
                $(this).before('<p class="h5 facet-label" data-for="' + facet_name + '">' + facet_label + '</p>');
            }
        });
    });
})(jQuery);
</script>

It works but only if I reload the page with active filters. If I change the filter, the labels stay.

Is there any option to ask if the are a new filters after a click?


Solution

  • The plugin author gave me an hint for a solution:

    <script>
        (function($) {
            $(document).on('facetwp-loaded', function() {
                $('.facetwp-facet').each(function() {
                    var facet_name = $(this).attr('data-name');
                    var facet_label = FWP.settings.labels[facet_name];
                    if ( 'undefined' !== typeof FWP.settings.num_choices[facet_name] && FWP.settings.num_choices[facet_name] > 0 && $('.facet-label[data-for="' + facet_name + '"]').length < 1 ) {
                        $(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
                    } else if ( 'undefined' !== typeof FWP.settings.num_choices[facet_name] && !FWP.settings.num_choices[facet_name] > 0 ) {
                        $('.facet-label[data-for="' + facet_name + '"]').remove();
                    } 
                });
            });
        })(jQuery);
        </script>