How To Add WooCommerce Custom Product Fields (ok)

https://www.ibenic.com/how-to-add-woocommerce-custom-product-fields/

https://rudrastyh.com/woocommerce/product-data-metabox.html

Ví dụ đã hoàn thành:

add_action( 'woocommerce_product_options_inventory_product_data', 'misha_adv_product_options');
function misha_adv_product_options(){
  $args = array(
    'label'   => 'Xuất xứ',
    'placeholder' => ' Ví dụ: Hà Nội',
    'class' => '',
    'style' => '',
    'wrapper_class' => '',
    'value' => get_post_meta( get_the_ID(), 'super_product', true ), // if empty, retrieved from post meta where id is the meta_key
    'id' => 'super_product', // required
    'name' => 'super_product', //name will set from id if empty
    'type' => '',
    'desc_tip' => true,
    'data_type' => '',
    'custom_attributes' => '', // array of attributes 
    'description' => 'Sản phẩm xuất xứ từ đâu'
  );
  echo "<style>.woocommerce-help-tip {display:none;}#super_product { padding-left: 10px; }</style>";
  echo '<div class="options_group">';
    woocommerce_wp_text_input( $args );
  echo '</div>';
} 
add_action( 'woocommerce_process_product_meta', 'misha_save_fields', 10, 1 );
function misha_save_fields( $post_id ){
  $custom_field_value = isset( $_POST['super_product'] ) ? $_POST['super_product'] : '';
  $product = wc_get_product( $post_id );
  $product->update_meta_data( 'super_product', $custom_field_value );
  $product->save();
}

meta.php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

global $product;
?>
<div class="product_meta">
	<?php do_action( 'woocommerce_product_meta_start' ); ?>
	<?php echo wc_get_product_tag_list( $product->get_id(), ', ', '<span class="tagged_as">' . _n( 'Hãng sản xuất:', 'Hãng sản xuất:', count( $product->get_tag_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>
	<?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
		<span class="sku_wrapper"><?php esc_html_e( 'Mã sản phẩm:', 'woocommerce' ); ?> <span class="sku"><?php echo ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' ); ?></span></span>
	<?php endif; ?>
	<?php if(get_post_meta( $product->get_id(), 'super_product', true )){
		echo '<span class="sku_wrapper">Xuất xứ: <span class="area">'.get_post_meta( $product->get_id(), "super_product", true ).'</span></span>';
	} ?>
	<?php do_action( 'woocommerce_product_meta_end' ); ?>
</div>

When working on a WooCommerce add-on or a custom solution, you will sometimes have to add some WooCommerce custom product fields so that you can save additional data for each product. In this tutorial we will go through adding fields to existing product tabs and also create a new product tab.

Adding WooCommerce Custom Product Fields

When you want to add a custom product field inside a WooCommerce metabox, you can add it creating a custom input. That is alright and you can work with that. But, creating custom product fields can be a cumbersome task if you want to add multiple fields.

Creating your own custom markup for the product fields is only fine when you are creating a custom layout in the metabox. But, if you are just going to use regular inputs, then use the WooCommerce product fields functions. It will be much easier for you to create many product fields and you will also the WooCommerce API for that.

Let’s learn about those functions.

Text Field

The text input is the basic input field that can receive a different type such as text, number, date etc. Everything that HTML5 does support, you can add there. But, don’t use it if you are going to add a radio input or a checkbox. There are two other functions for that. The function name for adding the text input as a WooCommerce product field is woocommerce_wp_text_input.

<?php

$args = array(

'label' => '', // Text in Label

'placeholder' => '',

'class' => '',

'style' => '',

'wrapper_class' => '',

'value' => '', // if empty, retrieved from post meta where id is the meta_key

'id' => '', // required

'name' => '', //name will set from id if empty

'type' => '',

'desc_tip' => '',

'data_type' => '',

'custom_attributes' => '', // array of attributes

'description' => ''

);

woocommerce_wp_text_input( $args );

view rawtext_input.php hosted with ❤ by GitHub

Checkbox Field

The checkbox input receives some other parameters and it’s created with the function woocommerce_wp_checkbox. The parameter cbvalue is the value which will make the checkbox checked. This value will be matched againts the parameter value. If they have the same value, the checkbox field will be checked.

<?php

$args = array(

'label' => '', // Text in Label

'class' => '',

'style' => '',

'wrapper_class' => '',

'value' => '', // if empty, retrieved from post meta where id is the meta_key

'id' => '', // required

'name' => '', //name will set from id if empty

'cbvalue' => '',

'desc_tip' => '',

'custom_attributes' => '', // array of attributes

'description' => ''

);

woocommerce_wp_checkbox( $args );

view rawcheckbox_input.php hosted with ❤ by GitHub

Radio Field

To create the radio input, we will need to use the function woocommerce_wp_radio. To create various radio options, you will need to use the parameter options. This will be an associative array where the key will be the value of the input and the value will be text of that input.

<?php

$args = array(

'label' => '', // Text in Label

'class' => '',

'style' => '',

'wrapper_class' => '',

'value' => '', // if empty, retrieved from post meta where id is the meta_key

'id' => '', // required

'name' => '', //name will set from id if empty

'options' => '', // Options for radio inputs, array

'desc_tip' => '',

'description' => ''

);

woocommerce_wp_radio( $args );

view rawradio_input.php hosted with ❤ by GitHub

Textarea Field

The textarea input is done with the function woocommerce_wp_textarea_input. The parameters are almost the same as for the text input but we can also set the rows and columns in parameters rows and cols.

<?php

$args = array(

'label' => '', // Text in Label

'placeholder' => '',

'class' => '',

'style' => '',

'wrapper_class' => '',

'value' => '', // if empty, retrieved from post meta where id is the meta_key

'id' => '', // required

'name' => '', //name will set from id if empty

'rows' => '',

'cols' => '',

'desc_tip' => '',

'custom_attributes' => '', // array of attributes

'description' => ''

);

woocommerce_wp_textarea_input( $args );

view rawtextarea_input.php hosted with ❤ by GitHub

Select Field

The select input has something similar with the radio input. The parameter options will be used to create all the options. The function that will create the select field is woocommerce_wp_select.

<?php

$args = array(

'label' => '', // Text in Label

'class' => '',

'style' => '',

'wrapper_class' => '',

'value' => '', // if empty, retrieved from post meta where id is the meta_key

'id' => '', // required

'name' => '', //name will set from id if empty

'options' => '', // Options for select, array

'desc_tip' => '',

'custom_attributes' => '', // array of attributes

'description' => ''

);

woocommerce_wp_select( $args );

view rawselect_input.php hosted with ❤ by GitHub

Hidden field

The hidden field can be used for some data that will be used internally and will not be needed to change by the user.

<?php

$args = array(

'value' => '',

'class' => '',

'id' => ''

);

woocommerce_wp_hidden_input( $args );

view rawhidden_input.php hosted with ❤ by GitHub

Default Product Tabs

Now that we know all the functions that we can use to add our own WooCommerce custom product fields, let’s learn about the default product tabs. There are 7 default tabs:

  • General

  • Inventory

  • Shipping

  • Linked Products

  • Attributes

  • Variations

  • Advanced

Some of those tabs will be only shown for a specific type of the product. In each of those tabs we can hook our own function to add our custom product fields. Here are the hooks we can use:

General Tab

  • woocommerce_product_options_pricing

  • woocommerce_product_options_downloads

  • woocommerce_product_options_tax

  • woocommerce_product_options_general_product_data

Inventory Tab

  • woocommerce_product_options_sku

  • woocommerce_product_options_stock

  • woocommerce_product_options_stock_fields

  • woocommerce_product_options_stock_status

  • woocommerce_product_options_sold_individually

  • woocommerce_product_options_inventory_product_data

Shipping Tab

  • woocommerce_product_options_dimensions

  • woocommerce_product_options_shipping

Linked Products Tab

  • woocommerce_product_options_related

Attributes

  • woocommerce_product_options_attributes

Variations

  • woocommerce_variable_product_bulk_edit_actions

Advanced

  • woocommerce_product_options_reviews

  • woocommerce_product_options_advanced

Example

Here is an example of the general tab and some WooCommerce custom product fields.

<?php

add_action( 'woocommerce_product_options_pricing', 'my_woo_custom_price_field' );

/**

* Add a Christmas Price field

**/

function my_woo_custom_price_field() {

$field = array(

'id' => 'christmas_price',

'label' => __( 'Christmas Price', 'textdomain' ),

'data_type' => 'price' //Let WooCommerce formats our field as price field

);

woocommerce_wp_text_input( $field );

}

add_action( 'woocommerce_product_options_general_product_data', 'my_woo_custom_fields' );

/**

* Add a select Field at the bottom

*/

function my_woo_custom_fields() {

$select_field = array(

'id' => 'my_select',

'label' => __( 'Custom Select', 'textdomain' ),

'options' => array(

'value1' => __( 'Text 1', 'textdomain' ),

'value2' => __( 'Text 2', 'textdomain' )

)

);

woocommerce_wp_select( $select_field );

}

view rawgeneral_tab.php hosted with ❤ by GitHub

Custom Product Tab

Some add-ons or solutions will also require additional product tabs. We can add custom product tabs using a filter or an action:

  • Filter: woocommerce_product_data_tabs

  • Action: woocommerce_product_write_panel_tabs

If we are going to use the action, then we will need to write the whole markup ourselves. If we are going to use the filter, we just need to extend the existing tab array with our new one. We also need to add the panel that we will show when our tab is clicked.

I will now show you both ways how to add the tabs.

Custom Tab with Filter

When adding a tab using the filter, you need to define the label, target and class. The target will be the attribute id of our panel.

<?php

add_filter( 'woocommerce_product_data_tabs', 'my_custom_tab' );

/**

* Adding a custom tab

*/

function my_custom_tab( $tabs ) {

$tabs['custom_tab'] = array(

'label' => __( 'My Custom Tab', 'textdomain' ),

'target' => 'the_custom_panel',

'class' => array(),

);

return $tabs;

}

view rawtab_filter.php hosted with ❤ by GitHub

Custom Tab with Action

When defining our custom tab with the action, then we need to create the whole markup. This means adding a li item and also the a with the target as the value in href.

<?php

add_action( 'woocommerce_product_write_panel_tabs', 'my_custom_tab_action' );

/**

* Adding a custom tab

*/

function my_custom_tab_action() {

?>

<li class="custom_tab">

<a href="#the_custom_panel">

<span><?php _e( 'My Custom Tab', 'textdomain' ); ?></span>

</a>

</li>

<?php

}

view rawtab_action.php hosted with ❤ by GitHub

Custom Panel

Since we have our custom tab defined, we also need to add a panel that will show up when clicking our tab. We are adding a custom panel by hooking into woocommerce_product_data_panels.

<?php

add_action( 'woocommerce_product_data_panels', 'custom_tab_panel' );

function custom_tab_panel() {

?>

<div id="the_custom_panel" class="panel woocommerce_options_panel">

<div class="options_group">

<?php

$field = array(

'id' => 'my_custom_input',

'label' => __( 'Custom Input', 'textdomain' ),

);

woocommerce_wp_text_input( $field );

?>

</div>

</div>

<?php

}

view rawtab_panel.php hosted with ❤ by GitHub

Be sure to add the same value in the attribute id that you have defined as the target.

Saving WooCommerce Custom Product Fields

The last part that we also need to define is how to save our product field. To save the product fields, you need to use the action woocommerce_process_product_meta.

<?php

add_action( 'woocommerce_process_product_meta', 'save_custom_field' );

function save_custom_field( $post_id ) {

$custom_field_value = isset( $_POST['my_custom_input'] ) ? $_POST['my_custom_input'] : '';

$product = wc_get_product( $post_id );

$product->update_meta_data( 'my_custom_input', $custom_field_value );

$product->save();

}

view rawsave_product.php hosted with ❤ by GitHub

We are just getting the WC_Product object and then update/add a new metadata. After that, we are calling the method save() to save every new change.

Conclusion

Since WooCommerce uses the WordPress Plugin API, you can customize every possible detail. To add WooCommerce custom product fields, you can use various actions and filters to achieve it. In this tutorial, you have learned a lot about custom product fields and actions/filter that you can use to do that.

If you have ever created your own custom product fields, please do share your experience in the comments below.

If you would like to learn more about WooCommerce, you can check out my eBook:

Book WooCommerce for Developer to buyBecome a Sponsor

Want to Learn more?

Get my articles to your inbox and read them with your email app, phone or just get notified on my new products. Join other 500+ subscribers.I agree to subscribe to your Newsletter and Product Emails as described in your Privacy Policy.SUBSCRIBE

Or you can support my work by subscribing to my premium content here.Get Access to Premium Content

LIKE THIS:

Loading...

Posted by Igor Benic

Web Developer who mainly uses WordPress for projects. Working on various project through Codeable & Toptal. Author of several ebooks at https://leanpub.com/u/igorbenic. All Posts Website

SHARE THIS:

24 Comments

  1. ts AUGUST 1, 2017 AT 2:26 PM

    Thanks a lot! This was very helpful for a project I’m working on!

    Reply

    1. Igor Benic AUGUST 2, 2017 AT 11:31 AM

      I am really glad it helps! 🙂

      Reply

  2. Matt AUGUST 31, 2017 AT 5:10 PM

    This is the best guide, and I’ve looked through tens of those. Thank you!

    How come there’s no mention of this in woocommerce docs? Or at least I couldn’t find it 😛

    Reply

    1. Igor Benic AUGUST 31, 2017 AT 9:39 PM

      Hi Matt, I am really glad it’s helpful to you. I am not sure if that’s somewhere in the WooCommerce docs.

      It is such a big plugin so it might be hard to cover everything. I usually browse the core code of the plugin as I find it really good to learn how something works:)

      Reply

  3. shalini DECEMBER 15, 2017 AT 11:55 PM

    how to add a file upload field in product new setting panel

    Reply

    1. Igor Benic DECEMBER 16, 2017 AT 2:53 PM

      To add an upload field you would need to add a file input <input type="file" name="custom_file" />. After that, you would need to check on the backend part with the global $_FILES if that input was filled. After that you will have to process the upload. I have an article on uploading files through AJAX. You may find the upload code helpful there: https://www.ibenic.com/wordpress-file-upload-with-ajax/

      Reply

  4. Rita César JANUARY 21, 2018 AT 10:12 PM

    Hi, I wrote this code in my theme functions, and dnot work

    add_action( ‘woocommerce_product_options_general_product_data’, ‘my_custom_capacidad_field’ ); function my_custom_capacidad_field() {

    $field = array( ‘id’ => ‘capacidad’, ‘placeholder’ => ‘capacidad’, ‘label’ => __(‘Capacidad’, ‘woocommerce’) );

    woocommerce_wp_text_input( $field ); }

    add_action( ‘woocommerce_process_product_meta’, ‘save_custom_field’ ); function save_custom_field( $post_id ) {

    $custom_field_value = isset( $_POST[‘capacidad’] ) ? $_POST[‘capacidad’] : ”;

    $product = wc_get_product( $post_id ); $product->update_meta_data( ‘capacidad’, $custom_field_value ); $product->save(); }

    Reply

Handle WooCommerce Product Settings

Let me show the beautiful way of adding options to WooCommerce products.Jul 3rd, 2019/13 comments

I understand that if you already read my metabox tutorial and use my metabox plugin (or maybe another plugin – doesn’t matter), you’re a master of meta boxes 💪 and you can easily create your custom one for CPT WooCommerce product. But I would like to talk about more seamless integration – hooking the default WooCommerce Product Data metabox with tabs.WooCommerce default Product Data meta boxDo you agree with me, that it is much better to add options into this metabox than creating another one?

By the way, if you want to remove Virtual and/or Downloadable checkboxes here, take a look at this tutorial.

How to add some fields to any of the default tabs of Product data metabox

“There is a hook for that!”

Actually there are hooks for each tab, which allows you to add any custom content after the default option fields.

Action hooks#

General tab

Here are 3 action hooks for each option group!

  • First option group with pricing options – woocommerce_product_options_pricing,

  • Second option group, downloadable product settings – woocommerce_product_options_downloads,

  • Third option group, tax settings – woocommerce_product_options_tax.

If you want to create you own option group below, use woocommerce_product_options_general_product_data, simple example:

add_action( 'woocommerce_product_options_general_product_data', 'misha_option_group' );
 
function misha_option_group() {
	echo '<div class="option_group">test</div>';
}

Note, that if you use one of the other 3 hooks, your fields shouldn’t be wrapped into <div class="option_group"> element.

Inventory tab

  • First group, under stock status settings – woocommerce_product_options_stock_status,

  • Second one, woocommerce_product_options_sold_individually.

Or add your custom groups with woocommerce_product_options_inventory_product_data.

Shipping tab

  • First group with product dimension – woocommerce_product_options_dimensions,

  • Second group – woocommerce_product_options_shipping.

Here is no hook for your custom options group 😱 but if you absolutely need it, you can do some tricks with the second hook and closing </div> element.

Linked products tab

Just one hook is here – woocommerce_product_options_related.

Advanced tab

Two hooks are here – woocommerce_product_options_reviews for the reviews option group and woocommerce_product_options_advanced for those who want to create an own option group.

Let’s add some options now!#

The code is below but here are some notes about it:

  • Remember that by default a checked checkbox value is on,

  • It is not necessary to deal with raw HTML, because there are WooCommerce functions for that – woocommerce_wp_checkbox(), woocommerce_wp_text_input(), woocommerce_wp_textarea_input(), woocommerce_wp_select() etc, maybe you already remember some of them from this tutorial.

  • desc_tip (line 10) is a very interesting parameter – if set to true, the value of description will be displayed like a tip, in another case it will printed near the field.

  • It is so awesome that WooCommerce allows to process product metadata with woocommerce_process_product_meta action hook (not with the standard save_post) because in this case we do not have to do any conditional checks (nonces etc).

add_action( 'woocommerce_product_options_advanced', 'misha_adv_product_options');
function misha_adv_product_options(){
 
	echo '<div class="options_group">';
 
	woocommerce_wp_checkbox( array(
		'id'      => 'super_product',
		'value'   => get_post_meta( get_the_ID(), 'super_product', true ),
		'label'   => 'This is a super product',
		'desc_tip' => true,
		'description' => 'If it is not a regular WooCommerce product',
	) );
 
	echo '</div>';
 
}
 
 
add_action( 'woocommerce_process_product_meta', 'misha_save_fields', 10, 2 );
function misha_save_fields( $id, $post ){
 
	//if( !empty( $_POST['super_product'] ) ) {
		update_post_meta( $id, 'super_product', $_POST['super_product'] );
	//} else {
	//	delete_post_meta( $id, 'super_product' );
	//}
 
}

Result of inserting the above code somewhere in functions.php, custom plugin etc.WooCommerce custom product option under the advanced tab.As you can see on the screenshot, description is displayed as a tip, but it could be displayed nearby with desc_tip parameter set to false (or not set at all).

How to add your custom tab with options#

Before just copying the code below, please read this:

  • You can unset any of the default tabs (line 7), using the ids general, shipping, linked_product, attribute, variations, advanced, but I’m not sure it is a good idea to do.

  • Awesome feature that allows you to show or hide tabs or sections or single option fields for specific product types! (line 10 or 43). Just use some of these classes show_if_simple, show_if_grouped, show_if_external, show_if_variable, show_if_virtual, show_if_downloadable.

  • Use the priority parameter (line 13) if you would like your tab to be displayed at the specific position.

  • In the below example there is just one option group but you can use more groups.

  • Do not forget to save the settings with woocommerce_process_product_meta action hook, I believe you can do it yourself 😁

/*
 * Tab
 */
add_filter('woocommerce_product_data_tabs', 'misha_product_settings_tabs' );
function misha_product_settings_tabs( $tabs ){
 
	//unset( $tabs['inventory'] );
 
	$tabs['misha'] = array(
		'label'    => 'Misha',
		'target'   => 'misha_product_data',
		'class'    => array('show_if_virtual'),
		'priority' => 21,
	);
	return $tabs;
 
}
 
/*
 * Tab content
 */
add_action( 'woocommerce_product_data_panels', 'misha_product_panels' );
function misha_product_panels(){
 
	echo '<div id="misha_product_data" class="panel woocommerce_options_panel hidden">';
 
	woocommerce_wp_text_input( array(
		'id'                => 'misha_plugin_version',
		'value'             => get_post_meta( get_the_ID(), 'misha_plugin_version', true ),
		'label'             => 'Plugin version',
		'description'       => 'Description when desc_tip param is not true'
	) );
 
	woocommerce_wp_textarea_input( array(
		'id'          => 'misha_changelog',
		'value'       => get_post_meta( get_the_ID(), 'misha_changelog', true ),
		'label'       => 'Changelog',
		'desc_tip'    => true,
		'description' => 'Prove the plugin changelog here',
	) );
 
	woocommerce_wp_select( array(
		'id'          => 'misha_ext',
		'value'       => get_post_meta( get_the_ID(), 'misha_ext', true ),
		'wrapper_class' => 'show_if_downloadable',
		'label'       => 'File extension',
		'options'     => array( '' => 'Please select', 'zip' => 'Zip', 'gzip' => 'Gzip'),
	) );
 
	echo '</div>';
 
}
 
/*
 * Save
 */
add_action('woocommerce_process_product_meta', 'bla_bla_bla' ...

Do you see a custom icon and do not know how I did it? 😁 Some custom CSS and that’s all. I even used the default WordPress icon set, already connected to the admin area – Dashicons.

So, just go to their website → Select an icon → Click the Copy CSS button, paste it in admin area any way you like.

add_action('admin_head', 'misha_css_icon');
function misha_css_icon(){
	echo '<style>
	#woocommerce-product-data ul.wc-tabs li.misha_options.misha_tab a:before{
		content: "\f487";
	}
	</style>';
}

The most

Last updated