Reputation: 17
I want to fetch all woocommerce categories with title and images. and after that, I wanted to display them on a front-page. Avoiding foreach loop becuase my front-page design is something like this one. [enter image description here][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.sstatic.net/A98em.jpg
Upvotes: 0
Views: 2185
Reputation: 1740
Following snippet will fetch product categories in WooCommerce. After fetching categories, it will display category name with link and category image in loop.
$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
}
}
Upvotes: 1