WooCommerce: Change HTML structure of billing fields in checkout

I want to use floating labels for the billing fields. Therefore I need to place the <label> element after the <input> field in the HTML structure.

At the moment my structure looks like this:

<p class="form-row form-row-first validate-required" id="billing_first_name_field" data-priority="10">
    <label for="billing_first_name" class="">First Name&nbsp;<abbr class="required" title="required">*</abbr></label>
    <span class="woocommerce-input-wrapper">
        <input type="text" class="input-text form-control" name="billing_first_name" id="billing_first_name" placeholder="" value="First Name" autocomplete="given-name">
    </span>
</p>

I want the label after the input/span element, like this:

<p class="form-row form-row-first validate-required" id="billing_first_name_field" data-priority="10">
    <span class="woocommerce-input-wrapper">
        <input type="text" class="input-text form-control" name="billing_first_name" id="billing_first_name" placeholder="" value="First Name" autocomplete="given-name">
    </span>
    <label for="billing_first_name" class="">First Name&nbsp;<abbr class="required" title="required">*</abbr></label>
</p>

Is there any way to change the output of the fields?

I found some hooks to change some elements of the fields: https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/

But that’s all related the content of the elements. Not the HTML structure itself.
Is that even possible?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

$field contains the complete <p>...</p> output.
So you can completely adjust the output. To keep it dynamic you can use the values ​​from $args


See: https://github.com/woocommerce/woocommerce/blob/master/includes/wc-template-functions.php#L2830 and accompanying code, how to do this

function change_woocommerce_field_markup($field, $key, $args, $value) {
    if( $key === 'billing_first_name') {
        $field = 'my html';
    }
    return $field;
} 

add_filter("woocommerce_form_field_text","change_woocommerce_field_markup", 10, 4);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply