Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Add Custom Fields for Specific Payment Gateway in Woocommerce?

Sometimes online store owners might need to get extra info other than the details that are not covered by the usual WooCommerce fields present on the checkout page. For instance, with the BACS payment gateway, a store owner might want to know how a customer plans to do a bank transfer. In order to receive such information you also need to add these custom fields into your store. Such Custom fields for a particular payment method allow customers to specify their preferred method for making the bank transfer, providing clarity and ensuring that their payment aligns with their preferences.

This post helps you to add custom fields for specific payment gateway in WooCommerce.

Where to Add Custom Code in WooCommerce?

It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install & activate the Code Snippets plugin. You can then add the code as a new snippet via the plugin.

Solution: Add Custom Fields for Specific Payment Gateway in Woocommerce

Consider a scenario where an online store offers a variety of payment options to customers. This code snippet given below enhances the BACS payment gateway in WooCommerce by adding a customizable select field during checkout, saving the selected value to the order meta, and displaying the value in the admin order details.

// BACS payment gateway description: Append custom select field
add_filter('woocommerce_gateway_description', 'ts_gateway_bacs_custom_fields', 20, 2);
function ts_gateway_bacs_custom_fields($description, $payment_id)
{
    if ('bacs' === $payment_id) {
        ob_start(); // Start buffering

        echo '<div class="bacs-fields" style="padding:10px 0;">';

        woocommerce_form_field('field_slug', array(
            'type'      => 'select',
            'label'     => __("Fill in this field", "woocommerce"),
            'class'     => array('form-row-wide'),
            'required'  => false,
            'options'   => array(
                ''          => __("Select something", "woocommerce"),
                'choice-1'  => __("via a Bank", "woocommerce"),
                'choice-2'  => __("via PayPal", "woocommerce"),
            ),
        ), '');

        echo '</div>';

        $description .= ob_get_clean(); // Append buffered content
    }
    return $description;
}
// Save custom BACS field to order meta
add_action('woocommerce_checkout_create_order', 'ts_save_bacs_custom_field', 10, 2);
function ts_save_bacs_custom_field($order, $data)
{
    if ($data['payment_method'] === 'bacs' && isset($_POST['field_slug'])) {
        $order->update_meta_data('_bacs_custom_field', sanitize_text_field($_POST['field_slug']));
    }
}


// Display and get the custom BACS field value in WooCommerce admin
add_action('woocommerce_admin_order_data_after_billing_address', 'ts_display_bacs_custom_field_in_admin', 10, 1);

function ts_display_bacs_custom_field_in_admin($order)
{
    if ($order->get_payment_method() === 'bacs' && ($value = $order->get_meta('_bacs_custom_field'))) {
        echo '<p><strong>' . __('Payment Additional Field:', 'woocommerce') . '</strong> ' . get_bacs_custom_field_value($value) . '</p>';
    }
}

// Helper function to get the actual value for the custom field
function ts_get_bacs_custom_field_value($field_slug)
{
    $options = array('choice-1' => __("via a Bank", "woocommerce"), 'choice-2' => __("via PayPal", "woocommerce"));
    return isset($options[$field_slug]) ? $options[$field_slug] : '';
}

Output

The output below shows a custom field for the Bank Transfer Payment method with dropdown options such as ‘via a Bank’ and ‘via PayPal’.

How to Add Custom Fields for Specific Payment Gateway in Woocommerce

The above-chosen option is saved and the value chosen by the customer is retrieved at the backend on the admin side.

How to Add Custom Fields for Specific Payment Gateway in Woocommerce


Code Explanation

Filtering BACS Payment Gateway Description:

  • The code starts with a filter hook woocommerce_gateway_description that allows customizing the description of a payment gateway.
  • The function ts_gateway_bacs_custom_fields is hooked into this filter.

Checking Payment Method:

  • Inside ts_gateway_bacs_custom_fields, it checks if the payment method is ‘bacs’ (‘bacs’ === $payment_id).
  • If the condition is true, it starts buffering the output with ob_start().

Outputting Custom Select Field:

  • It then echoes HTML to display a custom select field using woocommerce_form_field.
  • This field has a label, options, and is wrapped in a styled div.

Cleaning Output Buffer:

  • After echoing the HTML, it cleans and appends the buffered content to the $description variable with ob_get_clean().

Returning Modified Description:

  • The modified description is returned by the function.

Saving Custom BACS Field to Order Meta:

  • The code includes an action hook woocommerce_checkout_create_order that triggers during order creation.
  • The function ts_save_bacs_custom_field is hooked into this action.
  • It checks if the payment method is ‘bacs’ and if the custom field (field_slug) is set in the $_POST data.
  • If true, it updates the order meta data with the sanitized custom field value.

Displaying Custom BACS Field in WooCommerce Admin:

  • Another action hook woocommerce_admin_order_data_after_billing_address is used to display custom order data in the admin.
  • The function ts_display_bacs_custom_field_in_admin is hooked into this action.
  • It checks if the payment method is ‘bacs’ and if the custom field value is set in the order meta.
  • If true, it echoes a paragraph with the custom field label and its actual value.

Helper Function to Get Custom Field Value:

  • The code includes a helper function ts_get_bacs_custom_field_value.
  • This function takes a $field_slug as an argument, representing the key for the custom field. It retrieves the corresponding value from the $options array using the key. If the key exists, it returns the associated value; otherwise, it returns an empty string.

Conclusion

This post has guided you to add a custom field for a specific Payment Gateway. Similarly, you can add a custom field within a specific shipping method too. In order to ensure timely shipping, and avoiding delays you can add the delivery date field below the shipping methods in the woocommerce cart and checkout page

But the same can also be achieved via a plugin named Order Delivery Date Pro plugin for WooCommerce. This plugin lets you create different delivery schedules, set charges for Weekdays & special dates, manage local pickup dates, notify customers once the order is ready, and real-time syncing of your deliveries with Google Calendar. 

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Newest
Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x