首页 > 解决方案 > 预填充 Woocommerce 结帐字段

问题描述

我正在尝试在 woocommerce 结帐页面中预先填充其他字段,但我正在为此苦苦挣扎。

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);

它适用于 $current_user->phone、$current_user->company、$current_user->vat

请问有什么帮助吗?

标签: phpwordpresswoocommercecheckouthook-woocommerce

解决方案


电话、公司和其他信息在元数据中。

 $phone = get_user_meta($current_user,'phone_number',true);

您也不需要全局变量。这也是危险的。

 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);

你可以在这里看到更多: https ://codex.wordpress.org/Function_Reference/get_user_meta

增值税有点复杂,因为它基于国家而不是用户名。虽然国家存在,但增值税不会存在。检索它的最佳方法是通过 woocommerce。

至于公司名称(有时称为组织)也不是直接的 Wordpress。它通常是通过 3rd 方插件添加的,例如 woocommerce、会员或自定义插件,该插件会将功能添加到帐户中。你必须看看你在用什么。


推荐阅读