gpt4 book ai didi

php - 获取 Woocommerce 产品类别图像 url

转载 作者:行者123 更新时间:2023-12-01 20:25:10 26 4
gpt4 key购买 nike

我已使用以下代码来获取 Woocommerce 产品类别的缩略图 URL,但它仅输出 <img>标记为 src="unknown" .

$cat_slug = t-shirts;
$thumbnail_id = get_woocommerce_term_meta( $cat_slug, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<img src="'.$image.'" alt="" width="50" height="50" />';

使其发挥作用的最佳方法是什么?

编辑

在第二次调用牛仔裤类别的缩略图时,它仅输出 <img src(unknown) alt="" width="50" height="50" />

<div class="list-item">
<div class="item-img">

<?php

$term_slug = 't-shirts';
$taxonomy = "product_cat";
$term_id = get_term_by( 'slug', $term_slug, $taxonomy )->term_id;
$thumbnail_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );

echo '<img src="'.$image.'" alt="" width="50" height="50" />';

?>

</div>

<a href="#">
<div class="item-name">
<?php if( $term = get_term_by('slug', 't-shirts', 'product_cat') ) echo $term->name;?>
</div>
</a>

</div>

<div class="list-item">
<div class="item-img">

<?php

$term_slug = 'jeans';
$taxonomy = "product_cat";
$term_id = get_term_by( 'slug', $term_slug, $taxonomy )->term_id;
$thumbnail_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );

echo '<img src="'.$image.'" alt="" width="50" height="50" />';

?>

</div>

<a href="#">
<div class="item-name">
<?php if( $term = get_term_by('slug', 'jeans', 'product_cat') ) echo $term->name;?>
</div>
</a>

</div>

最佳答案

函数 get_woocommerce_term_meta() 需要术语 ID 而不是术语 slug。因此,您可以使用 get_term_by() Wordpress 函数从术语 slug 中获取术语 ID。

所以你的代码将是:

$term_slug    = 't-shirts';
$taxonomy = 'product_cat';
$term_id = get_term_by( 'slug', $term_slug, $taxonomy )->term_id;
$thumbnail_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );

// Output
echo '<img src="'.$image.'" alt="" width="50" height="50" />';

经过测试并有效

<小时/>

添加版本 3(与您的评论相关)

我使用 foreach 循环进行了一些其他更改,优化了代码,并允许您添加任意数量的产品类别段

我还添加了术语“链接”,并做了一些细微的更改。

<?php
$term_slugs = array('jeans', 't-shirts');
$taxonomy = "product_cat";

// Loop though the term slugs array
foreach ( $term_slugs as $term_slug ):
$term = get_term_by( 'slug', $term_slug, $taxonomy );
if( $term ):
$term_link = get_term_link( $term, $taxonomy );

$thumb_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
$img_src = wp_get_attachment_url( $thumb_id );
?>
<div class="list-item">
<div class="item-image">
<img src="<?php echo $img_src; ?>" alt="" width="50" height="50" />
</div>
<div class="item-name">
<a href="<?php echo $term_link; ?>"><?php echo $term->name; ?></a>
</div>
</div>
<?php endif;
endforeach; ?>

关于php - 获取 Woocommerce 产品类别图像 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com