2

我正在尝试设置一个自定义循环,循环遍历分配给产品类别的产品,但它似乎不起作用。

我的类别设置:

工厂直销 - FD1 - FD2 - FD3

我希望我的循环显示属于 ID 为 84 的 Factory Direct 的任何儿童类别的产品。

我尝试在我的模板中对此进行编码:

<ul class="products factoryloop">
    <?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12,
            'cat' => 84
            );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
                woocommerce_get_template_part( 'content', 'product' );
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>
</ul><!--/.products-->

我尝试将 ID 从 84 更改为特定类别(例如 FD1,其 ID 为 24),但它仍然无法正常工作。

有什么想法/建议吗?

如果我删除 WP_Query 中的 cat 参数,它会循环遍历产品,但我无法指定我的循环。

谢谢!

4

2 回答 2

1

您需要先获取该类别的所有子项,并将它们包含在cat查询的参数中。

<ul class="products factoryloop">
    <?php
        $parentCat = 84;
        $children = get_categories(array('child_of'=>$parentCat));

        $childs = array($parentCat);
        foreach($children as $child){
            $childs[] = $child->cat_ID;
        }
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12,
            'cat' => implode(',', $childs);
            );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
                woocommerce_get_template_part( 'content', 'product' );
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>
</ul><!--/.products-->
于 2013-09-17T23:29:37.740 回答
1

这就是我用query_posts做的,你应该用WP_Query做同样的事情。

function getCategoryByParent ($id) {
    $args=array(
      'orderby' => 'name',
      'parent' => $id,
      'hide_empty' => false,
      'taxonomy' => 'product_cat',
      'order' => 'ASC',
      );
    $categories=get_categories($args);
    return $categories;
}
$cats = getCategoryByParent(84);
query_posts( array( 'paged' => $paged, 'posts_per_page' => 9, 'post_type' => 'product', 'post_status' => 'publish' ,  'taxonomy' => 'product_cat', 'tax_query' => array( 
            array(
              'taxonomy' => 'product_cat',
              'field' => 'id',
              'terms' => $cats
            ))));

希望对您有所帮助,阿萨夫。

于 2013-09-17T23:57:20.153 回答