Add a barcode meta box to WooCommerce

September 5, 2014 . by Aaron B #Barcode#Function#Product#WooCommerce

You can now download a plugin from WordPress.org to add a barcode and ISBN to your WooCommerce website, This post had a lot of interest so I decided to build the plugin.

On a recent project, the client asked me if I could add a barcode to products on WooCommerce. Now, one way to achieve this would be to add one of the many WordPress plugins which are readily available. However, that isn’t necessarily the best solution. In fact, the problem with doing this as that you’re adding unnecessary ‘bloat’ to your site and anybody who reads my blog on a regular basis will know that I really hate bloat. I set about solving the problem by writing some code to add to the themes functions.php file.  It’s fairly straightforward and very effective. So, if you’d like to add this function to your own site, here’s how:

To get started, add the following to your themes functions.php:

// Add boarcode to products

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields() {

global $woocommerce, $post;
// Text Field
woocommerce_wp_text_input(
array(
'id' => 'barcode',
'label' => __( 'Barcode', 'woocommerce' ),
'placeholder' => 'barcode here',
'desc_tip' => 'true',
'description' => __( 'Product barcode.', 'woocommerce' )
)
);
}
function woo_add_custom_general_fields_save( $post_id ){

// Textarea
$woocommerce_barcode = $_POST['barcode'];
if( !empty( $woocommerce_barcode ) )
update_post_meta( $post_id, 'barcode', esc_html( $woocommerce_barcode ) );

}

Once you’ve done this and saved it to the themes functions.php you’ll  be able to see your new text box in the product edit page.

barcode

Looks pretty good, doesn’t it? Now, to display the saved data in this new text box we use a simple get_post_meta. All you need to do is add the following code where you would like to display the barcode on the product page:

<?php echo get_post_meta( get_the_ID(), 'barcode', true ); ?>

And there you have it; a really simple, bloat free way of adding a barcode meta box to WooCommerce without weighing your site down with heavy plugins you don’t need. All you’re adding is simple, clean code.

O.K, so now that I’ve told you how it’s done, why not have a go at adding this to your site?

How did you get on?

Get in touch and share your successes, questions and any gripes with me, I’m always happy to talk WordPress!

You can now download The Pro version of the plugin from us to add a barcode, ISBN & Amazon ASIN to your WooCommerce website. The Pro version works with simple & veritable products unlike the free version.