Reputation: 181
How I can get variation parent product ID.
EXAMPLE: I have product with ID 35 and this product has two variations colors - red (ID 351), black (ID 352)
My code:
$product = wc_get_product(get_the_ID()); //get_the_ID() is ID 351 and I need this parent ID 35
Upvotes: 5
Views: 3347
Reputation: 1210
As LoicTheAztec suggested in comments, you should use this:
$parent_product = wc_get_product($product->get_parent_id());
The reason why you should retrieve parent product via get_parent_id()
is that it will trigger hook woocommerce_product_variation_get_parent_id
and it will be easily modifiable by other plugins/themes:
add_filter('woocommerce_product_variation_get_parent_id', function($value, $wc_data) {
// ...
return $value;
}, 10, 2);
This will also work, but it won't trigger WC-specific hooks:
$parent_product_id = wp_get_post_parent_id($product->get_id());
$parent_product = wc_get_product($parent_product_id);
Note: That's not working outside the loop and will always return 0
if you attempt to substitute get_the_ID()
with $product->id
- in that case use $product->get_id()
as in the example above.
Use wp_get_post_parent_id
, as variations have their parent as the product itself.
Example:
$variation_id = get_the_ID();
$product_id = wp_get_post_parent_id($variation_id);
Never use WC_Product::get_parent():
$parent_product = $product->get_parent(); // will always return '0
Upvotes: 7