关于我之前在Retrieving WC Custom Field成功回答的问题,我现在有了选择字段,并且还希望添加自动完成的自定义字段(我还没有对此进行研究)
问题: 1.)如何自动填充自定义选择字段?
//Adding the custom field select
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'SIM Type', 'woocommerce' ),
'options' => array(
'one' => __( 'Regular', 'woocommerce' ),
'two' => __( 'Nano', 'woocommerce' ),
'three' => __( 'Micro', 'woocommerce' )
)
)
);
//Saving
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
// Display Custom Field Value
echo get_post_meta( $post->ID, '_select', true );
答案 0 :(得分:3)
更新:以编程方式设置选择字段中的
<option>
:
1)您需要存储选项键值的关联数组:
// The associative array to store (once)
$options_array = array(
'' => __( 'Select a value', 'woocommerce' ), // default empty value
'one' => __( 'Regular', 'woocommerce' ),
'two' => __( 'Nano', 'woocommerce' ),
'three' => __( 'Micro', 'woocommerce' )
);
// Serialize the array as a string
$option_str = maybe_serialize( $options_array );
// Save this array in Wordpress options
update_option( 'my_custom_selector_options', $option_str );
2)获取并反序列化您的选择器选项:
// Get your options select data
$select_options_str = get_option( 'my_custom_selector_options' );
// Unserialize this data:
$select_options_arr = maybe_unserialize( $select_options_str );
// Get the saved selected 'value' if it exist
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = ''; // When 'value' is not defined
//
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'SIM Type', 'woocommerce' ),
'options' => $select_options_arr,
'value' => $value,
)
);
所以现在你的字段选择器选项已经填入了从WordPress选项中获得的数据。
要自动填充 woocommerce_wp_select()
,您必须以这种方式添加 'value'
键:
## 1. The select (dropdown)
// Get the 'value' data if it exist
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = ''; // When 'value' is not defined
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'SIM Type', 'woocommerce' ),
'options' => array(
'' => __( 'Select a value', 'woocommerce' ), // Added a default empty value
'one' => __( 'Regular', 'woocommerce' ),
'two' => __( 'Nano', 'woocommerce' ),
'three' => __( 'Micro', 'woocommerce' )
),
'value' => $value, // <=== === === === === HERE set the 'value' key (autofill)
)
);
## ---------------------------------
## 2. SAVING
$woocommerce_select = $_POST['_select'];
// The Default empty value is not saved (added in this condition below)
if( !empty( $woocommerce_select ) || $woocommerce_select != '' )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
快速测试:
要查看其实际效果,请将'value' => $value,
替换为'value' => 'two',
然后选择的值将是:纳米 ...