質問

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();
?>
役に立ちましたか?

解決

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:

ライセンス: CC-BY-SA帰属
所属していません wordpress.stackexchange
scroll top