You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce结账表单自定义字段前添加H3标题(服务端方案)

解决方案:用精准的动作钩子在自定义账单字段前添加H3标题

嘿,我懂你不想依赖前端JS、想要纯服务端完美解决的需求!之前直接在woocommerce_checkout_fields过滤器里echo标题会跑到表单顶部,是因为这个过滤器的核心作用是修改字段数组结构,不是用来输出内容的——当你在这个函数里输出内容时,代码会在WooCommerce开始渲染表单字段之前就执行,所以标题会提前跑到整个表单最上方。

给你一个精准的服务端方案,用WooCommerce专门的字段前置钩子,正好把标题插在你的第一个自定义字段前面:

步骤1:保留原有的自定义字段函数(移除无效echo)

先把你原来函数里的echo代码删掉,保持字段定义逻辑不变:

// Modify billing fields
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
    unset($fields['billing']['billing_phone']);
    unset($fields['billing']['billing_email']);
    
    $fields['billing']['name_sender'] = array(
        'label' => __('Uw naam', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'),
        'clear' => true
    );
    $fields['billing']['email_sender'] = array(
        'label' => __('Uw email', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'),
        'clear' => true
    );
    $fields['billing']['phone_sender'] = array(
        'label' => __('Uw telefoonnummer', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'),
        'clear' => true
    );
    $fields['billing']['anoniem'] = array(
        'label' => __('Anoniem verzenden?', 'woocommerce'),
        'type' => 'checkbox',
        'class' => array('form-row-wide'),
        'clear' => true
    );
    return $fields;
}

步骤2:添加标题输出的动作钩子

WooCommerce提供了woocommerce_before_checkout_field_{field_key}的动作钩子,其中{field_key}就是你第一个自定义字段的键名name_sender。通过这个钩子,我们可以精准地在目标字段前输出H3标题:

// 在第一个自定义字段前添加H3标题
add_action( 'woocommerce_before_checkout_field_name_sender', 'add_sender_section_title' );
function add_sender_section_title() {
    // 用__()函数包裹标题,支持多语言适配
    echo '<h3 class="woocommerce-form-heading">' . __('Wie is de verzender?', 'woocommerce') . '</h3>';
}

这样标题就会完美出现在你的自定义字段区域最前方,和原生表单标题的渲染逻辑、样式保持一致,完全是服务端生成,不需要依赖前端JS调整位置。

额外小提示:

如果想要给标题自定义样式,可以给<h3>标签添加专属类名(比如上面的woocommerce-form-heading),之后就能通过CSS轻松调整字体、间距等样式啦。

内容的提问来源于stack exchange,提问作者Bas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:13:31