Skip to content

Instantly share code, notes, and snippets.

@trey8611
Created February 18, 2022 21:06
Show Gist options
  • Save trey8611/5e1ccf2f5aaf010885e42f10350923d0 to your computer and use it in GitHub Desktop.
Save trey8611/5e1ccf2f5aaf010885e42f10350923d0 to your computer and use it in GitHub Desktop.
[WooCommerce Variation Swatches and Photos] #wpallimport #woocommerce #swatches

This is an example snippet that imports swatches added by this plugin: https://woocommerce.com/products/variation-swatches-and-photos/. This example only works with the variation attribute "Colour" and it uses the images uploaded to the variations as the swatch images. It is highly likely that you will need to modify it for your specific use case.

add_action( 'wp_all_import_variable_product_imported', 'my_set_swatches', 10, 1 );


function my_set_swatches( $id ) {
	$product = wc_get_product( $id );
	if ( ! $product ) return;
	if ( ! $product->is_type( 'variable' ) ) return;
	
	$variations      = $product->get_children();
	if ( empty( $variations ) ) return;
	$variation_atts  = array();
	
	foreach ( $variations as $v_id ) {
		$v_product = wc_get_product( $v_id );
		if ( ! $v_product ) continue;
		
		$color_attribute  = $v_product->get_attribute( 'colour' );
		$att_slug         = wc_sanitize_taxonomy_name( $color_attribute );
		$variation_atts[] = $att_slug;
		
		$term            = get_term_by( 'slug', $att_slug, 'pa_colour' );
		$variation_img   = $v_product->get_image_id();
		
		update_term_meta( $term->term_id, 'pa_colour_swatches_id_type', 'photo' );
		update_term_meta( $term->term_id, 'pa_colour_swatches_id_photo', $variation_img );
		update_term_meta( $term->term_id, 'pa_colour_swatches_id_color', '#FFFFFF' );
	}
	
	if ( empty( $variation_atts ) ) return;
	
	$colour_key = md5( str_replace( "-", "_", sanitize_title( 'pa_colour' ) ) );
	
	$swatch_settings                          = array( $colour_key => array() );
	$swatch_settings[ $colour_key ]['type']   = 'term_options';
	$swatch_settings[ $colour_key ]['layout'] = 'label_above';
	$swatch_settings[ $colour_key ]['size'] = 'swatches_image_size';
	
	foreach ( $variation_atts as $v_att ) {
		$v_key = md5( str_replace( "-", "_", sanitize_title( $v_att ) ) );
		$swatch_settings[ $colour_key ]['attributes'][ $v_key ] = array(
			'type'  => 'color',
            'color' => '#FFFFFF',
            'image' => 0
		);
	}
	
	update_post_meta( $id, '_swatch_type_options', $swatch_settings );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment