I'm trying to create a custom loop to display all the WooCommerce categories on my site. It should be fairly simple but I'm having issues getting hold of the category thumbnails. No matter what I do, i seem to end up with the full sized images. Here's my code:
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'exclude' => '21'
);
echo '<ul>';
foreach( get_categories( $args ) as $category ) :
$thumbnail_id = get_term_meta( $category->term_id,'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<li><a href="'.$category->slug.'" class="label" title="' . $category->name . '">';
if($image!=""):
echo '<img src="' . $image . '">';
endif;
echo $category->cat_name.'</a></li>';
endforeach;
I've searched all over, but everyone else seems to get the correct images. I'm getting the full sized images as uploaded. Am I missing something here? Does anyone know of any reason why this might not be pulling in correctly? Could it be a theme issue?
Replace wp_get_attachment_url()
with wp_get_attachment_image()
to get the thumbnailed sized image (or specify the desired image size).
Also, you should use get_term_link()
to get the term URL instead of using the term slug.
So your code will be:
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'exclude' => '21'
);
echo '<ul>';
foreach( get_categories( $args ) as $category ) :
$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
$image_html = wp_get_attachment_image( $thumbnail_id, 'woocommerce_thumbnail' );
$term_link = get_term_link( $category, 'product_cat' );
echo '<li><a href="'.$term_link.'" class="label" title="' . $category->name . '">';
if( $image_html ):
echo $image_html;
endif;
echo $category->cat_name.'</a></li>';
endforeach;
It should work as expected.
You can choose a different size from:
thumbnail
,gallery_thumbnail
,woocommerce_gallery_thumbnail
,woocommerce_single
,single
…