Add additional fields to Admin User under Customer

2020-03-31 07:12发布

问题:

In woocommerce, after creating and registering some custom account fields in a custom php file using the following code:

<label for="reg_shipping_phone"> ... </label>
<input  class="..." id="reg_shipping_phone" name="shipping_phone" 
        type="tel" pattern="[a-z0-9.-]{6,40}"
        title=" ... " placeholder=" ... "
        value="<?php esc_attr_e( $_POST['shipping_phone'] ); ?>" />

and in my theme's function.php file:

//save on admin/&frontend on change
add_action( 'personal_options_update', 'woo_save_extra_register_fields' );    
add_action( 'woocommerce_save_account_details', 'woo_save_extra_register_fields' );

// Save extra registration fields data on from
add_action( 'woocommerce_created_customer', 'woo_save_extra_register_fields' );
function woo_save_extra_register_fields( $customer_id )
{
if( isset( $_POST['shipping_phone'] ) ) {
        update_user_meta( $customer_id, 'shipping_phone',  $_POST['shipping_phone'] );
    }
}

I would like to implement this "Shipping phone" field in the correct position on Backend User profile pages inside the "Customer's shipping address" section table

How can I insert additional fields in the "Customer's shipping address" section table?

For example I have tried the following *(but 11,5 is wrong...)*:

add_action( 'show_user_profile', 'extra_profile_fields',***11,5*** );
add_action( 'edit_user_profile', 'extra_profile_fields',***11,5*** );

function extra_profile_fields( $user ) { ?>


    <h3>NAME OF TABLE</h3>

    <table class="form-table">

        <tr>
            <th><label for="shipping_phone">SHIPPING PHONE</label></th>

            <td>
                <input type="text" name="shipping_phone" id="shipping_phone" value="<?php echo esc_attr(  $user->shipping_phone); ?>" class="regular-text" />
            </td>
        </tr>
>

    </table>
<?php }

Any help is appreciated.

回答1:

If you want to include your custom "Shipping phone" field in Backend User profile under "Customer's shipping address" section, you will use the following instead:

add_filter( 'woocommerce_customer_meta_fields', 'filter_add_customer_meta_fields', 10, 1 );
function filter_add_customer_meta_fields( $args ) {
    $args['shipping']['fields']['shipping_phone'] = array(
        'label'       => __( 'Shipping phone', 'woocommerce' ),
        'description' => '',
    );
    return $args;
}

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

This little code snippet will do it all. If you change the value in this "Shipping phone" field, it will be updated without needing any additional code.