Reputation: 443
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;
Upvotes: 1
Views: 870
Reputation: 7614
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?
If that's the case, you would probably be better server starting with a get_terms()
query before creating a new WP_Query
object.
The process would go like this:
Something like this:
//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
}
Upvotes: 1