WordPress将字段添加到结帐,无法将用户元添加到值

时间:2018-10-25 23:11:07

标签: wordpress woocommerce

我正在尝试向woocommerce结帐添加一个额外的表单字段,并使用现有的用户元值(如果存在)填充它,但是我似乎无法获取value属性进行渲染。

$ user_meta_billing_licence_number跟踪错误日志,如果我将其附加到标签和占位符(如果我将其附加到占位符而不是value属性),它将显示在标签中。我在做什么错了?

add_filter('woocommerce_billing_fields', 'custom_billing_fields', 20 );
function custom_billing_fields( $fields ) {
    // Add license field.
    $user_id = get_current_user_id();
    $user_meta_billing_licence_number = (string)get_user_meta( $user_id, 'billing_licence_number', true );
    error_log('debug: line 117: billing_licence_number = '.$user_meta_billing_licence_number);
    $fields['billing_licence_number'] = array(
        'label'     => __('License Number (for use on certificates)', 'woocommerce'),
        'required'  => false,
        'class'     => array('form-row-wide'),
        'clear'     => true,
        'placeholder' => 'Recommended format: MA12345'.$user_meta_billing_licence_number,
        'value'     => $user_meta_billing_licence_number
    );
    return $fields;
}

1 个答案:

答案 0 :(得分:0)

所以...看起来您无法通过此过滤器传递值。您必须稍后拦截它,并在打印字段期间覆盖取值:

<?php foreach ( $checkout->checkout_fields['billing'] as $key => $field ) : ?>

    <?php

        if($key == 'billing_licence_number') {
            $uID = get_current_user_id();
            woocommerce_form_field( $key, $field, get_user_meta($uID, 'billing_licence_number', true));
        } else {
            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
        }

    ?>

<?php endforeach; ?>