Site icon Hip-Hop Website Design and Development

How to create a WooCommerce Product filter based on PHP foreach

I am trying to create my own WooCommerce Product Attribute filter, using a PHP foreach. When using the regular WordPress Widgets ‘Filter Products on Attribute’ every visible product attribute (and their values) in the filterform is based on the given products on that archive-page. For example when you´re viewing the category (archive page) "Clothes" you only see the product attribute values that have been added to those visible products.

I already succeeded in creating a foreach to loop through the ‘attribute values’. But my foreach outputs all values. Any time. It does not check which products do contain the attribute values I foreach. I hope I’m clear in my explaination.

My code:

    <? $product_attribute = "pa_color";?>
    <? $get_pa_values = get_terms($product_attribute);?>
        <div class="heading">Filter on Color:</div>
        <ul class="list_labels">
            <? foreach($get_pa_values as $index => $color):?>
                <? $color_slug = $color->slug;?>
                <li class="badge">
                    <a href="?filter_color=<?=$color_slug;?>">
                        <?= $color->name;?>
                    </a>
                </li>
            <? endforeach;?>
        </ul>

    <? $product_attribute_size = "pa_size";?>
    <? $get_pa_values_size = get_terms($product_attribute_size);?>
        <div class="heading">Filter on Color:</div>
        <ul class="list_labels">
            <? foreach($get_pa_values_size as $index => $size):?>
                <? $size_slug = $size->slug;?>
                <li class="badge">
                    <a href="?filter_size=<?=$size_slug;?>">
                        <?= $size->name;?>
                    </a>
                </li>
            <? endforeach;?>
        </ul>

How to create a foreach that depends on the given products. In fact I am trying to achive exactly what the regular Widgets function does. So after clicking on the "Color attribute" value "Red" (for example) I want the next foreach (Attribute: Size) to check which from the visible products does have a Size that can be filtered.

Also when using multiple filters, my URL is not working, when I’m using:

        <a href="?filter_color=<?=$color_slug;?>">

Thanks a lot in advance.