Adding URL Query parameters to WP_Query

I am implementing a product filter for my WooCommerce store. I want to filter the product base on some attributes, such as color, which can be retrieve from the URL query parameters. For example, if the path is /product-category/clothing/?filter_color=16, then only product with color ID = 16 would be shown.

Right now this feature seems to be available when I added the widget from YITH WooCommerce Ajax Product Filter Plugin. However, I do not want to use this plugin because it is not consistent with other features and would like to implement my own. But I couldn’t find how YITH achieve this.

Read More

I want to make this work for both the main Loop and my custom Loops.
By main loop I am referring to this:

<?php while ( have_posts() ) : the_post(); ?>
    <?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>

And my custom loops:

                $args = array(
                    'post_type' => 'product',
                    'posts_per_page' => 12,
                    'product_cat' => $category->slug,
                    'orderby' => 'menu_order',
                    'order' => 'ASC'
                    );
                $loop = new WP_Query( $args );
                if ( $loop->have_posts() ) { ...

Related posts

1 comment

  1. You can check the query, retrieve the value of the color, check if they match and if so then display the product. Have a look at:

    <?php while ( have_posts() ) : the_post(); ?>
        <?php 
        if(isset($_GET['filter_color']) //check if the filter color is set
        {
            $color=$_GET['filter_color']; 
            $productColor = get_the_terms($product->ID,'pa_color');
    
            if ($color == $productColor) //if the filter color matches with the color of the prodct
                wc_get_template_part( 'content', 'product' ); //then show the product
        }
    
        ?>
    <?php endwhile; // end of the loop. ?>
    

    Same approach applies for your custom loops.

Comments are closed.