I am working on setting random thumbnails for each of the categories on my woocommerce site. By default a placeholder is assigned, but you can override this by uploading / assigning an image in the dashboard.
What I am wanting to do is for example, “Mens” is my parent category and “Jeans” is my subcategory. So I want to dispaly a random image of an item that is in the “Mens >> Jeans” category….. I hope this makes sense.
What I have come up with at the minute is this (in my wc_template_functions.php file)
args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => $category->name, 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) { $loop->the_post();}{
$image = print_r(get_the_post_thumbnail($loop->post->ID, 'shop_catalog'));}
$image = $image[0];
$image = apply_filters( 'woocommerce_placeholder_img_src',$image[0] );
Which is generating the images, but the problem i’m having is that, say I have “Jeans” under the parent category “Mens” and “Womens” the picture displayed is totally ignoring whether it’s in the “Mens” or “Womens” category. So i’m getting images of womens jeans in the “Men >> Jeans”.
What i need to do is to be able to specify two categories, “Jeans” and “Mens” but i’m unsure how to do this. I’ve been told that because products are not posts I cannot specify product category names, i have to use taxonomies?
Could someone help please and point me in the right direction?
Cheers
Chris
This is how you do it:
This will get products that are on both categories with IDs 25 and 27.
You can also use ‘field’ => ‘slug’´+ if you rather specify by slugs, but I think using ID’s will make a faster query in this case.