WooCommerce: Add Custom fields on product page

Sometimes, You need to collect some external data as product meta from customers. Before adding items to cart, customer must be enter some additional informations. For example, getting the site url before place an order for seo service.

To achieve this thing, we need to display the input field first,

add_action('woocommerce_before_add_to_cart_button', 'display_site_url_field');

/**
 * Display Site URL input field.
 *
 * @return void
 */
function display_site_url_field()
{
    woocommerce_form_field(
        'site-url',
        array(
            'type' => 'url',
            'required' => true,
            'label' => __('Your Site URL', 'my_text_domain'),
            'description' => __('Please enter your Site URL', 'my_text_domain'),
        ),
    );
}
PHP

Here, I’m using the woocommerce_before_add_to_cart_button action hook for display the input field. But, you can choose one of these action hooks for display input field based on your preferred positions.

and more from here.

To generate the HTML form input that also be compatible with site theme, we need to use woocommerce built-in function woocommerce_form_field.

Preview
Product page text-input preview.
Validation

Customer can’t add product into the cart without adding the site url.

So, We need to use woocommerce_add_to_cart_validation filter hook to validate the add_to_cart execution.

add_filter('woocommerce_add_to_cart_validation', 'add_to_cart_validation', 10, 3);

/**
 * Validate add to cart execution.
 *
 * @param bool $passed Passed or not.
 * @param int  $product_id Product ID.
 * @param int  $quantity Cart Quantity.
 *
 * @return bool
 */
function add_to_cart_validation($passed, $product_id, $quantity)
{
    if (!isset($_POST['site-url']) || empty($_POST['site-url'])) {
        wc_add_notice(__("Please choose your Site URL.", "my_text_domain"), 'error');
        $passed = false;
    }

    if (filter_var($_POST['site-url'], FILTER_VALIDATE_URL) === false) {
        wc_add_notice(__("Invalid Site URL.", "my_text_domain"), 'error');
        $passed = false;
    }

    return $passed;
}
PHP

Store data inside cart item

We need to store the site url data inside cart item for display & the checkout process. To store data, we need to use the woocommerce_add_cart_item_data filter hook.

add_filter('woocommerce_add_cart_item_data', 'add_to_cart_item_data', 10, 3);

/**
 * Store site url inside cart item array.
 *
 * @param mixed $cart_item_data Cart Item Data.
 * @param int   $product_id Product ID.
 * @param int   $variation_id Variation ID.
 *
 * @return array
 */
function add_to_cart_item_data($cart_item_data, $product_id, $variation_id)
{
    if (isset($_POST['site-url'])) {
        $cart_item_data['site-url'] = sanitize_text_field($_POST['site-url']);
    }

    return $cart_item_data;
}
PHP

Display data inside cart item

Display data inside cart item is very easy, we’ll get the stored data by key and add them inside cart item data array. we need to use the woocommerce_get_item_data filter hook for adding data from the cart item.

add_filter('woocommerce_get_item_data', 'display_url_on_cart_item', 10, 2);

/**
 * Display site url inside cart item.
 *
 * @param array $cart_item_data Cart Item Data that only be display.
 * @param array $cart_item cart item data.
 *
 * @return array
 */
function display_url_on_cart_item($cart_item_data, $cart_item)
{
    if (isset($cart_item['site-url'])) {
        $cart_item_data[] = array(
            'name' => __('Site URL', 'my_text_domain'),
            'value' => $cart_item['site-url'],
        );
    }

    return $cart_item_data;
}
PHP

Preview

Display custom data inside cart item.

Checkout process

We need to store data as order line item. To achieve this, we’ll use the woocommerce_checkout_create_order_line_item action hook.

add_action(
  'woocommerce_checkout_create_order_line_item', 
  'save_url_as_order_item', 10, 4
);

/**
 * Save data to order line item.
 *
 * @param \WC_Order_Item $item Order Item Object.
 * @param string         $cart_item_key Order Item Key.
 * @param array          $cart_item Cart Item Array.
 * @param \WC_Order      $order Order Object.
 *
 * @return void
 */
function save_url_as_order_item($item, $cart_item_key, $cart_item, $order)
{
    if (isset($cart_item['site-url'])) {
        $item->update_meta_data('Site URL', $cart_item['site-url']);
    }
}
PHP

Preview

Thank you page:

Thank you page order line item preview.

MyAccount Order Details:

MyAccount Order line item preview.

Admin Order Details:

Thanks.

Istiaq Nirab

A highly skilled and proficient WordPress developer with over Three years of professional experience in all aspects of WordPress website creation, including design, plug-ins, and implementation. Results-driven individual contributor with a successful track record in exceeding expectations for web development initiatives

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *