Reputation: 143
In Woocommerce, Due to an inventory sku issue with clothing size, we have two different products for ultimately the same product. Let's call it a blue shirt, but it is 2 different products in our store due to an ordering decision. I've created a grouped product to handle the display of this.
However I can't seem to hide the linked products from my shop. When I use the WC_Product_query
class and the get_products function, it doesn't seem to return all 46 products that are being queried. I'm wondering what exactly, I'm doing wrong and/or if there is a better solution.
Placed the following in my functions.php child theme:
add_action( 'woocommerce_product_query', 'only_grouped_products_query' );
function only_grouped_products_query( $q ) {
$query = new WC_Product_Query(array($q));
$products = $query->get_products();
$linked_array = array();
$i = 0;
foreach($products as $product){
$i++;
/*
echo $product->get_name() .' - ' . $product->product_type .'<br>';
$is_grouped = $product->product_type;
if ( $is_grouped == 'grouped' )
{
// echo $product->get_name() .' - ' . $product->product_type;
$get_child_id = $product->get_children();
if (is_array($get_child_id)){
foreach($get_child_id as $child_id){
$linked_array[] = $child_id;
}
} else {
$linked_array[] = $get_child_id;
}
}
*/
}
echo $i;
// $q->set( 'post__not_in', $linked_array );
}
The above code snippet does work, but it doesn't pull in all 46 results that the query is showing when I dump the original $query variable. $i only returns 10 results.
Upvotes: 3
Views: 3966
Reputation: 253783
Your question body explanations are not so clear… So I base this answer on your question title.
As the product type in Woocommerce is handled by product_type
custom taxonomy, you need to use a Tax query instead.
The following code will display only grouped product types on all Woocommerce archive pages:
add_filter( 'woocommerce_product_query_tax_query', 'only_grouped_products', 20, 1 );
function only_grouped_products( $tax_query ){
$tax_query[] = array(
'taxonomy' => 'product_type',
'field' => 'name',
'terms' => array('grouped'),
);
return $tax_query;
}
Code goes in function.php file of your active child theme (active theme). Tested and works.
So you can handle any product type:
'terms' => array('simple'),
'terms' => array('variable'),
'terms' => array('grouped'),
'terms' => array('external'),
And also all these custom product types (from known 3rd party plugins):
'terms' => array('composite'),
'terms' => array('subscriptions'),
'terms' => array('Variable Subscription'),
'terms' => array('booking'),
You can combine multiple product types too like for example simple and grouped products types only:
You will use:'terms' => array('simple', 'grouped'),
… and so on.
Upvotes: 4