将URL查询参数添加到WP_Query

时间:2015-09-30 03:31:11

标签: php wordpress woocommerce wp-query

我正在为我的WooCommerce商店实施产品过滤器。我想根据一些属性过滤产品,例如颜色,可以从URL查询参数中检索。例如,如果路径为/product-category/clothing/?filter_color=16,则仅显示颜色ID = 16的产品。

现在,当我从YITH WooCommerce Ajax Product Filter插件添加小部件时,此功能似乎可用。但是,我不想使用此插件,因为它与其他功能不一致,并且希望实现我自己的功能。但我无法找到YITH如何实现这一目标。

我想让它适用于主循环和我的自定义循环。 通过主循环,我指的是:

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

我的自定义循环:

                $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() ) { ...

1 个答案:

答案 0 :(得分:2)

您可以检查查询,检索颜色的值,检查它们是否匹配,如果匹配,则显示产品。看看:

<?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. ?>

同样的方法适用于您的自定义循环。

相关问题