Menu Close

WooCommerce: See If Product ID Belongs To a Grouped Product

default

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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// 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
}
View Source
Posted in WooCommerce Tips