如何在 Woocommerce 中添加 woocommerce-account-fields 上方的标题

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

前言

我的问题与 . The answer, I suspect, will also be very similar to the one 非常相似。

场景

结帐页面显示典型的帐单字段。在那些下面是div class woocommerce-account-fields,其中是div class create-account。嵌套在其中的表单有两个字段,account_usernameaccount_password.

我想连接到此并在最后一个帐单字段 (billing_email) 下方和 account_username 字段上方显示一个标题。

我试过的

看了上面提到的问题和答案,我想我可以做这样的事情:

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;
}

但这样做的结果是页面没有任何变化。但是,如果我使用 key == 'account_username 它会起作用,除了标题明显出现在错误的位置(在帐户用户名字段下方,而不是在其上方)。

这是我所指内容的直观屏幕截图。

如果我没理解错的话,那个位置在"create account"区域上方。

如果是这样的话,你可以使用动作挂钩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>';
}

您仍然可以使用 woocommerce_form_field_text,但不应使用 $field .= <heading>。但是,请使用 $field = <heading> . $field。这样,您的标题就会添加到顶部。不在底部。这就像 field + heading 当你做 $field .= <heading>heading + field$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;
}

另请注意 $key == 'account_username'