Add and save admin product variations custom field in Woocommerce

丶灬走出姿态 提交于 2019-11-29 15:57:08

In your last hooked function you have a missing argument, which is a similar to $loop argument in your 3rd function. So I have maid little changes in your code:

// Add product Barcode custom field
add_action('woocommerce_product_options_sku','add_barcode_custom_field' );
function add_barcode_custom_field(){
    woocommerce_wp_text_input( array(
        'id'          => '_barcode',
        'label'       => __('Barcode','woocommerce'),
        'placeholder' => 'Scan Barcode',
        'desc_tip'    => 'true',
        'description' => __('This is the Scan barcode field for this product.','woocommerce')
    ) ); 
}

// Save product Barcode custom field
add_action( 'woocommerce_process_product_meta', 'save_barcode_custom_field', 10, 1 );
function save_barcode_custom_field( $post_id ){
    if( isset($_POST['_barcode']) )
        update_post_meta( $post_id, '_barcode', esc_attr( $_POST['_barcode'] ) );
}

// Add Variation Barcode custom field
add_action( 'woocommerce_variation_options_pricing', 'add_barcode_variation_custom_field', 10, 3 );
function add_barcode_variation_custom_field( $loop, $variation_data, $variation ){

    $variation_barcode = get_post_meta($variation->ID,"_barcode", true );
    if( ! $variation_barcode ) $variation_barcode = "";

    woocommerce_wp_text_input( array(
        'id'          => '_barcode['.$loop.']',
        'label'       => __('Variation Barcode','woocommerce'),
        'placeholder' => 'Scan Barcode',
        'desc_tip'    => 'true',
        'description' => __('This is the Scan barcode field for this variation.','woocommerce')
        'value'       => get_post_meta($variation->ID,"_barcode", true ),
    ) );
}

// Save Variation Barcode custom field value
add_action( 'woocommerce_save_product_variation', 'save_barcode_variation_custom_field', 10, 2 );
function save_barcode_variation_custom_field( $variation_id, $i ){
    if( isset($_POST['_barcode'][$i]) )
        update_post_meta( $variation_id, '_barcode', sanitize_text_field($_POST['_barcode'][$i]) );
}

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works for WooCommerce version 2.6+ and 3.0+

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