Woocommerce每个类别的产品循环分开

问题描述 投票:1回答:2

在我的Woocommerce商店的主要商店页面(archive-product.php)上,我希望能够显示所有产品,但是按类别将它们分开。所以我需要能够为每个产品类别创建一个循环。

对于视觉参考,这是我想要实现的:for reference

每个灰色块代表一个新类别,并将遍历该类别中的产品。

有没有办法实现这个目标?

php wordpress woocommerce
2个回答
1
投票

正如您在评论中提到的,如果您不需要任何分页,要列出所有按类别划分的产品,您可以首先使用get_terms()函数遍历各个类别,并获取每次迭代所需的任何信息(例如:类别名称) ,然后为每个类别创建一个自定义查询并显示查询的产品,这样的内容将为您提供您正在尝试执行的操作:

<?php
foreach( get_terms( array( 'taxonomy' => 'product_cat' ) ) as $category ) :
    $products_loop = new WP_Query( array(
        'post_type' => 'product',

        'showposts' => -1,

        'tax_query' => array_merge( array(
            'relation'  => 'AND',
            array(
                'taxonomy' => 'product_cat',
                'terms'    => array( $category->term_id ),
                'field'   => 'term_id'
            )
        ), WC()->query->get_tax_query() ),

        'meta_query' => array_merge( array(

            // You can optionally add extra meta queries here

        ), WC()->query->get_meta_query() )
    ) );

?>
    <h2 class="category-title"><?php echo $category->name; ?></h2>

    <?php
    while ( $products_loop->have_posts() ) {
        $products_loop->the_post();
        /**
         * woocommerce_shop_loop hook.
         *
         * @hooked WC_Structured_Data::generate_product_data() - 10
         */
        do_action( 'woocommerce_shop_loop' );
        wc_get_template_part( 'content', 'product' );
    }
    wp_reset_postdata(); ?>
<?php endforeach; ?>

0
投票

在您的页面模板上试用此代码。它将获得每个类别的Woocommerce独立产品循环的结果。

$taxonomy     = 'product_cat';
  $orderby      = 'name';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
		
		
	//get product
		$args = array(
  'post_type'      => 'product', 
	'product_cat' => $cat->name,
  'posts_per_page' => $count,
  'paged'          => $paged,
);
$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) { 
    $query->the_post();
        ?>
		<span class="title"><h2>  <?php the_title(); ?> </h2></span>
       	<?php
    }
    wp_reset_postdata();
}

	}
 }
© www.soinside.com 2019 - 2024. All rights reserved.