0
votes

I want to display the category image as banner in the woocommerce single product page. I'm using this code, but it shows all the category image.

if(is_single()) {
    $terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ){
      $category_name = $term->name;
      $category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
    $image = wp_get_attachment_url($category_thumbnail);
     echo '<img class="absolute '.$category_name.' category-image" src="'.$image.'">';
    }
    }

I want only to show the category image. when I click on the product, it shows its category image as banner.

2

2 Answers

1
votes

Problem in code : What you have done in your coding is, you are fetching all the terms(get_the_terms) assinged to the product.That is why it is displaying all the images.

Solution : Either you can change your code to get banner image of particular product or else you can simply put dummy condition to get only one image.

Code for dummy condition :

if(is_single()) {
    $terms = get_the_terms( $post->ID, 'product_cat' );
    $i=0; //Variable for dummy condition
    foreach ( $terms as $term ){
        if($i==0): //Dummy Condition
            $category_name = $term->name;
            $category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
            $image = wp_get_attachment_url($category_thumbnail);
            echo '<img class="absolute '.$category_name.' category-image" src="'.$image.'">';
            $i++; //Increment it to make condition false
        endif;
    }
}

Let me know if you have any doubt.

0
votes

You slect child category that why display all category image