We needed another field in our products for Prod ref/Cat numbers and I found the bit of code below which works perfectly.
I now need to add a second field for Nominal Codes used by the accountants software.
I tried using the below code again, adjusted for the new field, but it didn't work.
function jk_add_custom_sku() {
$args = array(
'label' => __( 'Custom SKU', 'woocommerce' ),
'placeholder' => __( 'Enter custom SKU here', 'woocommerce' ),
'id' => 'jk_sku',
'desc_tip' => true,
'description' => __( 'This SKU is for internal use only.', 'woocommerce' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_sku', 'jk_add_custom_sku' );
function jk_save_custom_meta( $post_id ) {
// grab the SKU value
$sku = isset( $_POST[ 'jk_sku' ] ) ? sanitize_text_field( $_POST[ 'jk_sku' ] ) : '';
// grab the product
$product = wc_get_product( $post_id );
// save the custom SKU meta field
$product->update_meta_data( 'jk_sku', $sku );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'jk_save_custom_meta' );
Adding extra fields can be done in a very simple way:
function jk_add_custom_sku() {
$args_1 = array(
'label' => __( 'Custom SKU', 'woocommerce' ),
'placeholder' => __( 'Enter custom SKU here', 'woocommerce' ),
'id' => 'jk_sku',
'desc_tip' => true,
'description' => __( 'This SKU is for internal use only.', 'woocommerce' ),
);
woocommerce_wp_text_input( $args_1 );
// Extra field
$args_2 = array(
'label' => __( 'Nominal codes', 'woocommerce' ),
'placeholder' => __( 'Enter nominal codes here', 'woocommerce' ),
'id' => '_nominal_codes',
'desc_tip' => true,
'description' => __( 'This is for nominal codes.', 'woocommerce' ),
);
woocommerce_wp_text_input( $args_2 );
}
add_action( 'woocommerce_product_options_sku', 'jk_add_custom_sku' );
// Save
function jk_save_custom_meta( $product ){
if( isset($_POST['jk_sku']) ) {
$product->update_meta_data( 'jk_sku', sanitize_text_field( $_POST['jk_sku'] ) );
}
// Extra field
if( isset($_POST['_nominal_codes']) ) {
$product->update_meta_data( '_nominal_codes', sanitize_text_field( $_POST['_nominal_codes'] ) );
}
}
add_action( 'woocommerce_admin_process_product_object', 'jk_save_custom_meta', 10, 1 );