get product variation parent product
Asked Answered
K

1

5

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

Kalvin answered 13/3, 2021 at 16:25 Comment(1)
use $product->get_parent_id()Gelasius
R
7

The proper way

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);

Old answer

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
Rigidify answered 13/3, 2021 at 16:30 Comment(4)
It is not working, tried like this: $variation_id = get_the_ID(); $product_id = wp_get_post_parent_id($variation_id); $product = wc_get_product($product_id); and I have in my template this variable: $product->get_price_html(); and it is giving error: Uncaught Error: Call to a member function get_price_html() on boolKalvin
nevermind your code works but it is not fixing issue for my problem. I asked wrong thing :/Kalvin
You need to check what is in $product_id $product would be an object.Society
Im using ACF and it is not giving parent product fields to variation product...Kalvin

© 2022 - 2024 — McMap. All rights reserved.