In the end my main problem turned out to be that I was executing code right into functions.php (for testing purpose). The code was executing before woocommerce was initialized and then was failing to fetch products correctly.
Despite that, I couldn’t get Wp_Query to return only products of one given category. It was still returning every product from my database so I found a way around it.
$category; //this is the var containing the wanted category slug
$productPosts = new WP_Query(array(
'post_type' => 'product'
));
//I could have used $productPosts->have_posts() here but I decided not to use it in my particular context
foreach ($productPosts->posts as $p) {
$currentProduct = new WC_Product_Variable($p->ID);
//I can only access category ids with WC_Product so I'm building an array of category slugs instead
foreach ($currentProduct->get_category_ids() as $catId) {
if( $term = get_term_by( 'id', $catId, 'product_cat' ) ){
array_push($categories, $term->name); //push it
}
}
if(in_array($category, $categories)){ //if the current currentProduct has the asked category,
//push it in $currentProduct into $products array
array_push($products, $currentProduct);
}
else{//current product doesn't have asked category
}
} //end foreach, we now have all products of asked category... in $products array
This works… But really, it feels wrong. I’m making several database queries for each product I want to include in my final array… Is this how woocommerce is supposed to work ?
Also, I’m not sure how i’m supposed to paginate with this data but anyway it’s not my concern here…
There must be a better way to do this but I couldn’t find it for now…