I created a function that display parent category thumbnails for all the pages that uses this template (taxonomy-product_cat.php) . The function is working on one of my parent and it's subcategories (category 1 with 6 subcategories), the problem is on the other category (category 2 with 6 subcategories) I created. It repeats the echo 6 times = equivalent to the number of it's subcategories. I don't know what's causing it.
function woocommerce_get_parent_thumbnail() {
global $post;
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($prod_terms as $prod_term) {
// gets product cat id
$product_cat_id = $prod_term->term_id;
// gets an array of all parent category levels
$product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );
// This cuts the array and extracts the last set in the array
$last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
foreach($last_parent_cat as $last_parent_cat_value){
$category_thumbnail = get_woocommerce_term_meta($last_parent_cat_value, 'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
echo '<div class="d-flex" style="background-image:url('.$image.');">';
}
}
}
Display function
<div class="">
<?php
woocommerce_get_parent_thumbnail();
?>
<div class="row align-items-center justify-content-lg-end justify-content-md-center justify-content-sm-center w100">
<div class="col-md-12 col-lg-5 mLxxl mRxxl pTxxl pLxxl pBxxl pRxxl">
<p class="">catalogue</p>
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<h1 class=""><?php woocommerce_page_title(); ?></h1>
<?php endif; ?>
<p class="fs-16"></p>
</div>
</div>
</div>