如何在 WooCommerce 结账时将 HTML 添加到 "billing_email" 字段?

How do I add HTML to the "billing_email" field at WooCommerce checkout?

我想在 billing_email 字段输入框下方添加一行文字。详情如下

原始 HTML 输出。

<p class="form-row form-row-wide validate-required validate-email" id="billing_email_field" data-priority="110">
    <label for="billing_email" class="">Email address&nbsp;<abbr class="required" title="required">*</abbr></label>
    <span class="woocommerce-input-wrapper">
        <input type="email" class="input-text " name="billing_email" id="billing_email" placeholder="" value="" autocomplete="email username">
    </span>
</p>

修改了 HTML 输出。

<p class="form-row form-row-wide validate-required validate-email" id="billing_email_field" data-priority="110">
    <label for="billing_email" class="">Email address&nbsp;<abbr class="required" title="required">*</abbr></label>
    <span class="woocommerce-input-wrapper">
        <input type="email" class="input-text " name="billing_email" id="billing_email" placeholder="" value="" autocomplete="email username">
    </span>
    <br>
    <span>Please enter the correct email address so that you can receive our emails.</span>
</p>

我试过WooCommerce help documentation - Customizing checkout fields using actions and filters,但是对我来说太难了,所以我在这里寻求帮助。

如有任何帮助,我们将不胜感激!

要专门针对 billing_email 字段进行更改,您可以使用 'woocommerce_form_field_' . $args['type'], 过滤器挂钩。其中 $args['type'] 可以替换为类型 email

$field包含从<p>到结束</p>的所有HTML。但是,因为你想在现有代码之间添加新的HTML,而不是重写整个字段,你可以使用str_replace

所以你得到:

function filter_woocommerce_form_field_email( $field, $key, $args, $value ) {   
    // Billing email
    if ( $key === 'billing_email') {
        // Replace existing html with new ones
        $field = str_replace( '</span>', '</span><br><span>Please enter the correct email address so that you can receive our emails.</span>', $field );
    }
    
    return $field;
} 
add_filter( 'woocommerce_form_field_email', 'filter_woocommerce_form_field_email', 10, 4 );

相关: