WooCommerce-显示特定产品类别的随机产品缩略图

时间:2016-02-20 作者:Jnsn_

我试图显示特定类别的随机产品缩略图。我现在有这个代码,但它不起作用,将显示所有产品,如何从特定的产品类别随机?

<?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 个回复
最合适的回答,由SO网友:Adam 整理而成

将tax\\u查询添加到$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 );
建议阅读:

相关推荐