How to add billing fields on the Woocommerce edit-account page! (Wordpress)

2

Personal how can I add fields that are already default to woocommerce on my account page? I tried it like this: but do not aim at the expected result.

add_action( 'woocommerce_edit_account_form', 'add_fields_to_edit_account_form');
function add_fields_to_edit_account_form( $fields ) {
    $fields['billing']['billing_cpf'] = array(
        'label'         => __('CPF', 'woocommerce'),
        'placeholder'   => _x('CPF', 'placeholder', 'woocommerce'),
        'required'      => true,
        'class'         => array('form-row-last'),
     );

    return $fields;
}

Thank you!

    
asked by anonymous 24.10.2018 / 15:03

1 answer

1

If this CPF is coming through the WooCommerce Extra Checkout Fields plugin, the billing method in an array probably will not understand this information in woocommerce_edit_account_form . The easiest, but less dynamic, way would be to pull this information through the wp_get_current_user () function. Below you can see how I did (incidentally, I followed the same formatting as the form-edit-account.php of WooCommerce):

//add cpf field
function add_cpf_field() {

    $user = wp_get_current_user();

    ?><p class="woocommerce-form-row woocommerce-form-row--first form-row form-row-first">
        <label for="billing_cpf"><?php esc_html_e( 'CPF', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="billing_cpf" id="billing_cpf" value="<?php echo esc_attr( $user->billing_cpf ); ?>" />
    </p><?php
}
add_action( 'woocommerce_edit_account_form', 'add_cpf_field');


//save cpf field
function save_cpf_details( $user_id ){
    $cpf = ! empty( $_POST['billing_cpf'] ) ? wc_clean( $_POST['billing_cpf'] ) : '';
    update_user_meta( $user_id, 'billing_cpf', $cpf );
}

add_action( 'woocommerce_save_account_details', 'save_cpf_details' );

//validate cpf field
function validate_cpf( $validation_error  ) {
    if ( isset( $_POST['billing_cpf'] ) ) {

    if(strlen($_POST['billing_cpf']) < 11 ) //condição básica de pelo menos 11 caracteres
        $validation_error->add( 'error', __( 'Your CPF is not valid.', 'woocommerce' ),'');
    }
}
add_action( 'woocommerce_save_account_details_errors','validate_cpf', 10, 1 );

I hope I have helped! ;)

    
24.10.2018 / 18:00