Skip to content

Instantly share code, notes, and snippets.

@trey8611
Created July 17, 2024 18:40
Show Gist options
  • Save trey8611/344444947076fee32f528cb9d243595c to your computer and use it in GitHub Desktop.
Save trey8611/344444947076fee32f528cb9d243595c to your computer and use it in GitHub Desktop.
Import swatches image into YITH WooCommerce Color, Image & Label Variation Swatches Premium

This snippet sets the swatch image for the "pa_shade" attribute assigned to each variation. Read the comments for tips on customizing it for other attributes and restricting it to a certain import ID.

# ************************************************************************************************************
# * Import swatches image for the "YITH WooCommerce Color, Image & Label Variation Swatches Premium" plugin. *
# ************************************************************************************************************

add_action( 'wp_all_import_variable_product_imported', 'wpai_wp_all_import_variable_product_imported', 10, 1 );
function wpai_wp_all_import_variable_product_imported( $post_parent ) {
	# Optionally restrict to a certain import ID.
	# For example, to only run for import ID 124:
	# if ( '124' != wp_all_import_get_import_id() ) return;
	
    $parent = wc_get_product( $post_parent );
	if ( ! $parent ) return;
	$children = $parent->get_children();
	if ( empty( $children ) ) return;
	
	foreach ( $children as $vid ) {
		$variation = wc_get_product( $vid );
		if ( ! $variation ) continue;

		# Change "pa_shade" to the correct attribute if it's different.
		# For example, a common one might be "pa_color".
		$shade = $variation->get_attribute( 'pa_shade' );
		$term = get_term_by( 'name', $shade, 'pa_shade' );

		if ( $term && ! is_wp_error( $term ) ) {
			$img_url = wp_get_attachment_url( $variation->get_image_id() );
			update_term_meta( $term->term_id, '_yith_wccl_value', $img_url );
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment