我想获取所有带有标题和图像的woocommerce类别。之后,我想将它们显示在首页上。避免foreach循环是因为我的首页设计是这样的。 [在此处输入图片描述] [1]
<?php
$termSlug = array();
$tax_terms = get_terms('product_cat', array('hide_empty' => '0'));
foreach ( $tax_terms as $tax_term ):
$termSlug[] = $tax_term->slug;
endforeach;
$args = array(
'post_type' => 'product', //Post type event
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $termSlug
)
)
);
// The Query
$the_query = new WP_Query( $args );
//echo '<pre>';print_r($the_query);echo "</pre>";
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<?php
}
}else{
?>
<h2 style='font-weight:bold;color:#fff'>Nothing Found</h2>
</div>
<?php } echo '</div>';?>
[1]: https://i.stack.imgur.com/A98em.jpg
答案 0 :(得分:0)
以下代码段将在WooCommerce中获取产品类别。提取类别后,它将循环显示链接和类别图像的类别名称。
$product_categories = get_terms( 'product_cat', 'hide_empty=0' );
if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
foreach ( $product_categories as $category ) {
?>
<div class="category-item">
<h4><a href="<?php echo esc_url( get_term_link( $category ) ); ?>"><?php echo esc_html( $category->name ); ?></a></h4>
<?php
$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
?>
<?php if ( $image ) : ?>
<img src="<?php echo esc_url( $image ); ?>" alt="" />
<?php endif; ?>
</div>
<?php
}
}