Victor Hopman
Victor Hopman

Reputation: 23

Woocommerce - Get variation SKU from Bundled Products

I use WooCommerce with a Bundled Products plugin to display a page where people can choose options to configure a product. Each option is a product with variations. To get the variations from all 4 products I use the code below. Which used to work fine until I upgraded to WC 3 (oops). Now I get an error that the sku is empty. Do I need to change the way I get the SKU from the products?

   do_action( 'woocommerce_before_bundled_items', $product );

foreach ( $bundled_items as $bundled_item ) {

    /**
     * 'woocommerce_bundled_item_details' hook
     *
     * @hooked wc_pb_template_bundled_item_details_wrapper_open  -   0
     * @hooked wc_pb_template_bundled_item_thumbnail             -   5
     * @hooked wc_pb_template_bundled_item_details_open          -  10
     * @hooked wc_pb_template_bundled_item_title                 -  15
     * @hooked wc_pb_template_bundled_item_description           -  20
     * @hooked wc_pb_template_bundled_item_product_details       -  25
     * @hooked wc_pb_template_bundled_item_details_close         -  30
     * @hooked wc_pb_template_bundled_item_details_wrapper_close - 100
     */
    do_action( 'woocommerce_bundled_item_details', $bundled_item, $product );
 $variations = $bundled_item->get_product_variations();
 foreach($variations as $variation) {
    if($variation['sku'] == 'colors') {
      $bi['colors'] = $bundled_item;
      continue 2;
    }
    if($variation['sku'] == 'material') {
      $bi['material'] = $bundled_item;
      continue 2;
    }
    if($variation['sku'] == 'corners') {
      $bi['corners'] = $bundled_item;
      continue 2;
    }
    if($variation['sku'] == 'text') {
      $bi['text'] = $bundled_item;
      continue 2;
    }
 }
    do_action( 'woocommerce_after_bundled_items', $product );

}

Upvotes: 2

Views: 2561

Answers (1)

MWoodruff
MWoodruff

Reputation: 11

This code works for me in 3.0 to find the SKU of variations of each bundled item, or of an item in a bundle that has no variations:

//Check for Variation ID first & use Variation, if it exists
$product_variation_id = $bundled_item->get_variation_id();        
// Check if product has variation.
if ($product_variation_id){
   $product = new WC_Product_Variation($product_variation_id);            
}else{
   $product = $bundled_item->get_product();                
}
$sku = $product->get_sku();

Upvotes: 1

Related Questions