我想在 Woocommerce 中显示不同 product_cat 的随机产品图像 [英] I want to display random Product Image of distinct product_cat in Woocommerce
问题描述
我正在尝试显示不同产品类别的随机产品图片.将它们链接到类别页面并获取类别标题.我的代码得到随机图像,但太多了,不知道如何获得类别 slug 和标题.
I am trying to display random product images of distinct Product categories. Link them to Category page and get the Category title. I get random images with my code, but too much and have no idea how to get Category slug and title.
$args = array(
'taxonomy' => 'product_cat',
'posts_per_page' => -1,
'showposts' => -1,
'numberposts' => -1,
'orderby' => 'rand',
);
$the_query = new WP_Query( $args );
while ($the_query->have_posts()) : $the_query->the_post();
$temp_thumb = get_the_post_thumbnail($post->ID, 'shop_thumbnail', array('class' => 'attachment-shop_catalog size-shop_catalog wp-post-image'));
$temp = get_term($post->ID, 'product_cat');
$temp_title = $temp->name;
$temp_url = $temp->slug;
echo '<a href="' . $temp_url . '">' . $temp_thumb . $temp_title . '</a>';
endwhile;
推荐答案
如果我正确理解您的问题,您正在尝试创建产品类别列表,该列表链接到每个单独类别的产品存档页面,以及您希望这些类别列表项中的每一个都包含从其下的随机产品中选择的图像吗?
If I understand your question correctly, you are trying to create a list of product categories, that link to the product archive page of each of these individual categories, and you want each of these category list items to contain a image selected from a random product under it?
如果是这种情况,在创建新的 WP_Query
对象之前,您可能会更好地使用 get_terms()
查询开始.
If that's the case, you would probably be better server starting with a get_terms()
query before creating a new WP_Query
object.
流程如下:
- 遍历所有产品类别
- 为每个类别创建一个列表项
- 对随机产品进行快速查询并提取其特色图片.
像这样:
//get terms (i.e. get all product categories)
$arguments = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
);
$terms = get_terms( $arguments );
//loop through each term
foreach ($terms as $term) {
echo $term->name;
echo '<br>';
echo get_random_featured_image($term->term_id);
echo '<br>';
}
//function to get random product based on product category id
function get_random_featured_image($term_id) {
$arguments = array(
'post_type' => 'product',
'orderby' => 'rand', //this grabs a random post
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $term_id, //this makes sure it only grabs a post from the correct category
),
),
);
$query = new WP_Query($arguments);
while($query->have_posts()) {
$query->the_post();
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium' )[0];
}
wp_reset_postdata();
return $image_src; //return the image url
}
这篇关于我想在 Woocommerce 中显示不同 product_cat 的随机产品图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!