问题
I am trying to pre-populate additional fields in the woocommerce checkout page but I am struggling with it.
add_filter('woocommerce_checkout_get_value', function($input, $key ) {
global $current_user;
switch ($key) :
case 'billing_first_name':
case 'shipping_first_name':
return $current_user->first_name;
break;
case 'billing_last_name':
case 'shipping_last_name':
return $current_user->last_name;
case 'billing_phone':
return $current_user->phone;
break;
case 'billing_company':
case 'shipping_company':
return $current_user->company;
break;
case 'billing_vat':
return $current_user->vat;
break;
endswitch;
}, 10, 2);
It works except for $current_user->phone, $current_user->company, $current_user->vat
Any help please?
回答1:
The phone, company and other information is in the Meta data.
$phone = get_user_meta($current_user,'phone_number',true);
You also do not need to have a global variable. It is also dangerous.
add_filter('woocommerce_checkout_get_value', function($input, $key )
{
$current_user = get_current_user_id();
switch ($key) :
case 'billing_first_name':
case 'shipping_first_name':
return $current_user->first_name;
break;
case 'billing_last_name':
case 'shipping_last_name':
return $current_user->last_name;
case 'billing_phone':
$phone = get_user_meta($current_user,'phone_number',true);
return $phone;
break;
case 'billing_company':
case 'shipping_company':
// May or may not be in meta data
break;
case 'billing_vat':
// Not available through user
break;
endswitch;
}, 10, 2);
You can see more here: https://codex.wordpress.org/Function_Reference/get_user_meta
Vat is a bit more complicated in that it is based on country and not the user name. While country is there, the VAT will not be. The best way to retrieve that is through woocommerce.
As for company name (sometimes called organization) that too is not direct Wordpress. It is typically added via a 3rd party plugin, like woocommerce, memberships or a custom plugin that will add the feature to the account. You have to see what you are using.
回答2:
just use like this
global $current_user;
case 'billing_phone': return $current_user->billing_phone; break;
来源:https://stackoverflow.com/questions/55494911/pre-populate-woocommerce-checkout-fields