在Woocommerce中使用预选值禁用选择字段

时间:2018-12-13 20:35:22

标签: php wordpress woocommerce checkout disabled-input

我希望能够在“城市选择”字段上实现相同的目标。我希望城市像只有一个普通文本或不能更改的给定值的国家/地区字段。

what i'm trying to achieve

下面是我的function.php中woocommerce字段状态的代码。我应该使用哪种类型?

add_filter( 'woocommerce_checkout_fields', 'custom_checkout_fields', 10, 1 );
function custom_checkout_fields( $fields ) {  

    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = array('Auckland' => 'Auckland');


    return $fields;
}

1 个答案:

答案 0 :(得分:1)

您可以在结帐页面(以及我的帐户>地址>帐单邮寄地址部分)中将字段只读 (已禁用)

2种不同情况:

1)对于select类型

add_filter( 'woocommerce_billing_fields', 'custom_checkout_billing_city_field', 10, 1 );
function custom_checkout_billing_city_field( $billing_fields ) {
    // HERE define the city
    $city = 'Auckland';

    // Set the city value (to be sure)
    WC()->customer->set_billing_city( $city );

    // Change the billing city field
    $billing_fields['billing_city']['type'] = 'select';
    $billing_fields['billing_city']['options'] = array( $city => $city );
    $billing_fields['billing_city']['default'] = $city;
    $billing_fields['billing_city']['custom_attributes']['disabled'] = 'disabled';

    return $billing_fields;
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。

选择字段被禁用(只读)且预选了城市:

enter image description here


2)对于text类型

add_filter( 'woocommerce_billing_fields', 'custom_checkout_billing_city_field', 10, 1 );
function custom_checkout_billing_city_field( $billing_fields ) {
    // HERE define the city
    $city = 'Auckland';

    // Set the city value (to be sure)
    WC()->customer->set_billing_city( $city );

    // Change the billing city field
    $billing_fields['billing_city']['default'] = $city;
    $billing_fields['billing_city']['custom_attributes']['readonly'] = 'readonly';

    return $billing_fields;
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。

文本字段仅与预选城市一起读取:

enter image description here