Get "primary" category image from WooCommerce product

Viewed 3275

I am trying to get the featured image of the "Primary" selected category of a product.

Getting the images from the categories is not the problem, but how do I get the "primary" one?

Currently this is what I am using and of course getting all the images.

I only want to display one image.

<?php
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
    $category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
    $image = wp_get_attachment_url($category_thumbnail);
            echo '<img src="'.$image.'" alt="" />';
}?>
1 Answers

You need to target the terms with 'parent' argument equal to 0.

As you have set for your products only one "primary" product category for each normally, so we just take the first one anyway (but you can have many for a product):

<?php

global $post;
$term_ids = wp_get_post_terms( $post->ID, 'product_cat', array('fields' => 'ids', 'parent' => '0') );
if( count($term_ids) > 0 ){
    echo '<img src="'. wp_get_attachment_url( get_woocommerce_term_meta( $term_ids[0], 'thumbnail_id', true ) ) .'" alt="" />';
}

?>

This is tested and works.

Related