如何在WooCommerce中以随机顺序获取所有产品的变体

问题描述:

我有一个拥有可变产品的WooCommerce商店,我想用变体产品以及商店页面显示所有产品。 我下面的代码给出:如何在WooCommerce中以随机顺序获取所有产品的变体

$params = array('posts_per_page' => 2, 'post_type' => 'product', 'orderby' => 'rand'); 

$wc_query = new WP_Query($params); 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 

query_posts(array(
    'post_type'  => 'product', 
    'paged'   => $paged, 
    'posts_per_page' => 2, 
    'orderby' => 'rand' 
)); 

if (have_posts()) : 
while (have_posts()) : the_post(); 
echo '<h2>'.the_title.'</h2>'; 
if ($product->is_type('variable')) 
{ 
    $available_variations = $product->get_available_variations(); 
    foreach ($available_variations as $key => $value){ 
     if($value['variation_is_active']==1){ 
      // varible products details 
     } 
    } 
} 
endwhile; 
    the_posts_pagination(); 
    wp_reset_postdata(); 
else: 
    echo 'No Products'; 
endif: 

//我得到的产品,但只有随机化的主要产品没有变化

请帮助我。 在此先感谢

为了得到可变产品,你有 post_type键使用product_variation

所以你$paramsquery_posts应该是这样的:

$params = array(
    'posts_per_page' => 2, 
    'post_type' => array('product', 'product_variation'), // <-- check this line. 
    'orderby' => 
    'rand' 
); 
//... 
//... 
query_posts(array(
    'post_type' => array('product', 'product_variation'), // <-- check this line. 
    'paged' => $paged, 
    'posts_per_page' => 2, 
    'orderby' => 'rand' 
    ) 
); 

参考:Get List of All WooCommerce Products

希望这有助于!