Woocommerce 在产品缩略图上方显示产品类别缩略图

我想在商店页面中的产品缩略图上方显示类别缩略图。我尝试使用这段代码,但它不起作用。


请帮助我,我需要完成这件事。任何帮助将不胜感激。谢谢。


        /**

     * Display product category thumbnail.

     *

     * @param mixed $product_category Category term Id, term name or term slug.

     */

    <?php

$thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_bid', true );

$image_url = wp_get_attachment_url( $thumbnail_id ); ?>


守着一只汪
浏览 166回答 1
1回答

守着星空守着你

/**&nbsp;* Display product category thumbnail.&nbsp;*&nbsp;*/add_action('woocommerce_before_shop_loop_item_title', 'display_product_category_thumbnail', 20);function display_product_category_thumbnail(){&nbsp; &nbsp; global $product;&nbsp; &nbsp; $productFirstCategory = reset(get_the_terms($product->get_id(), 'product_cat'));&nbsp; &nbsp; $small_thumb_size = 'woocommerce_thumbnail';&nbsp; &nbsp; $dimensions = wc_get_image_size($small_thumb_size);&nbsp; &nbsp; if ($thumbnail_id = get_term_meta($productFirstCategory->term_id, 'thumbnail_id', true)) {&nbsp; &nbsp; &nbsp; &nbsp; $image = wp_get_attachment_image_src($thumbnail_id, $small_thumb_size);&nbsp; &nbsp; &nbsp; &nbsp; if (is_array($image)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $image = reset($image);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $image_srcset = function_exists('wp_get_attachment_image_srcset') ? wp_get_attachment_image_srcset($thumbnail_id, $small_thumb_size) : false;&nbsp; &nbsp; &nbsp; &nbsp; $image_sizes = function_exists('wp_get_attachment_image_sizes') ? wp_get_attachment_image_sizes($thumbnail_id, $small_thumb_size) : false;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $image = wc_placeholder_img_src();&nbsp; &nbsp; &nbsp; &nbsp; $image_srcset = false;&nbsp; &nbsp; &nbsp; &nbsp; $image_sizes = false;&nbsp; &nbsp; }&nbsp; &nbsp; if ($image) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $src_set = '';&nbsp; &nbsp; &nbsp; &nbsp; if ($image_srcset && $image_sizes) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $src_set = '" srcset="' . esc_attr($image_srcset) . '" sizes="' . esc_attr($image_sizes);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo '<img src="' . esc_url($image) . '" alt="' . esc_attr($productFirstCategory->name)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . '" width="' . esc_attr($dimensions['width']) . '" height="'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . esc_attr($dimensions['height']) . $src_set . '" />';&nbsp; &nbsp; }}您必须使用挂钩woocommerce_before_shop_loop_item_title来挂钩您的函数以在产品标题之前执行。全局变量$product保存当前循环的产品对象。获取当前产品 id 并将其传递给 WP 函数,get_the_terms以数组形式获取与该产品相关的所有术语,并使用 PHP 函数仅检索第一个术语对象reset并将其分配给变量$productFirstCategoryWooCommerce 函数wc_get_image_size以数组形式检索维度详细信息下一个if-else block用于指定产品类别图像或默认图像最终if condition用于输出标题之前的图像
打开App,查看更多内容
随时随地看视频慕课网APP