Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Products and the CRUD Layer

Custom Product Fields and Tabs

Add custom fields and tabs to the WooCommerce product editor, save them safely with the CRUD API, and show them on the product page with proper escaping.

Sooner or later a store needs a product fact that WooCommerce does not ask for: a warranty length, a country of origin, a "gift wrap available" switch, a link to a size chart. The platform has a ready-made place for these: the Product data box on the product edit screen, with its tabs and panels. You add a field there, save its value on the product, and print it on the product page.

This lesson covers the whole loop: render a field in the admin, sanitize and save it through the CRUD object, add your own admin tab, and add a tab or a line on the storefront. It builds on CRUD Classes and Data Stores and on the general meta box ideas in Meta Boxes. Everything that needs WordPress is shown read-only; the runnable stand-in is the sanitizing step, which is where most real bugs live.

flowchart LR
    A["Admin renders field<br/>(product_options hook)"] --> B["Editor submits form"]
    B --> C["WooCommerce checks nonce<br/>and permission"]
    C --> D["Your save hook<br/>(woocommerce_process_product_meta)"]
    D --> E["Sanitize, then<br/>update_meta_data and save"]
    E --> F["Storefront hook<br/>reads get_meta and escapes"]

Data flows in at the admin hook, is cleaned in your save hook and is escaped again on the way out.

Adding a field to the General tab

The General tab fires an action that is made for extra fields. WooCommerce provides helper functions that print a complete form row (label, input, description) in the same style as the built-in fields:

PHP
add_action( 'woocommerce_product_options_general_product_data', function (): void {
    echo '<div class="options_group">';

    woocommerce_wp_text_input( [
        'id'                => '_acme_warranty_months',
        'label'             => __( 'Warranty (months)', 'acme-extras' ),
        'description'       => __( 'Leave empty if there is no warranty.', 'acme-extras' ),
        'desc_tip'          => true,
        'type'              => 'number',
        'custom_attributes' => [ 'min' => '0', 'step' => '1' ],
    ] );

    woocommerce_wp_checkbox( [
        'id'          => '_acme_gift_wrap',
        'label'       => __( 'Gift wrap', 'acme-extras' ),
        'description' => __( 'Offer gift wrapping for this product.', 'acme-extras' ),
    ] );

    echo '</div>';
} );

The helpers read the current value for you: they look up the field's id as a meta key on the product being edited. The same family includes woocommerce_wp_select(), woocommerce_wp_textarea_input(), woocommerce_wp_radio() and woocommerce_wp_hidden_input(). They accept an id, label, description, desc_tip, class, wrapper_class, custom_attributes, and (for selects) an options array.

Start private meta keys with an underscore (_acme_gift_wrap). WordPress hides underscore keys from the generic "Custom Fields" box, so editors cannot change your data by accident, and your own field remains the single way to edit it.

Saving the values

When the editor presses Update, WooCommerce verifies the request and then runs the woocommerce_process_product_meta action with the product ID. That is where your plugin saves its fields. Use the CRUD object, so the value is stored wherever the product's data store keeps it and the save hooks fire:

PHP
add_action( 'woocommerce_process_product_meta', function ( int $product_id ): void {
    $product = wc_get_product( $product_id );
    if ( ! $product ) {
        return;
    }

    $months = isset( $_POST['_acme_warranty_months'] )
        ? absint( wp_unslash( $_POST['_acme_warranty_months'] ) )
        : 0;

    $product->update_meta_data( '_acme_warranty_months', $months > 0 ? $months : '' );
    $product->update_meta_data(
        '_acme_gift_wrap',
        isset( $_POST['_acme_gift_wrap'] ) ? 'yes' : 'no'
    );

    $product->save_meta_data();
} );

Three habits are worth copying:

  1. Unslash, then sanitize. WordPress adds slashes to superglobals, so call wp_unslash() first, then a sanitizer that matches the data: absint() for whole numbers, wc_format_decimal() for prices and decimals, wc_clean() for plain text, esc_url_raw() for URLs, wp_kses_post() for limited HTML.
  2. A missing checkbox is a value, too. Browsers do not submit unchecked checkboxes, so an absent key must be stored as "no".
  3. Save the meta, not the whole product. save_meta_data() writes only changed meta. Calling save() inside a hook that runs during a save can retrigger your own hooks.

WooCommerce checks the nonce and the user's capability before this action runs, but your own handler is still the right place to refuse bad data, and code that calls your saving function from elsewhere (an importer, say) will not have gone through that check. See Security for WooCommerce Extensions for the wider picture.

The sanitizing stand-in

The saving step can be tested without WordPress if you treat a field as a small schema: a type and a few rules. The stand-in below mimics wp_unslash, absint, wc_clean and a checkbox rule, and returns both the clean values and the problems found.

PHP A field-save sanitizer (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real versus stand-in: the idea of a schema with per-type cleaning is real and common; the real helper functions are WordPress's, with more edge cases (for example wc_clean() also handles arrays). Note that the first sample turned -24 into 24 through the absolute value, which is how absint() behaves. If a negative number is invalid for your field, reject it instead of silently flipping it.

Your own tab in the Product data box

For more than a couple of fields, give your plugin its own tab. Three pieces are needed: the tab button (a filter), the panel (an action) and, if you want, a visibility rule.

PHP
add_filter( 'woocommerce_product_data_tabs', function ( array $tabs ): array {
    $tabs['acme_extras'] = [
        'label'    => __( 'Extras', 'acme-extras' ),
        'target'   => 'acme_extras_data',          // the id of the panel below
        'class'    => [ 'show_if_simple', 'show_if_variable' ],
        'priority' => 70,
    ];
    return $tabs;
} );

add_action( 'woocommerce_product_data_panels', function (): void {
    echo '<div id="acme_extras_data" class="panel woocommerce_options_panel">';
    echo '<div class="options_group">';

    woocommerce_wp_text_input( [
        'id'    => '_acme_size_chart_url',
        'label' => __( 'Size chart URL', 'acme-extras' ),
        'type'  => 'url',
    ] );

    echo '</div></div>';
} );

The target of the tab must equal the id of the panel. The classes show_if_simple and show_if_variable (and the matching hide_if_* ones) are toggled by WooCommerce's admin script according to the selected product type, so the tab appears only where it makes sense. The tab's save logic is the same woocommerce_process_product_meta hook as before.

Variations have their own versions of both hooks: woocommerce_product_after_variable_attributes prints per-variation fields and woocommerce_save_product_variation saves them. Per-variation fields need the variation's ID, not the parent's.

Showing the data on the storefront

There are two places to show your data: a line inside the summary area, and a tab in the tabbed area below it.

PHP
// A line in the summary area (the hook number sets the order).
add_action( 'woocommerce_single_product_summary', function (): void {
    global $product;

    $months = $product ? (int) $product->get_meta( '_acme_warranty_months', true ) : 0;
    if ( $months > 0 ) {
        printf(
            '<p class="acme-warranty">%s</p>',
            esc_html( sprintf(
                _n( '%d month warranty', '%d months warranty', $months, 'acme-extras' ),
                $months
            ) )
        );
    }
}, 25 );

// A tab on the product page.
add_filter( 'woocommerce_product_tabs', function ( array $tabs ): array {
    global $product;

    if ( $product && $product->get_meta( '_acme_size_chart_url', true ) ) {
        $tabs['acme_size_chart'] = [
            'title'    => __( 'Size chart', 'acme-extras' ),
            'priority' => 35,
            'callback' => function (): void {
                global $product;
                printf(
                    '<a href="%s">%s</a>',
                    esc_url( $product->get_meta( '_acme_size_chart_url', true ) ),
                    esc_html__( 'Open the size chart', 'acme-extras' )
                );
            },
        ];
    }
    return $tabs;
} );

Escape at the last moment, with the function that fits the context: esc_html() for text, esc_url() for link targets, esc_attr() for attribute values and wp_kses_post() when you deliberately allow some HTML. Never assume that a value was clean because your own save hook cleaned it: other code, imports and old data can write the same meta key.

The default tab priorities help you place a tab: Description is 10, Additional information is 20 and Reviews is 30, so 35 puts yours after them. To understand why a hook such as woocommerce_single_product_summary runs where it does, see The WooCommerce Hook Map.

Rendering safely: a stand-in

Output escaping is the other half of field handling. This stand-in mimics the three escaping functions with PHP's htmlspecialchars and builds the warranty line and the size-chart tab from stored meta. Note how a hostile value ends up as harmless text, and how a non-HTTP link is dropped.

PHP Escaping at output (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

What is real: cast numbers, escape late and skip empty output. What is the stand-in: esc_url() in WordPress handles many more cases than the protocol check here.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function prints a complete labelled text field in the WooCommerce product editor?

    woocommerce_wp_text_input() and its siblings output a label, an input and a description in the same style as core fields.
  2. 2. Why must a save handler store 'no' when a checkbox key is missing from $_POST?

    An unchecked checkbox is simply not sent. Without handling the missing key, the old "yes" would never be cleared.
  3. 3. Which pair connects a custom product data tab button to its panel?

    The 'target' value of the tab must equal the id attribute of the panel div.
  4. 4. How should you print a stored URL in a storefront link?

    Escape late with the function that matches the context. Saved data can come from imports or older code and is not guaranteed clean.

Summary

  • Add fields with woocommerce_product_options_general_product_data and the woocommerce_wp_* helpers; hide your keys behind an underscore prefix.
  • Save in woocommerce_process_product_meta through update_meta_data() and save_meta_data() on the CRUD object.
  • Unslash, then sanitize with a function that matches the type; store an explicit value for unchecked checkboxes.
  • Add your own admin tab with woocommerce_product_data_tabs and woocommerce_product_data_panels; target must equal the panel's id.
  • Show data with woocommerce_single_product_summary or woocommerce_product_tabs, and escape at output.

Next: Custom Product Types