Pre populate Woocommerce checkout fields

时间秒杀一切 提交于 2021-02-08 06:33:48

问题


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

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