WooCommerce: get and set shipping & billing address's postcode

亡梦爱人 提交于 2019-12-09 05:39:26

问题


How do I set/get the Postcode(Zip-code) in woocommerce? Is there a function for this?

ie., can I set the zip code through any function?

I would also like to know, how to populate this field with my data(say 546621) if the user is not logged in?


回答1:


You can do the following to get/set billing/shipping postcodes,

To set the values,

$customer = new WC_Customer();
$customer->set_postcode('123456');     //for setting billing postcode
$customer->set_shipping_postcode('123456');    //for setting shipping postcode

If you just want to fetch the postcodes, you can fetch it from the user meta table itself,

$shipping_postcode = get_user_meta( $current_user->ID, 'shipping_postcode', true );
$billing_postcode = get_user_meta( $current_user->ID, 'billing_postcode', true );



回答2:


Thanks @rao! I was looking for this for hours...I was able to take your code and use it to pull the user's entire address - so I can use each address field to pre-populate an address form I'm creating elsewhere.

$fname = get_user_meta( $current_user->ID, 'first_name', true );
$lname = get_user_meta( $current_user->ID, 'last_name', true );
$address_1 = get_user_meta( $current_user->ID, 'billing_address_1', true ); 
$address_2 = get_user_meta( $current_user->ID, 'billing_address_2', true );
$city = get_user_meta( $current_user->ID, 'billing_city', true );
$postcode = get_user_meta( $current_user->ID, 'billing_postcode', true );

echo $fname . "<BR>";
echo $lname . "<BR>";
echo $address_1 . "<BR>";
echo $address_2 . "<BR>";
echo $city . "<BR>";
echo $postcode . "<BR>";



回答3:


You can use the WC_Customer class which provides this function. Its loaded inside the Woocommerce class. This information is stored inside the current session.

function set_shipping_zip() {
    global $woocommerce;

    //set it
    $woocommerce->customer->set_shipping_postcode( 12345 );
    $woocommerce->customer->set_postcode( 12345 );

    //get it
    $woocommerce->customer->get_shipping_postcode();    
    $woocommerce->customer->get_postcode();
}

The complete documentation for this class: http://docs.woothemes.com/wc-apidocs/class-WC_Customer.html

Hope this helps.



来源:https://stackoverflow.com/questions/19155682/woocommerce-get-and-set-shipping-billing-addresss-postcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!