Search code examples
phparrayswordpresswoocommerceargs

Get all products from multiple categories (Woocommerce/Wordpress)


I want to display all products from multiple categories at once.

When i want to display all products from one category my $args array looks like this:

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

I remember that I can simply make an array inside my $args:

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

But it gives me the following error:

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

I know this is a simple thing but i cant figure out why its not working. Thanks for any help!


Solution

  • Please try below snippet.

    $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);