Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a custom field to WooCommerce Billing form?

I get this code to add a custom field to the WooCommerce Billing form.

The field is shown but the problem is that the field has not label nor placeholder nor class name.

What am I missing here? I added this code to functions.php in my child theme.

/*******************************
  CUSTOM BILLING FIELD
 ******************************** */
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');

function custom_woocommerce_billing_fields($fields)
{

    $fields['billing']['billing_options'] = array(
        'label' => __('NIF', 'woocommerce'), // Add custom field label
        'placeholder' => _x('Your NIF here....', 'placeholder', 'woocommerce'), // Add custom field placeholder
        'required' => false, // if field is required or not
        'clear' => false, // add clear or not
        'type' => 'text', // add field type
        'class' => array('my-css')    // add class name
    );

    return $fields;
}
like image 431
JPashs Avatar asked Nov 29 '22 00:11

JPashs


1 Answers

If you are using woocommerce_billing_fields then you don't need to specify the fields it will be automatically get assign to the billing fields. But if your are using woocommerce_checkout_fields then only you need to specify that you want a field for shipping or billing.

For woocommerce_billing_fields

add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');

function custom_woocommerce_billing_fields($fields)
{

    $fields['billing_options'] = array(
        'label' => __('NIF', 'woocommerce'), // Add custom field label
        'placeholder' => _x('Your NIF here....', 'placeholder', 'woocommerce'), // Add custom field placeholder
        'required' => false, // if field is required or not
        'clear' => false, // add clear or not
        'type' => 'text', // add field type
        'class' => array('my-css')    // add class name
    );

    return $fields;
}


For woocommerce_checkout_fields
add_filter('woocommerce_checkout_fields', 'custom_woocommerce_billing_fields');

function custom_woocommerce_billing_fields($fields)
{
    $fields['billing']['billing_options'] = array(
        'label' => __('NIF', 'woocommerce'), // Add custom field label
        'placeholder' => _x('Your NIF here....', 'placeholder', 'woocommerce'), // Add custom field placeholder
        'required' => false, // if field is required or not
        'clear' => false, // add clear or not
        'type' => 'text', // add field type
        'class' => array('my-css')   // add class name
    );

    return $fields;
}

Reference:

  • https://gist.github.com/mikejolley/1860056
  • Customizing checkout fields using actions and filters
like image 78
Raunak Gupta Avatar answered Dec 04 '22 10:12

Raunak Gupta