如何显示 Woocommerce 类别图像?

新手上路,请多包涵

我在 PHP 中使用此代码:

 $idcat = 147;
$thumbnail_id = get_woocommerce_term_meta( $idcat, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<img src="'.$image.'" alt="" width="762" height="365" />';

其中 147 是手动设置的当前ID,但我需要其他类别的当前ID

有什么建议吗?

原文由 MrRoman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 541
2 个回答

要在 archive-product.php 中显示当前显示的类别的类别图像,请在 is_product_category() 为 true 时使用当前类别 term_id

 // verify that this is a product category page
if ( is_product_category() ){
    global $wp_query;

    // get the query object
    $cat = $wp_query->get_queried_object();

    // get the thumbnail id using the queried category term_id
    $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );

    // get the image URL
    $image = wp_get_attachment_url( $thumbnail_id );

    // print the IMG HTML
    echo "<img src='{$image}' alt='' width='762' height='365' />";
}

原文由 doublesharp 发布,翻译遵循 CC BY-SA 4.0 许可协议

我是这样做的:

 function loop_product_category_image(){
    global $wp_query;
    $terms = get_the_terms( $wp_query->ID, 'product_cat' );
    $thumbnail_id = get_term_meta( $terms[0]->term_id, 'thumbnail_id', true );
    $image = wp_get_attachment_url( $thumbnail_id );
    echo "<img src='{$image}' alt='category image' width='162' height='165' />";
}

例如,您可以挂钩:在产品循环中:

 add_action('woocommerce_before_shop_loop_item', 'loop_product_category_image', 7);

或在产品中:

 add_action('woocommerce_before_main_content', 'cylkow_loop_product_category_image', 7);

或任何你想要的地方。

您还可以使用条件标签 https://woocommerce.com/document/conditional-tags/

原文由 adrian proscinski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题