如何从woocommerce中的链接产品中获取分组的产品ID

I have a grouped product product-1 , which has many linked products:

-product-1 (grouped product)

  • |__ product-2 (simple or variable product)
  • |__ product-3 (simple or variable product)

I want to get the ID of product-1 using the ID of product-2

You can't get the product Id of a particular grouped product through one of its children product ID, as each children can be in many different grouped products.

The only data that define the children products IDS for a grouped product is located in wp_postmeta table arround the meta_key _children as an array of children product IDs.

Now if the children product ID which you want to use to retrieve the parent grouped product ID is only the children of one unique grouped product, you can use the following SQL query embedded in a function:

function get_parent_grouped_id( $children_id ){
    global $wpdb;
    $results = $wpdb->get_col("SELECT post_id FROM {$wpdb->prefix}postmeta
        WHERE meta_key = '_children' AND meta_value LIKE '%$children_id%'");
    // Will only return one product Id or false if there is zero or many
    return sizeof($results) == 1 ? reset($results) : false;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

USAGE

Here below 738 is one the children Ids from a grouped product. It can also be a dynamic value through a variable…

$parent_grouped_id = get_parent_grouped_id( 738 );

ADDITION - Get all grouped products using a WC_Product_Query:

1) Array of grouped products Objects:

$grouped_products = wc_get_products( array( 'limit' => -1, 'type' => 'grouped' ) );

1) Array of grouped products IDS only:

$ids = wc_get_products( array( 'limit' => -1, 'type' => 'grouped', 'return' => 'ids' ) );