Save filtered billing phone to admin user profile in WooCommerce

谁说胖子不能爱 提交于 2021-01-28 12:19:15

问题


Everything I have read over the last couple of days has indicated that if I want to save fields in the user-edit.php (User Admin Backend), I should be using the edit_user_profile_update & personal_options_update hooks (and I'm not including the validation hook in this question...)

In the codex, they state that:

Consider an example:

update_user_meta($user_id, 'custom_meta_key', $_POST['custom_meta_key']);

Make doubly sure that you give a different key name for the $_POST data key and the actual user meta key. If you use the same key for both, Wordpress for some reason, empties the value posted under that key.
So you'll always get an empty value in $_POST['custom_meta_key'] so change it in the html input element's name attribute and append a suffix. Changing it to $_POST['custom_meta_key_data'] and it'll pass the data properly.

However, given the fact that I want to add validations to the existing billing_phone field, I do not know how to create said "custom_meta_key_data" (eg: '_billing_phone', or 'prefix_billing_phone') to then enter the value into said prefix_billing_phone to then convert to 'billing_phone' via update_user_meta().

I have provided my base code below, and I have searched the internet for two days as to a solution, but I cannot find a workaround.

In addition, the str_replace() doesn't action, which made me look inside the user-edit.php and the comments support the quoted notes above, where between hitting update, and the profile reloading, it saves each variable as _billing_ (prefixed '_') and records the original value (pre if statements / my code below) and saves that - not what I have conditioned/attempted to validate. I don't know how to copy that so that I can simply validate my fields...

add_action( 'personal_options_update', 'audp_save_user_account_fields' );
add_action( 'edit_user_profile_update', 'audp_save_user_account_fields' ); 

function audp_save_user_account_fields( $user_id ) {
    
    /* Input Value: "0412 345 678"
     * SHOULD Become: "0412345678"
     */
    $billing_phone = str_replace( array( ' ', '(', ')' ), '', $_POST['billing_phone'] );
    
    if ( !empty( $_POST['billing_phone'] ) && preg_match( '/^04[0-9]{8}$/D', $billing_phone ) ) {
        
        $billing_phone_query = get_users( array( 
            'meta_key' => 'billing_phone',
            'meta_value' => $billing_phone, 
        ) );
        
        foreach ( $billing_phone_query as $query ) {
            
            if ( $user_id == $query->ID ) {
                
                /* This value ($billing_phone) should be eg: "0412345678"
                 * but remains "0412 345 678" 
                 */
                update_user_meta( $user_id, 'billing_phone', $billing_phone );
            
            }
        
        }
    
    }

}

Addition / Edit

Under personal_options_update and edit_user_profile_update the fields still do not update as per the conditionals. For example, if I enter '0411 111 111' (spaces), the spaces are not removed. I have attempted to do var_dump( $_POST ); die(); at every stage of the conditional below and the value ('billing_phone') passes the changes (eg: 0411111111), but at the update_user_meta() and when the page reloads it reverts back to the '0411 111 111'? The code I have is:

function audp_save_user_account_fields( $user_id ) {
    
    $billing_phone_key = 'billing_phone';
    
    if ( isset( $_POST[$billing_phone_key] ) ) {
        
        // var_dump( $_POST['billing_phone_key] ) = '0411 111 111'
        $billing_phone = preg_replace( '/[^0-9]/i', '', sanitize_text_field($_POST[$billing_phone_key] ) );
        // var_dump on $billing_phone = '0411111111'
        
        if ( !empty( $_POST[$billing_phone_key] ) ) {
            
            // var_dump( $billing_phone ) = '0411111111'
            update_user_meta( $user_id, 'billing_phone', $billing_phone );
            // page reloads with value '0411 111 111'.
        }
        
    }

}
add_action( 'edit_user_profile_update', 'audp_save_user_account_fields' );

I read somewhere that you might have to pass the old variable and the new variable somehow and/or delete the user_meta_data and then add the new one but I have not tried that yet...?? Any further suggestions would be appreciated.


回答1:


Updated

Now to filter a phone number string keeping only numbers, you can better use preg_replace() than str_replace().

In the following, The billing phone number will be filtered before saving in:

  • Wordpress admin user dashboard
  • My Account Addresses Edit billing Address
  • Once order is placed (before data is saved)

The code:

// In Wordpress user profile (increased hook priority)
add_action( 'personal_options_update', 'save_user_billing_phone_fields', 999999 );
add_action( 'edit_user_profile_update', 'save_user_billing_phone_fields', 999999 );
function save_user_billing_phone_fields( $user_id ) {
    $field_key = 'billing_phone';

    if( isset($_POST[$field_key]) && ! empty($_POST[$field_key]) ) {
        // Filtering billing phone (removing everything else than numbers)
        $billing_phone = preg_replace( '/[^0-9]/', '', sanitize_text_field($_POST[$field_key]) );

        // Update the billing phone
        update_user_meta( $user_id, 'billing_phone', $billing_phone );
    }
}

// On My account > edit addresses > Billing
add_action( 'woocommerce_process_myaccount_field_billing_phone', 'filter_my_account_billing_phone_fields' );
function filter_my_account_billing_phone_fields( $value ) {
    return preg_replace( '/[^0-9]/', '', $value );
}

// On order submission
add_action( 'woocommerce_checkout_posted_data', 'wc_checkout_posted_data_filter_callback' );
function  wc_checkout_posted_data_filter_callback( $data ) {
    $field_key = 'billing_phone';

    if( isset($data[$field_key]) ) {
        // Filtering billing phone (removing everything else than numbers)
        $data[$field_key] = preg_replace( '/[^0-9]/', '', $data[$field_key] );
    }
    return $data;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Related: Extract numbers from a string



来源:https://stackoverflow.com/questions/62813524/save-filtered-billing-phone-to-admin-user-profile-in-woocommerce

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