我正在尝试显示不同产品类别的随机产品图片。将它们链接到类别页面并获取类别标题。我使用我的代码获得随机图像,但是太多并且不知道如何获得Category slug和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;
答案 0 :(得分:1)
如果我正确理解了您的问题,那么您正在尝试创建一个产品类别列表,这些产品类别链接到每个类别的产品存档页面,并且您希望这些类别列表项中的每一个都包含从中选择的图像它下面的随机产品?
如果是这种情况,那么在创建新的get_terms()
对象之前,您可能会更好地使用WP_Query
查询启动服务器。
这个过程会是这样的:
这样的事情:
//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
}