inspirednz inspirednz - 1 year ago 110
PHP Question

How to add a heading above woocommerce-account-fields in Woocommerce

Preamble



My question is very similar to the one asked here. The answer, I suspect, will also be very similar to the one here.

Scenario



The checkout page displays the typical Billing fields. Below those is the div class
woocommerce-account-fields
, in which is the div class
create-account
. The form nested in that has two fields,
account_username
and
account_password
.

I want to hook into this and display a heading below the last billing field (
billing_email
) and above the
account_username
field.

What I tried



Reading the above mentioned question and answer, I figured I'd be able to do something like this:

add_action( 'woocommerce_form_field_text','XYZ_checkout_custom_heading', 10, 2 );

function XYZ_checkout_custom_heading( $field, $key ){
if ( is_checkout() && ( $key == 'billing_email') ) {
$field .= '<div id="add_custom_heading"><h3>' . __('MY CUSTOM HEADING') . '</h3></div>';
}
return $field;
}


But the result of this is no change to the page. However, if I use
key == 'account_username
it works, except obviously the heading ends up in the wrong place (below the account username field, and not above it).

Here is a screen shot of what I am referring to, visually.

enter image description here

Answer Source

If I understood it correctly, that location is above "create account" area.

If that's the case, you can use action hook woocommerce_before_checkout_registration_form

add_action( 'woocommerce_before_checkout_registration_form','XYZ_checkout_custom_heading');

function XYZ_checkout_custom_heading( ){
    echo '<div id="add_custom_heading"><h3>' . __('MY CUSTOM HEADING') . '</h3></div>';
}

You can still use woocommerce_form_field_text but you should not use $field .= <heading>. But instead, use $field = <heading> . $field. This way, your heading is added at the top. Not at the bottom. It's like field + heading when you're doing $field .= <heading> but heading + field with $field = <heading> . $field

add_action( 'woocommerce_form_field_text','XYZ_checkout_custom_heading', 10, 2 );

function XYZ_checkout_custom_heading( $field, $key ){
    if ( is_checkout() && ( $key == 'account_username') ) {
        $field = '<div id="add_custom_heading"><h3>' . __('MY CUSTOM HEADING') . '</h3></div>' . $field;
    }
    return $field;
}

also note of $key == 'account_username'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download