woocommerce display parent category thumbnail only (taxonomy-product_cat.php)

大城市里の小女人 提交于 2019-12-08 07:37:43

问题


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>

来源:https://stackoverflow.com/questions/47030992/woocommerce-display-parent-category-thumbnail-only-taxonomy-product-cat-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!