2017-03-03 97 views
0

我想一次顯示來自多個類別的所有產品。獲取來自多個類別的所有產品(Woocommerce/Wordpress)

當我要顯示所有產品從一類我的$ args數組是這樣的:

$args = array(
    'post_type' => 'product', 
    'product_cat' => 'backpacks', 
    'orderby' => '_sku' 
); 

我記得,我可以簡單地在我的的$ args數組:

$args = array(
    'post_type' => 'product', 
    'product_cat' => array(
     'backpacks','accessoires', 
), 
    'orderby' => '_sku' 
); 

但它給了我以下錯誤:

Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\live\wp-includes\formatting.php on line 4312

我知道這是一件簡單的事情,但我無法弄清楚爲什麼它不工作。 感謝您的幫助!

回答

1

請嘗試下面的代碼段。

$sortcolumn = 'ID'; 
$prod_categories = array(12, 17); //category IDs 
$product_args = array(
    'numberposts' => -1, 
    'post_status' => array('publish', 'pending', 'private', 'draft'), 
    'post_type' => array('product', 'product_variation'), //skip types 
    'orderby' => $sortcolumn, 
    'order' => 'ASC', 
); 

if (!empty($prod_categories)) { 
    $product_args['tax_query'] = array(
     array(
      'taxonomy' => 'product_cat', 
      'field' => 'id', 
      'terms' => $prod_categories, 
      'operator' => 'IN', 
    )); 
} 

$products = get_posts($product_args); 
+0

有點複雜,但感謝隊友! –

+0

不客氣@B –

1

發現了一個簡單的方法來做到這一點

$args = array(
'post_type' => 'product', 
'tax_query' => array(
    'relation' => 'OR', 
    array(
     'taxonomy' => 'product_cat', 
     'field' => 'slug', 
     'terms' => 'backpacks' 
    ), 
    array(
     'taxonomy' => 'product_cat', 
     'field' => 'slug', 
     'terms' => 'accessoires' 
    ) 
), 
); 
相關問題