Answer the question
In order to leave comments, you need to log in
How to display product image on catalog page?
Hello everyone, this is the situation:
I want to display an image of a product in the catalog, for categories and the products themselves, while doing this through picture, so that it is possible to display images in webp format.
The output of the product card image in the catalog is located in content-product.php and looks like this:
$image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
$image = $product->get_image( $image_size );
echo $image;
$small_thumbnail_size = apply_filters( 'subcategory_archive_thumbnail_size', 'woocommerce_thumbnail' );
$dimensions = wc_get_image_size( $small_thumbnail_size );
$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
if ( $thumbnail_id ) {
$image = wp_get_attachment_image_src( $thumbnail_id, $small_thumbnail_size );
$image = $image[0];
} else {
$image = wc_placeholder_img_src();
}
if ( $image ) {
$image = str_replace( ' ', '%20', $image );
$image_webp = str_replace( ['.png', '.jpg', '.jpeg', '.gif'], '.webp', $image );
echo '<div class="product__catalog-img"><picture><source srcset="' . esc_url($image_webp) . '" type="image/webp"><img src="' . esc_url($image) . '" alt="' . esc_attr( $category->name ) . '"></picture></div>';
}
Answer the question
In order to leave comments, you need to log in
The product image in the catalog output loop is rendered by the woocommerce_template_loop_product_thumbnail action, which hangs on the woocommerce_before_shop_loop_item_title hook. You can replace the image output function with your own and output whatever you want.
For example like this:
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
add_action( 'woocommerce_before_shop_loop_item_title', 'fink_template_loop_product_thumbnail', 10 );
function fink_template_loop_product_thumbnail() {
global $product;
$image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
$product_id = $product->get_id();
$image = get_the_post_thumbnail_url( $product_id, $image_size ); //Получаем url картинки
if ( $image ) {
$image = str_replace( ' ', '%20', $image );
$image_webp = str_replace( ['.png', '.jpg', '.jpeg', '.gif'], '.webp', $image );
echo '<div class="product__catalog-img"><picture><source srcset="' . esc_url($image_webp) . '" type="image/webp"><img src="' . esc_url($image) . '" alt="' . esc_attr( $product->get_name() ) . '"></picture></div>';
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question