Search code examples
phpwordpressmethodswoocommerceproduct-variations

Get weight value from WooCommerce variations of a variable product


I am working on a plugin that auto adjusts product prices. All of my products are variable products which has made this tougher than I can solve.

if( $product->is_type( 'variable' ) ){
                           
  foreach ( $product->get_available_variations() as $key => $variation ) {
                                
    foreach ($variation['attributes'] as $attribute ) {

      if ( ! $attribute->get_weight() ) {

I have a check to make sure the product is variable. The only product Attribute is 'Size'. Here I have 4-8 different Size Variations per product. Each of these have a weight value which seemed to be default implemented by Woocommerce. I am unable to get the weight though from each variation. Curious if I am calling get_weight() from the wrong place, or if there is a different method for this. get_weight() of course does not work so I wonder if getting attributes from variations is completely wrong?


Solution

  • Using WC_Variable_Product get_visible_children() (or get_children()) method, try:

    global $product; // If needed | or $product = wc_get_product( $product_id );
    
    if( $product->is_type( 'variable' ) ){
        foreach ( $product->get_visible_children() as $variation_id ) {
            $variation = wc_get_product( $variation_id ); // Get the product variation object
            $weight    = $variation->get_weight(); // Get weight from variation
    
            if ( ! $weight ) {
                echo '<div>' __("No weight") . '</div>';
            } else {
                echo '<div><strong>' __("Weight") . ':</strong> ' . wc_format_weight( $weight ) . '</div>';
            }
        }
    }
    

    or you can use WC_Variable_Product get_available_variations() as follows:

    global $product; // If needed | or $product = wc_get_product( $product_id );
    
    if( $product->is_type( 'variable' ) ){
        foreach ( $product->get_available_variations() as $key => $variation_data ) {
            $weight = $variation_data['weight']; // Get weight from variation
    
            if ( ! $weight ) {
                echo '<div>' __("No weight") . '</div>';
            } else {
                echo '<div><strong>' __("Weight") . ':</strong> ' . $variation_data['weight_html'] . '</div>';
            }
        }
    }
    

    Both code snippet works.