If you use Variable products in WooCommerce it is handy to inform the customer of which variation they have added to their shopping basket. This is assuming you are using WooCommerce 3.0+.

We are going to be adding variation data to the WooCommerce Basket page by adding a function to the ‘woocommerce_get_item_data’ filter. The filter passes the $data variable which is an array of text as name, value pairs which is printed to screen and the $cart_item variable which holds all the info on the product.

function nnm_output_variation_choices($data,$cart_item){
	$item_data = $cart_item['data'];
	if(!empty($item_data) && $item_data->is_type( 'variation' )) {
		$attrs = $item_data->get_attributes();
		if(is_array($attrs) && !empty($attrs)){
			foreach($attrs as $attkey => $attval){
				$data[] = array(
					'name' => ucfirst(str_replace('pa_', '', $attkey)),
					'value' => $attval,
				);
			}
		}
	}
	return $data;
}
add_filter( 'woocommerce_get_item_data', 'nnm_output_variation_choices',10,2);

This code would live in the functions.php file of your theme. It is only needed when WooCommerce is active so I tend to wrap it up in my WooCommerce setup process, where all the code dependent on WooCommerce is kept in a separate file and fired only after we’ve checked whether WooCommerce is active, which goes something more like this:

define('THEME_URL', get_stylesheet_directory() );

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) { 
	$file = THEME_URL . '/woo/woocommerce-setup.php';
	$filepath = locate_template($file);		
	require_once $filepath;
}

I’m checking WooCommerce is active and if true I’m loading my woocommerce functions: ‘/woo/woocommerce-setup.php’. If I happen to turn off the WooCommerce plugin the site will carry on regardless rather than throwing out loads of errors. Handy!

Leave a Reply

Privacy & more..

Cookie Consent Policy