How to add a (second) custom sku field to WooCommerce products?

巧了我就是萌 提交于 2020-07-21 06:17:27

问题


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' );


回答1:


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 );


来源:https://stackoverflow.com/questions/61290387/how-to-add-a-second-custom-sku-field-to-woocommerce-products

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!