1

I am trying to show random product thumbnails from a specific category. I have this code at the moment but it is not working and will show from all products, how to randomize from a specific product category?

<?php
    $args = array(
    'posts_per_page'   => 1,
    'orderby'          => 'rand',
    'post_type'        => 'product' ); 

     $random_products = get_posts( $args );

     foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
        <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
     <?php endforeach; 
     wp_reset_postdata();
?>
1

Add a tax_query to your $args...

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',   //possible values are term_id, name, slug or term_taxonomy_id
            'terms' => 'tshirt'  //can be single string or array of slugs, names, term_ids or taxonomy_ids
        )
    )
);

$results = get_posts( $args );

Recommended reading:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.