Grouped Products are part of WooCommerce core and let you “add similar (think materials, design, etc.) products to a single grouped product. This allows the customer to add products […] to their cart on one page instead of navigating to several different pages to do so” (WooCommerce docs).
It may happen during your coding career that you need to know whether a given Product ID is part of a Grouped Product (so, it’s a “child” of a Grouped Product) – the snippet below will help with that. Enjoy!
PHP Snippet: Find Out If Product ID Is a Grouped Product Child
/**
* @snippet See If Product ID Belongs to Grouped Product
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
// GET ALL GROUPED PRODUCTS
$args = array(
'type' => 'grouped',
'status' => 'publish',
'limit' => -1,
);
$products = wc_get_products( $args );
// LOOP THROUGH RESULTS
foreach ( $products as $product ) {
$children = array();
foreach ( $product->get_children() as $child_id ) {
$children[] = $child_id;
}
}
// CHECK IF PRODUCT 123 IS A CHILD
if ( in_array( 123, $children ) ) {
// DO SOMETHING
}
Where to add custom code?
You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?
This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101
Related content
- WooCommerce: Custom Add to Cart URLs – The Ultimate Guide
In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […] - WooCommerce: Disable Grouped Product Price Range $$$-$$$
You may want to disable the Grouped product price range on the Shop and Single Product page. This usually looks like $100-$999. With this snippet you will be able to display “From: ” in front of the minimum price, or otherwise completely hide it ๐
Rodolfo Melogli
Business Bloomer Founder
Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli