MainWP Community

Display Product Category Thumbnail above Product Thumbnail Image in WooCommerce

Display product category thumbnail above the product thumbnail image if using WooCommerce on your child site.

Snippet Type

Execute on Child Sites

Snippet

add_action('woocommerce_before_shop_loop_item_title', 'display_product_category_thumbnail', 20);
function display_product_category_thumbnail()
{
    global $product;

    $productFirstCategory = reset(get_the_terms($product->get_id(), 'product_cat'));

    $small_thumb_size = 'woocommerce_thumbnail';
    $dimensions = wc_get_image_size($small_thumb_size);

    if ($thumbnail_id = get_term_meta($productFirstCategory->term_id, 'thumbnail_id', true)) {
        $image = wp_get_attachment_image_src($thumbnail_id, $small_thumb_size);

        if (is_array($image)) {
            $image = reset($image);
        }

        $image_srcset = function_exists('wp_get_attachment_image_srcset') ? wp_get_attachment_image_srcset($thumbnail_id, $small_thumb_size) : false;
        $image_sizes = function_exists('wp_get_attachment_image_sizes') ? wp_get_attachment_image_sizes($thumbnail_id, $small_thumb_size) : false;
    } else {
        $image = wc_placeholder_img_src();
        $image_srcset = false;
        $image_sizes = false;
    }

    if ($image) {
        
        $src_set = '';
        if ($image_srcset && $image_sizes) {
            $src_set = '" srcset="' . esc_attr($image_srcset) . '" sizes="' . esc_attr($image_sizes);
        }

        echo '<img src="' . esc_url($image) . '" alt="' . esc_attr($productFirstCategory->name) 
            . '" width="' . esc_attr($dimensions['width']) . '" height="' 
            . esc_attr($dimensions['height']) . $src_set . '" />';
    }
}
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.