Sometimes each variation needs its own custom fields. Say if you need to add a unique UPC or EAN code. This turned out to be surprisingly simple. Thanks to Remi Corson for the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/** * Add a UPC and EAN meta fields to variations * * Tutorial: http://www.remicorson.com/woocommerce-custom-fields-for-variations/ */ add_action( 'woocommerce_product_after_variable_attributes', 'jb_woo_variation_add_upc_and_ean_fields', 10, 3); function jb_woo_variation_add_upc_and_ean_fields($loop, $variation_data, $variation) { woocommerce_wp_text_input( array( 'id' => '_upc[' . $variation->ID . ']', 'label' => 'UPC', 'description' => '', 'desc_tip' => 'false', 'value' => get_post_meta( $variation->ID, '_upc', true ), 'placeholder' => '', 'wrapper_class' => 'form-row form-row-first', 'type' => 'text' )); woocommerce_wp_text_input( array( 'id' => '_ean[' . $variation->ID . ']', 'label' => 'EAN', 'description' => '', 'desc_tip' => 'false', 'value' => get_post_meta( $variation->ID, '_ean', true ), 'placeholder' => '', 'wrapper_class' => 'form-row form-row-last', 'type' => 'text' )); } //save the new meta data to the variations add_action( 'woocommerce_save_product_variation', 'jb_woo_add_unit_size_field_save' ); function jb_woo_add_unit_size_field_save($post_id){ $upc = $_POST['_upc'][ $post_id ]; if ( ! empty( $_POST['_upc'] ) ) { update_post_meta( $post_id, '_upc', esc_attr( $upc ) ); } $ean = $_POST['_ean'][ $post_id ]; if ( ! empty( $_POST['_ean'] ) ) { update_post_meta( $post_id, '_ean', esc_attr( $ean ) ); } } |
PS. You should check out Remi’s page for pretty much ANYTHING Woocommerce related. It is basically an infinite well of Woo knowledge.