Home > database >  WordPress get product by taxonomy
WordPress get product by taxonomy

Time:04-11

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?

CodePudding user response:

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>';
  • Related