Skip to content

WooCommerce: Produce a list of variations associated with a product, by label, based on product availability.

This code will not be useful for shops set up with stock management in the way that WooCommerce anticipates. The objective here had specifically to do with a shop built on an earlier version of WooCommerce, and a peculiar set of preferences and habitual practices that, in short, required the ability to display the labels for temporarily unavailable items without set prices. The code may be useful for other applications requiring variations associated with a product, and their labels.

/*
 * PRODUCE A LIST AFTER VARIATIONS TABLE OF UNAVAILABLE PRODUCT VARIATIONS, BY NAME
 * along with CSS formatting, allows for restoration of combined pre-WooCommerce 3 and 
 * Variations Table plugin display features
 * meaning Discus staff will not have to change inventory or customary practices
 */ 
if ( function_exists( 'vt_woocommerce_variable_add_to_cart' )  ) : 

	add_action( 'woocommerce_after_single_product_summary', 'ckm_add_to_var_table', 9 ); //fires after vt function

	function ckm_add_to_var_table() {
		
		global $product; 
		
		if ( $product->is_type( 'variable' ) ) {
		
			//GET ALL VARIATIONS BY ID
			$variation_ids_array = $product->get_children(); 
			
			//GET ACTUALLY AVAILABLE VARIATIONS AS OBJECTS
			$avail_vars = $product->get_available_variations() ;
			
			//GET THEIR PRODUCT IDS (since WooC 3.0)
			foreach ( $avail_vars as $avail_var ) { 
				
				$avail_var_ids[] = $avail_var['variation_id'] ;
				
			} 
			
			//GET IDS OF UNAVAILABLE PRODUCTS
			$unavailable_ids = array_diff( $variation_ids_array, $avail_var_ids ) ;
			
			//ADD TO VARTABLE
			
			if ( $unavailable_ids ) {
			
				$output = '<div id="vartable-div">
								<table id="vartable-plus" class="table">
									<tbody>' ;
							
				foreach ($unavailable_ids as $unavailable_id ) {
					
					$prod = wc_get_product( $unavailable_id ) ; 
					$oos_name = wc_get_formatted_variation( $prod->get_variation_attributes(), true, false ) ;
					
					$output .= '<tr><td>' .  $oos_name . '</td><td><i>Not currently available</i></td></tr>' ;
				
				}
			
				$output .= '		</tbody>
								</table>
							</div><!--/ END EXTRA VARIATIONS TABLE -->' ;
							
				echo $output;
				
			}
			
		}
		
	}
	
endif;

Leave a Reply