I am using the plugin WooCommerce Variation Swatches and Photos which lets me add a thumbnail to my product's attributes.
I need to list all the attributes on a template and I would like to also get and show the thumbnail.
$terms = get_terms( array(
'taxonomy' => 'pa_texture',
'hide_empty' => false,
) );
foreach ( $terms as $term ) {
print_r($term);
}
The thumbnail feature is not default in WooCommerce so when I print_r $term there is no thumbnail URL:
WP_Term Object
(
[term_id] => 54
[name] => Guilin
[slug] => guilin
[term_group] => 0
[term_taxonomy_id] => 54
[taxonomy] => pa_texture
[description] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet facilisis convallis.
[parent] => 0
[count] => 2
[filter] => raw
[meta_value] => 0
)
How can I get the attribute's thumbnail image?
The classic way for product categories terms 'product_cat'
taxonomy is:
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
) );
foreach ( $terms as $term ) {
$thumb_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
$img_src = wp_get_attachment_url( $thumb_id );
echo '<p><img src="'.$img_src.'" alt="" />'.$tem->name.'</p>';
}
So may be changing the taxonomy to product attributes like 'pa_texture'
, it should do the trick
(I hope, but I am not sure as I dont use Variation Swatches and Photos plugin).
Found the solution thanks to @Und3rTow's input.
The correct parameter in get_woocommerce_term_meta is pa_texture_swatches_id_photo
.
Here is the final code:
$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'pa_texture_swatches_id_photo', true );
$textureImg = wp_get_attachment_image_src( $thumbnail_id ); ?>
<img src="<?php echo $textureImg[0]; ?>">
This is untested, however some variation of the following should work:
foreach ( $terms as $key => $term ) {
$thumbnail_id = get_woocommerce_term_meta( $term->term_id, $term->taxonomy . '_photo', true );
$terms[ $key ]->thumb = wp_get_attachment_image_src( $thumbnail_id );
print_r( $term );
}
If you look at the relevant plugin file, you can see how the author get the images. The code above is based loosely from that.
I had a similar problem when displaying images in upsells products. There is a mess, but:
if ( $products_upsells->have_posts() ) : while ( $products_upsells->have_posts() ) : $products_upsells->the_post();
$_product = wc_get_product(get_the_ID());
$attributes = $_product->get_attributes();
$attr_id = $attributes['pa_kolor']['options'][0];
$thumb_id = get_term_meta($attr_id);
$img_src = wp_get_attachment_url($thumb_id['pa_kolor_swatches_id_photo'][0] );
echo '<img src="'.$img_src.'" alt="" />';
endwhile; endif;
wp_reset_query();
See this code:
$_product = wc_get_product(get_the_ID());
$attributes = $_product->get_attributes();
$attr_id = $attributes['pa_kolor']['options'][0];
$thumb_id = get_term_meta($attr_id);
$img_src = wp_get_attachment_url($thumb_id['pa_kolor_swatches_id_photo'][0] );