I cannot get WooCommerce products by id category

I am trying to get products by category id as follows:

<?php

$args = array(
    'posts_per_page' => 20,
    'taxonomy' => 'product_cat',
    'post_type' => 'product',
    'post_status' => 'publish',
    'cat' => $cat_id
); 

$query = new WP_Query($args);

$posts = get_posts($args);
var_dump($posts);

?>

The variable $cat_idcontains the correct category identifier. I checked it out. Products are added to the correct categories.

The problem is that whenever I am a var_dumpvariable $posts, I get an empty array. As soon as I remove the keyword 'cat'from the arguments, I can easily get products from all categories. The only problem is the keyword 'cat'.

Am I doing something wrong?

+1
source share
1 answer

Instead, you can try:

$args = array(
    'posts_per_page' => 20,
    'post_type' => 'product',
    'post_status' => 'publish',
    'tax_query' = array(
         'taxonomy' => 'product_cat',
         'field'    => 'term_id',
         'term'     =>  $cat_id
     )
);
$query = new WP_Query($args);
var_dump($query);

, .

+1

Source: https://habr.com/ru/post/1651601/


All Articles