wordpresswoocommerceproductinventory

Add a barcode field to Product Inventory in WooCommerce


I would like to add a Barcode Field under my SKU code field in my Inventory settings of my Product. I'd like to use this as I'm working with WooCommerce POS and based on the barcode field I could do a scan, but still use the SKU fields for the real SKU codes.

How can I accomplish this without the use of any plugins. (Read: Function.php code).

I already tried using the following code, but without any success:

//Add barcode to the product inventory tab
add_action('woocommerce_product_options_inventory_product_data','add_barcode');
function add_barcode(){
    global $woocommerce,$post;
    woocommerce_wp_text_input(
        array(
            'id'          => '_barcode',
            'label'       => __('Barcode','woocommerce'),
            'placeholder' => 'Scan Barcode',
            'desc_tip'    => 'true',
            'description' => __('Scan barcode.','woocommerce')
        ));
}
//Save Barcode Field
function add_barcode_save($post_id){
    if(isset($_POST['_barcode'])){
        update_post_meta($post_id,'_barcode',sanitize_text_field($_POST['_barcode']));
    }else{
        delete_meta_data($post_id,'_barcode',sanitize_text_field($_POST['_barcode']));
    }
}
add_action('woocommerce_process_product_meta','add_barcode_save');
//Set POS Custom Code
function pos_barcode_field(){return '_barcode';}
add_filter('woocommerce_pos_barcode_meta_key','pos_barcode_field');

As the code just doesn't seem to have any effect at all when added to the Functions.php. I'm using the Fruitful theme if that changes anything.

Does anyone know what I'm doing wrong here? Thanks in advance for the help you could provide me!


Solution

  • As I mentioned above, your code should be a plugin. Here's your code updated for WooCommerce 3.0. It isn't backcompatible though.

    function add_barcode(){
        woocommerce_wp_text_input(
            array(
                'id' => '_barcode',
                'label' => __( 'Barcode', 'your-plugin' ),
                'placeholder' => 'Scan Barcode',
                'desc_tip' => 'true',
                'description' => __( "Scan the product's barcode.", "your-plugin" )
            )
        );
    }
    add_action('woocommerce_product_options_inventory_product_data','add_barcode');
    
    
    function add_barcode_save( $product ){
        if( isset( $_POST['_barcode'] ) ) {
            $product->update_meta_data( '_barcode', sanitize_text_field( $_POST['_barcode'] ) );
        } else {
            $product->delete_meta_data( '_barcode' );
        }
    }
    add_action( 'woocommerce_admin_process_product_object', 'add_barcode_save' );
    

    Then anywhere you need to retrieve the meta data, you can do so like this:

    $product = wc_get_product( $product_id );
    $product->get_meta( '_variable_billing' );