如果在woocommerce中为空,请将结算地址保存到自定义结帐字段

时间:2017-10-25 14:55:45

标签: php wordpress woocommerce

我已经按照教程中的说明如何在结帐时包含自定义字段,一切正常,但我希望将完整的结算地址保存到此自定义字段(如果未填写)。

这就是我所拥有的

function cloudways_save_extra_checkout_fields( $order_id, $posted ){
// don't forget appropriate sanitization if you are using a different field type
if( isset( $posted['cloudways_text_field'] ) ) {
    update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );

if(empty($posted['cloudways_text_field']))
    {
    // it's empty!
        update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
    }
else
    {
        update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
    }    

}

}     add_action('woocommerce_checkout_update_order_meta','cloudways_save_extra_checkout_fields',10,2);

但我不知道如果没有填写,如何将帐单地址数组保存到此自定义文本字段。

指向教程的链接是https://www.cloudways.com/blog/how-to-edit-delete-fields-and-email-in-woocommerce-custom-checkout-fields/amp/

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试将地址构建到数组中并将其保存在字段中。或者您也可以将其构建为字符串,实际上取决于您希望字段包含的数据,字符串或数组。 这是一个数组的例子:

function cloudways_save_extra_checkout_fields( $order_id, $posted ) {
    // don't forget appropriate sanitization if you are using a different field type
    if ( isset( $posted['cloudways_text_field'] ) ) {
        update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );

        if ( empty( $posted['cloudways_text_field'] ) ) {
            $billing_address_array = array(
                'billing_address_1' => $posted['billing_address_1'],
                'billing_address_2' => $posted['billing_address_2'],
                'billing_city'      => $posted['billing_city'],
                'billing_postcode'  => $posted['billing_postcode'],
                'billing_state'     => $posted['billing_state'],
                'billing_country'   => $posted['billing_country'],
            );
            update_post_meta( $order_id, '_cloudways_text_field', wc_clean( $billing_address_array ) );
        } else {
            update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
        }
    }
}
add_action( 'woocommerce_checkout_update_order_meta', 'cloudways_save_extra_checkout_fields', 10, 2 );