Helmut
Helmut

Reputation: 443

I want to display random Product Image of distinct product_cat in Woocommerce

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

Answers (1)

Frits
Frits

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:

  1. Loop through all product categories
  2. Create a list item of each category
  3. Do a quick query for a random product and pull it's featured image.

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

Related Questions