'WordPress get product by taxonomy

I have created 7 WooCommerce products under 'membership-level' category. Now, to get those products I am using the following code but not working as expected.

$args = [
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'membership-level',
        )
    )
];

echo '<pre>';
print_r( get_posts( $args ) );
echo '</pre>';

Is there anything I am missing?



Solution 1:[1]

To query products by product category you have to set

  • taxonomy name: in your case "product_cat"
  • field (p.ex: term_id, slug): in your case slug
  • and term

So try something like that


$args = [
    'post_type' => 'product',
    'tax_query' => array(

            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array('membership-level')

    )
];

echo '<pre>';
print_r( get_posts( $args ) );
echo '</pre>';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ZecKa