2017-01-25 45 views
0

我做了一個自定義查詢以獲得產品變體,但是當我垃圾產品時,它的變體狀態將保持爲publish,所以如果客戶發生了404錯誤試圖查看被廢棄的產品變體。 那麼,我如何過濾這些變體以獲得已發佈父代產品的變體?如何僅在母公司產品發佈時獲取產品變體

我的代碼:

<?php 
$args = ['post_type' => ['product_variation'], 
      'orderby' => 'meta_value_num', 
      'order'  => 'DESC', 
      'post_status'=>'publish', 
      'product_type'=>'variation', 
      'meta_query' => [ 
       [ 
        'key'  => 'attribute_pa_flower-type', 
        'value' => $flower_type, 
        'compare' => '=', 
       ] 
      ] 
     ]; 
?> 

<?php $the_query = new WP_Query($args);?> 

<?php if ($the_query->have_posts()) : ?> 

    <div class="boxes"> 
     <?php while ($the_query->have_posts()) : $the_query->the_post(); ?> 
     ... 

回答

1

做一些這樣的事情:

//to hold the published product id which has vriation. 
$has_variable_ids = []; 

$args_parent = [ 
    'post_type' => ['product'], 
    'post_status' => 'publish', 
    'posts_per_page' => -1 
]; 

$pubished_post = new WP_Query($args_parent); 
if (!empty($pubished_post->posts)) 
{ 
    foreach ($pubished_post->posts as $post) 
    { 
     $_product = wc_get_product($post->ID); 
     if ($_product->is_type('variable')) 
     { 
      // Product has variations 
      $has_variable_ids[] = $post->ID; 
     } 
    } 
} 


$args = [ 
    'post_type' => ['product_variation'], 
    'orderby' => 'meta_value_num', 
    'order' => 'DESC', 
    'post_status' => 'publish', 
    'post_parent__in' => $has_variable_ids, 
    'meta_query' => [ 
     [ 
      'key' => 'attribute_pa_flower-type', 
      'value' => $flower_type, 
      'compare' => '=', 
     ] 
    ] 
]; 

$the_query = new WP_Query($args); 

請注意:我have't測試,但它應該工作。

希望這會有所幫助!

+0

是的,這是有效的,我最終做的是得到每個變體的父帖子,並檢查其在while循環內的狀態,但我會更改我的代碼爲你的,因爲它更快 – Mohammad

+0

我沒有找到和WooCommerce功能爲此,我這樣做了我的WP知識。 –