Help to add custom field to woocommerce

Hi,

I’m trying to add custom fields to woocommerce. So far i have the fields added just where i want them, but it won’t save them. The guide i followed just showed to add one field, but i needed to SKU fields in Woocommerce. I’m sure it’s just me as a newbie to PHP not knowing how to save 2 strings. can anybody help me with the right code.

Link to guide: https://www.liquidweb.com/blog/custom-fields-woocommerce-products/

My code:
function add_custom_sku() {
//SKU2
$args = array(
‘label’ => __( ‘SKU 2’, ‘woocommerce’ ),
‘placeholder’ => __( ‘Skriv 2 varenummer her’, ‘woocommerce’ ),
‘id’ => ‘sku2’,
‘desc_tip’ => true,
‘description’ => __( ‘This is SKU2’, ‘woocommerce’ ),
);
woocommerce_wp_text_input( $args );

//SKU3

$args = array(
‘label’ => __( ‘SKU 3’, ‘woocommerce’ ),
‘placeholder’ => __( ‘Skriv 3 varenummer her’, ‘woocommerce’ ),
‘id’ => ‘sku3’,
‘desc_tip’ => true,
‘description’ => __( ‘This is SKU3’, ‘woocommerce’ ),
);
woocommerce_wp_text_input( $args );
}
add_action( ‘woocommerce_product_options_sku’, ‘add_custom_sku’ );

function save_custom_meta( $post_id )
{
// grab the SKU value
$sku = isset( $_POST[ ‘sku2’ ] ) ? sanitize_text_field( $_POST[ ‘sku2’ ] ) : ‘’;
$sku2 = isset( $_POST[ ‘sku3’ ] ) ? sanitize_text_field( $_POST[ ‘sku3’ ] ) : ‘’;

// grab the product
$product = wc_get_product( $post_id );

// save the custom SKU meta field
$product->update_meta_data( ‘sku2’, $sku );
$product->update_meta_data( ‘sku3’, $sku );
$product->save();
}

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service