How to display product cropped thumbnail (150×150) for WooCommerce product categories

I have tried to display woocommerce categories thumbnails, but nothing works, below is the code to display the categories list and it works awesomely, just one thing left the thumbnails.

$product_cats = get_terms([
    'taxonomy'   => 'product_cat', 
    'hide_empty' => true, 
    'parent'     => 0, 
    'fields'     => 'names' // Term names
]);

foreach ( $product_cats as $key => $parent_term_name ) {
    printf( '<button class="tablinks %s" onclick="https://wordpress.stackexchange.com/questions/337144/%s">%s</button>',
        $key === 0 ? esc_attr( 'active' ) : '',
        "myFunction(event,'{$parent_term_name})",
        $parent_term_name
    );
}

I have tried to add this part so that I could display the image, but nothing works beside from the placeholder image.

$category_thumbnail = get_woocommerce_term_meta($parent_term_name->term_id, 'thumbnail_id', true);
   if ( $category_thumbnail ) { 
       $image = wp_get_attachment_url($category_thumbnail);
    }
   else {
   $image = wc_placeholder_img_src();
}

1 Answer
1

To include the product category thumbnail (125 × 125 px) in your product category items (buttons), use the following:

$product_cats = get_terms([
    'taxonomy'   => 'product_cat',
    'hide_empty' => true,
    'parent'     => 0,
]);

foreach ( $product_cats as $key => $parent_term ) {
    $thumb_id = get_woocommerce_term_meta( $parent_term->term_id, 'thumbnail_id', true );
    $size="thumbnail";
    $image    = wp_get_attachment_image_src($thumb_id, $size);

    printf( '<button class="tablinks %s" onclick="https://wordpress.stackexchange.com/questions/337144/%s"><img src="https://wordpress.stackexchange.com/questions/337144/%s" width="150" height="150" />%s</button>',
        $key === 0 ? esc_attr( 'active' ) : '',
        "myFunction(event,'{$parent_term->name}')",
        $thumb_id ? $image[0] : wc_placeholder_img_src($size),
        $parent_term->name
    );
}

Leave a Comment