过去几天,我一直坚持将动态生成的字段的数据存储在woocommerce结帐页面上。我正在使用woocommerce预订插件,我必须在其中获取个人类型的名称。 为此,我做到了。
// Add checkout custom text fields
add_action( 'woocommerce_before_order_notes', 'add_checkout_custom_text_fields', 20, 1 );
function add_checkout_custom_text_fields( $checkout) {
$index = 0;
// 1st Loop through cart items
foreach(WC()->cart->get_cart() as $cart_item){
// 2nd Loop through each unit related to item quantity
for($i = 1; $i <= $cart_item['booking']['Adults']; $i++){
$index++;
woocommerce_form_field("my_field$index", array(
'type' =>'text',
'class'=>array('my-field-class form-row-wide'),
'label'=>__('Adults')." ($i)",
'placeholder'=>__('Enter adult name'),
'required' => true,
), $checkout->get_value("my_field$index"));
}
for($i = 1; $i <= $cart_item['booking']['Childs']; $i++){
$index++;
woocommerce_form_field("my_field$index", array(
'type' =>'text',
'class'=>array('my-field-class form-row-wide'),
'label'=>__('Childs')." ($i)",
'placeholder'=>__('Enter child name'),
'required' => true,
), $checkout->get_value("my_field$index"));
}
}
}
我在结帐页面上获得了可以正常工作的字段,但是现在我希望它们存储在数据库中并显示在订单的管理订单页面和谢谢页面上,这让我感到不安,我该如何解决这个问题,Stackoverflow我相信只有这个平台可以获得解决方案。
编辑在花费大量时间之后,我已经成功地将自定义数据存储到数据库中,现在我希望将其显示在admin和thankyou页面上。
这是我的代码,用于保存要发布的字段。
// Save fields in order meta data
add_action('woocommerce_checkout_create_order', 'save_custom_fields_to_order_meta_data', 20, 2 );
function save_custom_fields_to_order_meta_data( $order, $data ) {
$index = 0;
// 1st Loop through order items
foreach(WC()->cart->get_cart() as $cart_item){
// 2nd Loop through each unit related to item quantity
for($i = 1; $i <= $cart_item['booking']['Adults']; $i++){
$index++;
if (isset( $_POST['my_field'.$index.'']) && ! empty($_POST['my_field'.$index.'']) ){
$order->update_meta_data( '_my_field_'.$index.'_'.$i, esc_attr( $_POST['my_field'.$index.''] ) );
}
}
for($i = 1; $i <= $cart_item['booking']['Childs']; $i++){
$index++;
if (isset( $_POST['my_field'.$index.'']) && ! empty($_POST['my_field'.$index.'']) ){
$order->update_meta_data( '_my_field_'.$index.'_'.$i, esc_attr( $_POST['my_field'.$index.''] ) );
}
}
}
}
答案 0 :(得分:0)
// Display fields in order edit
add_action('woocommerce_admin_order_data_after_billing_address','display_custom_fields_in_admin_order', 20, 1);
function display_custom_fields_in_admin_order( $order ){
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_adult%' and post_id = ".$order->get_id()."" );
$i= 1;
foreach($results as $result) {
echo '<p><strong>Adult Name '.$i.':</strong>' . $result->meta_value . '</p>';
$i++;
}
$results = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_child%' and post_id = ".$order->get_id()."" );
$i= 1;
foreach($results as $result) {
echo '<p><strong>Child Name '.$i.':</strong>' . $result->meta_value . '</p>';
$i++;
}
}