Customizing WooCommerce Input Fields Using woocommerce_wp_text_input

Running an online store on WooCommerce offers vast opportunities for customization and enhancement, but utilizing those can be a bit tricky! Many WooCommerce store owners encounter limitations when they want to add specific information to their products or manage data that doesn’t fit into the default options provided by WooCommerce. 

Whether it’s unique identifiers, additional pricing details, or custom data points relevant to your business model, not being able to incorporate these elements directly on the dashboard and product edit pages can lead to inefficiencies and manual workarounds.

Luckily, there is a solution: woocommerce_wp_text_input. This a handy PHP function designed specifically for the WooCommerce backend (i.e. the WooCommerce admin area and product edit pages) rather than the store’s frontend. It empowers site admins to tailor their WooCommerce store under the hood to their exact requirements by allowing them to add custom text input fields. 

In this guide, we’ll explain in depth what woocommerce_wp_text_input is and how to use it. As a bonus, we’ll also show you how to efficiently add custom input fields to your frontend as well. 

Let’s take a look!

What is woocommerce_wp_text_input, and why is it important?

woocommerce_wp_text_input is designed for backend operations within WooCommerce. It enables the addition of custom text input fields to various sections of the product data meta boxes and custom WooCommerce-specific backend applications. 

This versatility makes it a vital asset for store developers and owners looking to customize their store’s backend beyond the standard options provided by WooCommerce​.

woocommerce_wp_text_input is essentially a wrapper that generates HTML for a text input field, designed to be used within the WooCommerce admin product pages. Its primary goal is to simplify the process of adding custom fields to various WooCommerce backend sections, including the product edit pages. This allows developers to customize product data sections more efficiently, making it a vital tool for extending WooCommerce’s functionality to meet specific business needs.

This function accepts an array of arguments ($field) that determine the characteristics of the input field. Some of these parameters include:

  • ID: Essential for distinguishing the field and retrieving data upon form submission.
  • Label: Provides clear guidance on the information expected within the field.
  • Description: Offers further insight into the field’s purpose, improving usability.
  • Type: While the default type is text, this can be adjusted for different data types like ‘number’ for numerical entries.
  • Value: Useful for setting a default or existing value, aiding in edit operations.
  • Placeholder: Acts as a hint for the expected content or format, enhancing user guidance.
  • Custom_attributes: Allows you to add extra HTML attributes for more precise control over the field’s functionality.

To utilize the woocommerce_wp_text_input function, it has to be hooked into the appropriate WooCommerce action based on where you want the field to appear. For example, to add a custom field to the General section of the Product Data meta box, you would hook into woocommerce_product_options_general_product_data (tutorial coming later in the article!).

The function’s flexibility in terms of where it can place fields and how they can be configured allows for a wide range of customizations.

Example use cases for woocommerce_wp_text_input

Adding a custom vendor or manufacturer field

Adding a custom vendor or manufacturer field to your WooCommerce products can be valuable for several reasons, especially if, for your store, the distinction between different manufacturers is crucial for your customers or your backend processes. 

Having a manufacturer field allows you to track which products come from which vendor more easily, which can help in inventory management, reordering, and analyzing sales by manufacturer.

Tracking number input

By incorporating this input field into the order editing screen, store managers can easily add or update the tracking number for shipments. This enhances the order management process, allowing for more efficient handling of shipping information and improving the communication of tracking details to customers.

Enabling store credit purchases

If you offer products that can be purchased using credits (loyalty rewards, virtual currency in a game, or pre-paid store credit) instead of traditional currency, you can use woocommerce_wp_text_input to add a custom field for entering the credit amount associated with that product.

Developing custom WooCommerce plugins

As an example, if you’re developing a WooCommerce extension that calculates fees dynamically based on factors like the product’s base currency or the quantity of the product added to the cart, you can use woocommerce_wp_text_input to create an option to automatically calculate fees based on the base amount in the product’s currency or let administrators enter fee amounts manually. 

You can also use woocommerce_wp_text_input to create the input fields in your custom plugin’s dashboard to allow site admins to configure its settings.

How you use woocommerce_wp_text_input boils down to your specific goal and what you want to achieve. The scenarios are more or less limitless!

Other functions to add custom fields for different data types in the WooCommerce backend

You can use a number of other functions to help add custom fields for different data types, such as:

  • Checkbox fields with woocommerce_wp_checkbox: Ideal for opt-in features such as newsletter subscriptions or terms and conditions acknowledgments. Checkboxes are critical in ensuring compliance and fostering marketing engagements through consent-based user actions.
  • Select fields with woocommerce_wp_select: Enhance admin user experience with dropdown menus for options like size or color. This method streamlines the selection process, offering a tidy solution for variations that do not require separate stock keeping.
  • Number fields with woocommerce_wp_text_input (type ‘number’): By setting the type to ‘number’, this function confines inputs to numerical data, catering to unique product requirements such as custom lengths for fabrics, which are indispensable for specific inventory types.

However, it’s also crucial to acknowledge the limitations here: 

  • These custom fields are designed for backend use, meaning they don’t directly facilitate customer interactions on the store’s frontend. 
  • Implementing them can affect page load times if used excessively, due to the processing required. 
  • To create them, you need coding knowledge, including PHP, HTML, and WooCommerce hooks.
  • Options for styling customization are somewhat limited. 

Using the woocommerce_wp_text_input function, step-by-step

You can write the code in the child theme’s functions.php file or create a custom plugin in the wp-content/plugins/ folder of the WordPress installation. 

For this tutorial, we’ll go through the process of creating your own plugin.

Adding a custom text input field in the General tab in the product edit page

New custom product edit page field
  1. Inside the wp-content/plugins/ folder of your WordPress installation, create a PHP file and name it something like custom-product-edit-page-field.php.
  2. At the beginning of this file, add a PHP comment block that WordPress reads as plugin metadata (Plugin Name, Description, Author, etc.) like so:
    <?php
    /**
    * Plugin Name: My Custom WooCommerce Product Edit page Field
    * Plugin URI: (If any)
    * Description: Adds a custom field to the WooCommerce products edit page.
    * Version: 1.0
    * Author: Your Name
    * Author URI: http: (If any)
    */
  3. Below the plugin header information, add the PHP code to create and save the custom product field.
    // Hook to add custom field to product general options
    add_action( 'woocommerce_product_options_general_product_data', 'add_my_custom_product_field' );
    function add_my_custom_product_field() {
        woocommerce_wp_text_input(
            array(
                'id'          => '_my_custom_product_text_field',
                'label'       => __( 'New Custom Product Edit Page Field', 'woocommerce' ),
                'placeholder' => __( 'Enter value here', 'woocommerce' ),
                'desc_tip'    => 'true',
                'description' => __( 'Enter the custom value here.', 'woocommerce' ),
            )
        );
    }

    // Hook to save custom field value
    add_action( 'woocommerce_admin_process_product_object', 'save_my_custom_product_field' );
    function save_my_custom_product_field( $product ) {
        $custom_field_value = isset( $_POST['_my_custom_product_text_field'] ) ? $_POST['_my_custom_product_text_field'] : '';
        $product->update_meta_data( '_my_custom_product_text_field', sanitize_text_field( $custom_field_value ) );
    }

Explanation: 

  • The woocommerce_product_options_general_product_data action hook adds a new text input field to the General tab of the product data metabox in the WooCommerce product editing page. If you want to display this field somewhere else, check the other action hooks. 
  • The woocommerce_wp_text_input function is called to generate a text input field. The function arguments define the field’s characteristics, such as its ID (_my_custom_product_text_field), label (New Custom Product Edit Page Field), and placeholder text.
  • The woocommerce_admin_process_product_object action hook triggers the save_my_custom_product_field function, which retrieves the value entered in the custom field, sanitizes it to ensure it’s safe to store, and then saves it as product metadata.

Adding a custom text input field in a custom WooCommerce submenu (useful for developing WooCommerce plugins)

Adding a custom text input field in a WooCommerce submenu
  1. Again, inside the wp-content/plugins/ folder, create a PHP file and name it something like custom-woo-submenu.php. Then, add a PHP comment block at the beginning of this file
  2. Use the sample code below to create a submenu under WooCommerce:
    <?php
    /**
    * Plugin Name: My Custom WooCommerce Tab
    * Plugin URI:
    * Description: Adds a custom tab under WooCommerce in the WordPress admin with a custom setting.
    * Version: 1.0
    * Author: Your Name
    * Author URI:
    * License:
    */


    function add_woocommerce_custom_submenu() {
        add_submenu_page(
            'woocommerce', // Parent slug
            'My Custom Submenu in WooCommerce', // Page title
            'My Custom Submenu in WooCommerce', // Menu title
            'manage_woocommerce', // Capability
            'my-custom-submenu', // Menu slug
            'woocommerce_custom_page_content' // Callback function
        );
    }


    function woocommerce_custom_page_content() {
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            <form method="post" action="options.php">
                <?php
                // Output security fields for the registered setting "woocommerce_custom_options"
                settings_fields('woocommerce_custom_options');
                // Output setting sections and their fields
                do_settings_sections('my-custom-submenu');
                // Output save settings button
                submit_button('Save Settings');
                ?>
            </form>
        </div>
        <?php
    }



    function woocommerce_custom_settings_init() {
        // Register a new setting for "woocommerce_custom_options" page
        register_setting('woocommerce_custom_options', 'my_custom_option');

        // Register a new section in the "woocommerce_custom_options" page
        add_settings_section(
            'woocommerce_custom_section',
            'Custom settings',
            'woocommerce_custom_section_callback',
            'my-custom-submenu'
        );

        // Register a new field in the "woocommerce_custom_section" section, inside the "woocommerce_custom_options" page
        add_settings_field(
            'my_custom_option', // As used in the 'id' attribute of tags
            'Custom text field title', // Title of the field
            'woocommerce_custom_field_callback', // Callback for the field
            'my-custom-submenu', // Page it will be displayed on
            'woocommerce_custom_section' // Section it belongs to
        );
    }

    function woocommerce_custom_section_callback() {
        echo '<p>Custom settings description.</p>';
    }


    Explanation: 
    • The add_woocommerce_custom_submenu() function adds a submenu page under the WooCommerce menu. It uses add_submenu_page() function to register a new submenu page.
    • The woocommerce_custom_page_content() function is the callback for the content of the custom submenu page. It outputs HTML markup for the settings page. Inside the form, it calls WordPress functions to handle settings fields, sections, and the submit button.
    • The woocommerce_custom_settings_init() function is hooked into the admin_init action hook. It registers the plugin’s settings using WordPress functions like register_setting(), add_settings_section(), and add_settings_field().
    • The woocommerce_custom_section_callback() function is the callback for the custom section added in woocommerce_custom_settings_init(). It simply echoes a description for the custom settings section.
  3. Add the custom text input field using woocommerce_wp_text_input.
    function woocommerce_custom_field_callback() {
        // Get the value of the setting we've registered with register_setting()
        $setting = get_option('my_custom_option');
        // Display the field
        woocommerce_wp_text_input(
            array(
                'id'                => 'my_custom_option',
                'label'             => 'Custom text field in custom submenu in WooCommerce',
                'value'             => $setting ? $setting : '',
                'desc_tip'          => true,
                'description'       => 'Description for the input.',
            )
        );
    }
  4. Add the action hooks.
    add_action('admin_menu', 'add_woocommerce_custom_submenu');

    add_action('admin_init', 'woocommerce_custom_settings_init');


    Explanation: 
    • This first line of code hooks the add_woocommerce_custom_submenu function to the admin_menu action hook. This means that when the WordPress admin menu is being created, the custom submenu page will be added under the WooCommerce menu.
    • The second line of code hooks the woocommerce_custom_settings_init function to the admin_init action hook. The admin_init hook is triggered before any other hook when a user accesses the admin area. So, when the WordPress admin area is initialized, the submenu contents will be displayed.

Pro tip: Always ensure input data is clean and secure to prevent vulnerabilities, utilizing WooCommerce’s built-in functions like wc_clean for sanitation.

Customizing fields on the frontend

Custom backend fields are a great addition to any WooCommerce store, but those custom fields are also very important on the frontend. They give customers a more tailored shopping experience, from personalized product options to unique user interactions.

To manually introduce custom fields on the frontend, you’ll need to use hooks and filters, as we’ve already seen, which are a powerful way to extend and customize the WordPress and WooCommerce functionality. 

Hooks allow you to “hook into” a part of a website or plugin to either add new functionality or modify existing features without altering the core code. There are two types of hooks: actions and filters. 

  • Action hooks let you insert custom code at specific points within the WordPress execution, like adding a new field within a form. 
  • Filters, on the other hand, enable you to modify data, such as the contents of a blog post, before it is sent to the database or displayed to the user.

Using hooks and filters requires inserting your custom code into your theme’s functions.php file or a site-specific plugin. For example, to add a custom field to a WooCommerce product page, you could use the woocommerce_before_add_to_cart_button action hook to insert your field right before the “Add to Cart” button. 

If you don’t feel like writing code for frontend custom fields, we recommend using a dedicated plugin, which is much faster and more convenient. 

Introducing Advanced Product Fields for WooCommerce

Advanced Product Fields for WooCommerce homepage

Advanced Product Fields for WooCommerce (APF) offers a streamlined solution to the complex world of WooCommerce customization, eliminating the need for manual coding on your product pages. With APF, you can overcome the limitations of WooCommerce’s native customization options and present your products exactly as you wish. 

This plugin allows you to effortlessly add up to 16 different field types to your products, including text and text area fields, number fields, select lists, checkboxes, radio buttons, and image and color swatches, among others.

Product with multiple different custom fields

APF simplifies the addition of custom fields, enabling features like personalized engraving instructions, gift-wrapping options, or special product variations without touching a line of code. 

If you want to see how these look in practice, take a look at the APF demo page

Benefits of using Advanced Product Fields for WooCommerce

Using Advanced Product Fields significantly enhances the WooCommerce experience for both store owners and their customers. 

It gives you:

  • Greater customization flexibility: APF’s wide range of field types provides the tools to meet diverse product customization needs, allowing for a more tailored shopping experience.
  • Improved usability and conversion potential: By making it easier for customers to find and select product options that meet their needs, APF can help improve the overall user experience and increase conversion rates.
  • Streamlined store management: Features like easier data handling and validation mean store owners can manage customized product offerings more efficiently, reducing the potential for errors and enhancing overall store functionality.
  • Reduced technical complexities: For web developers and store owners alike, APF reduces the hurdles associated with customizing WooCommerce stores, making it a valuable tool for enhancing site performance and customer satisfaction.

Transform your WooCommerce store with custom fields today

Customizing fields, both on the backend and frontend, can significantly uplift your e-commerce store’s functionality and appeal. Employing functions like woocommerce_wp_text_input equips store owners with the tools needed to extend their online store’s capabilities, enabling more detailed product specifications and enhanced user interactions. 

Meanwhile, Advanced Product Fields offers a seamless solution for frontend customization, eliminating the need for complex coding. Its comprehensive suite of field types and user-friendly interface make product customization and elevated user experience a breeze.Don’t miss out on the opportunity to elevate your store – try Advanced Product Fields today!

Share