Get Woocommerce Variation Parent Attribute

Rob Gelhausen picture Rob Gelhausen · Apr 6, 2018 · Viewed 12.6k times · Source

I have a Woocommerce variable product. I need to get the attribute (pa_brand) of the parent of that variation? Here is the code I have which is not returning anything. A better way to ask this question may be how can I get a product variation from a product id?

global $product;
global $post;
$post_id = $post->ID;
$parent_id = wp_get_post_parent_id( $post_id );
$brand = $product->get_attribute( 'pa_brand' );

Answer

Sarathlal N picture Sarathlal N · Dec 28, 2018

@Rob Gelhausen already answered it as a comment for the question. To get more notice, I'm making it as an answer.

To get Main product ID / Parent product from variation product id, we can use below code.

$variation = wc_get_product($variation_id);
$product = wc_get_product( $variation->get_parent_id() );

To get attribute, we can use below code.

$brand = $product->get_attribute( 'pa_brand' );