Adding WooCommerce Products custom fields

Taking you through the basics of registering custom fields on WooCommerce Products, adding custom fields to variable products, adding fields to the bulk edit screen , adding a custom field to quick edit screen, and display with a custom admin column

Adding WooCommerce Products Custom fields

Custom fields allow you to add custom to each product, custom fields can be used to store all types of data from text to attachments, in this example we will be showing you how to create a basic text field and how you store its value as product meta data.

Displaying a products custom field

The first step is to display the custom field on the products edit page, this is done by hooking into the woocommerce_product_options_pricing action, combined with using the built in woocommerce function woocommerce_wp_text_input to display a text input field, saving us from manually creating the input html element.

/**
 * Display Simple Product field.
 */
function jcwc1_admin_display_custom_field()
{
    woocommerce_wp_text_input(array(
        'id' => '_custom_field',
        'wrapper_class' => 'show_if_simple show_if_variable',
        'label' => __('Custom Field', 'woocommerce'),
        'data_type' => 'text'));
}

add_action('woocommerce_product_options_pricing', 'jcwc1_admin_display_custom_field');

Saving products custom fields

With the custom field displayed we can save the value into the post meta table referencing the product id, todo this we use the woocommerce_process_product_meta action to validate that this is a simple product, use the wc_clean function to sanitize the input data before saving it in the database.

/**
 * Save Simple Product field.
 * 
 * @param integer $post_id Product Id
 * @param \WP_Post $post Post
 * @return void 
 */
function jcwc1_admin_save_custom_field($post_id, $post)
{
    $product = wc_get_product($post);
    if ($product->is_type('simple')) {
        update_post_meta($post_id, '_custom_field', wc_clean($_POST['_custom_field']));
    }
}
add_action('woocommerce_process_product_meta', 'jcwc1_admin_save_custom_field', 10, 2);

Adding WooCommerce custom fields onto Product Variations

Adding custom fields onto a Product variations is very similar to adding it onto a simple product, we need to display the custom field onto each product variation, and process the data submitted by multiple variations using both the product and variation ID.

Displaying custom fields on product variations

Adding custom fields onto the variable products edit screen, can be done using the woocommerce_product_after_variable_attributes action to display an input field using woocommerce_wp_text_input combined with using the loop counter to alter the input name, so that it can be linked to each product variation when saving.

/**
 * Display Custom Field variation field
 * 
 * @return void 
 */
function jcwc1_variation_display_custom_field($loop, $variation_data, $variation)
{
    $variation_id = $variation->ID;
    $current_value = get_post_meta($variation_id, '_custom_field', true);
    echo '<div class="form-row form-row-full">';
    woocommerce_wp_text_input(array(
        'id' => '_custom_field[' . $loop . ']',
        'wrapper_class' => 'show_if_simple show_if_variable',
        'label' => __('Custom Field', 'woocommerce'),
        'data_type' => 'text',
        'value' => $current_value
    ));
    echo '</div>';
}
add_action('woocommerce_product_after_variable_attributes', 'jcwc1_variation_display_custom_field', 10, 3);

Saving product variations custom fields

Using the Variable Products variation product loop counter allows the capturing of the submitted custom field value when using the woocommerce_save_product_variation action.

/**
 * Save Custom Field variation data
 * 
 * @param integer $variation_id 
 * @param integer $i 
 * @return void 
 */
function jcwc1_save_product_variation_custom_field($variation_id, $i)
{
    update_post_meta($variation_id, '_custom_field', wc_clean($_POST['_custom_field'][$i]));
}
add_action('woocommerce_save_product_variation', 'jcwc1_save_product_variation_custom_field', 10, 2);

Adding custom fields to WooCommerce bulk edit screen

The bulk edit screen on the Product archive admin screen allows you to select multiple products and apply a modifier to all the selected products.

Display custom fields on WooCommerce products bulk edit screen

Adding custom fields to WooCommerce product bulk edit panel can be done using the woocommerce_product_bulk_edit_start action, similar to other fields in the bulk edit panel we need to add two fields, a dropdown that is used to say if the value should be updated, and the input field to update selected values with.

<?php
/**
 * Display bulk edit input for custom field
 */
function jcwc1_bulk_edit_custom_field()
{
?>
    <div class="inline-edit-group">
        <label class="alignleft">
            <span class="title"><?php _e('Custom Field', 'woocommerce'); ?></span>
            <span class="input-text-wrap">
                <select class="change_custom_field change_to" name="change_custom_field ">
                    <option value="">— No change —</option>
                    <option value="1">Change to:</option>
                </select>
            </span>
        </label>

        <label class="change-input" style="display: none;">
            <input type="text" name="_custom_field" class="text _custom_field" placeholder="Enter value" value="">
        </label>
    </div>
<?php
}
add_action('woocommerce_product_bulk_edit_start', 'jcwc1_bulk_edit_custom_field');

Save WooCommerce products bulk edited custom fields

Using the woocommerce_product_bulk_edit_save action allows the processing of data submitted from the bulk edit panel, checking to see if the dropdown has been set to change the value and a new value has been submitted, if both of these conditions are met then we sanitize the value using wc_clean before updating the products custom field.

/**
 * Save bulk edit input for Commodity code
 * 
 * @param WC_Product $product
 */
function jcwc1_bulk_edit_save_custom_field($product)
{
    $post_id = $product->get_id();
    if (isset($_REQUEST['_custom_field']) && $_REQUEST['change_custom_field'] === '1') {
        $custom_field = $_REQUEST['_custom_field'];
        update_post_meta($post_id, '_custom_field', wc_clean($custom_field));
    }
}
add_action('woocommerce_product_bulk_edit_save', 'jcwc1_bulk_edit_save_custom_field');

Adding WooCommerce Product custom fields to quick edit screen

Adding fields to WooCommerce quick edit screen requires that you display and save the field as normal, but have to pre populate each field using javascript.

Displaying WooCommerce Products quick edit custom fields

Using the woocommerce_product_quick_edit_start action allows you to output your custom field input, the input should not have any value set, as this will be populated when you click the quick edit button.

<?php
/**
 * Display quick edit custom field
 *
 * @return void
 */
function jcwc1_display_quick_edit_custom_field()
{
?>
    <label>
        <span class="title"><?php esc_html_e('Custom Field', 'woocommerce'); ?></span>
        <span class="input-text-wrap">
            <input type="text" name="_custom_field" class="text custom_field" value="">
        </span>
    </label>
    <br class="clear" />
<?php
}
add_action('woocommerce_product_quick_edit_start', 'jcwc1_display_quick_edit_custom_field');

Saving WooCommerce products quick edit custom fields

The woocommerce_product_quick_edit_save action allows you to capture each products custom field value and store it in the post meta table, sanitising the value first using wc_clean.

/**
 * Save quick edit custom field
 *
 * @param WC_Product $product
 * @return void
 */
function jcwc1_display_quick_save_custom_field($product)
{
    $post_id = $product->get_id();
    if (isset($_REQUEST['_custom_field'])) {
        $custom_field = $_REQUEST['_custom_field'];
        update_post_meta($post_id, '_custom_field', wc_clean($custom_field));
    }
}
add_action('woocommerce_product_quick_edit_save', 'jcwc1_display_quick_save_custom_field');

Pre populating WooCommerce products quick edit custom fields

The quick edit custom field input has to be populated when the quick edit button is clicked, populating the custom field input with the value from the chosen product. We do this by storing each products custom field value in the name column (so that we know it will be output as this is the products main column with the quick edit button in it).

We use the manage_product_psots_custom_column to output a div containing the custom fields value, and for quickness we are using the admin_footer action to add javascript to trigger when the quick edit button is pressed, it reads the custom fields value and populates the selected products custom field value.

<?php
/**
 * Display Custom Field column value on products table
 * 
 * @param string $column Column Name
 * @param integer $post_id 
 * @return void 
 */
function jcwc1_display_quick_edit_data($column, $post_id)
{

    if ('name' !== $column) {
        return;
    }

    echo '<div id="jcwc1_product_data_' . $post_id . '">' . esc_html(get_post_meta($post_id, '_custom_field', true)) . '</div>';
}
add_action('manage_product_posts_custom_column', 'jcwc1_display_quick_edit_data', 10, 2);

/**
 * Populate quick edit custom field
 *
 * @return void
 */
function jcwc_1_populate_quick_edit_field()
{
?>
    <script>
        (function($) {
            $('#the-list').on('click', '.editinline', function() {

                var post_id = $(this).closest('tr').attr('id');
                post_id = post_id.replace('post-', '');

                var custom_field = $('#jcwc1_product_data_' + post_id).text();
                $('input[name="_custom_field"]', '.inline-edit-row').val(custom_field);
            });
        })(jQuery);
    </script>
<?php
}
add_action('admin_footer', 'jcwc_1_populate_quick_edit_field');

Display custom fields on Product admin columns

Adding custom admin columns to the product achive screen allows you to quickly see their values without having to go into each product and check.

Add custom column headings

Adding a custom column can be done similar to adding any custom admin column in wordpress using the manage_edit-product_columns filter, adding a new record into the columns array, setting the column identifier as the array key, and the heading label as the array value.

/**
 * Add Custom Field column heading to products table
 * 
 * @param array $columns List of columns.
 * @return string[]
 */
function jcwc1_add_column_custom_field($columns)
{
    $columns['custom_field'] = 'Custom Field';
    return $columns;
}
add_filter('manage_edit-product_columns', 'jcwc1_add_column_custom_field');

Display custom column content

Adding the custom column heading registers the custom column, all that is left to do is display the column content using the manage_product_posts_custom_column action, and if the column name is the same as the column identifier set when registering the column heading then we display the custom field value.

/**
 * Display Custom Field column value on products table
 * 
 * @param string $column Column Name
 * @param integer $post_id 
 * @return void 
 */
function jcwc1_display_column_custom_field($column, $post_id)
{

    if ('custom_field' !== $column) {
        return;
    }

    echo get_post_meta($post_id, '_custom_field', true);
}
add_action('manage_product_posts_custom_column', 'jcwc1_display_column_custom_field', 10, 2);

Leave a Reply

Fields marked with an * are required to post a comment