2017-02-15 103 views
0

我已經在Woo-commerce網站上訂購了大約10,000個訂單。約0.4%未保存所需的自定義字段「custom_location」。我不知道這是如何可能的,無法找到重現的方式。WooCommerce自定義字段不保存到數據庫...有時

此外,我使用該字段的選定值將輔助值保存到數據庫。即使數據庫中的'custom_location'爲空,輔助值也會正確保存。顯然,$ _POST ['custom_location']包含有效的數據,但它沒有保存...爲什麼?

// Here I create the custom select field 
add_filter('woocommerce_checkout_fields' , 'custom_override_checkout_fields'); 
function custom_override_checkout_fields($fields) { 
    // <select> options 
    $args = array('post_type' => 'MY_CUSTOM_POST_TYPE', 
       'posts_per_page' => -1, 
       'order' => 'ASC', 
       'post_status' => 'publish', 
       'suppress_filters' => true); 
    $locations = get_posts($args); 
    $ops = array('default' => 'Select a location'); 
    foreach($locations as $l) { 
     $ops[$l->ID] = __($l->post_title, 'woocommerce'); 
    } 
    // Add 'custom_location' field to 'shipping' 
    $fields['shipping'] = array('custom_location' => array(
     'label'  => __('Location', 'woocommerce'), 
     'placeholder' => _x('', 'empty', 'woocommerce'), 
     'required' => true, 
     'clear'  => false, 
     'type'  => 'select', 
     'options'  => $ops 
     )) 
     + $fields['shipping']; 

    return $fields; 
} 
// Save related data 
add_action('woocommerce_checkout_update_order_meta', 'save_extra_data'); 
function save_extra_data($order_id) { 
    $loc = $_POST['custom_location']; 

    // This was saved correctly to DB even when 'custom_location' is null in DB! 
    $meta = get_post_meta($loc, 'extra-shipping-data', true); 
    update_post_meta($order_id, '_shipping_extra', $meta); 
} 
+0

其中定義了您在foreach循環中使用的$位置變量? – LoicTheAztec

+0

我將$ locations var添加到代碼中。這是我通過「get_posts()」獲得的一系列帖子 –

回答

0

如果客戶賬單和送貨地址相同,您的位置將被保存爲空。在您的代碼中,缺少locations的聲明。只需稍作更改,您就可以最大限度地減少代碼和工作量。確保你用你的選擇替換ops

add_filter('woocommerce_checkout_fields' , 'custom_override_checkout_fields'); 
function custom_override_checkout_fields($fields) { 
    // <select> options 
    $ops = array('default' => 'Select a location', 'location1' => 'Location 1'); 

    // Add 'custom_location' field to 'shipping' 
    $fields['shipping'] = array('shipping_custom_location' => array(
     'label'  => __('Location', 'woocommerce'), 
     'placeholder' => _x('', 'empty', 'woocommerce'), 
     'required' => true, 
     'clear'  => false, 
     'type'  => 'select', 
     'options'  => $ops 
    )) 
    + $fields['shipping']; 

    return $fields; 
} 
+0

在這個應用程序中,送貨地址總是與開票不同,所以我們不允許它是可選的。我在前一段時間添加了位置聲明,對不起,你錯過了。 (順便說一下,$ ops確實需要由管理員編輯,這就是get_posts代碼存在的原因) –

+0

您是否嘗試將id從'custom_location'更改爲'shipping_custom_location'?它應該工作。 – LearnWoo