I need to create My Account page for registered users with changeable fields on backend and frontend.
Now the fields are updated if I change the values through the admin panel. However, if I change the field values through My Account, the fields are not saved or updated.
What do i need to change or add to the code?
I used the following LoicTheAztec's answers:
Add a custom field in Woocommerce Edit Account page
Adding some my account custom fields to admin user pages in Woocommerce
Adding an additional custom field in Woocommerce Edit Account page
My code:
- Template:
$user = wp_get_current_user();
<form class="tabs-content__page_inner woocommerce-EditAccountForm edit-account" action="" method="post"
<div class="pers-acc__tab-fields_field tab-field woocommerce-form-row form-row">
<label for="account_phone" class="tab-field__title"><?php esc_html_e( 'Телефон', 'woocommerce' ); ?></label>
<div class="tab-field__input-inner">
<input type="text" class="tab-field__input woocommerce-Input woocommerce-Input--text input-text" name="account_phone" id="account_phone" value="<?php echo esc_attr( $user->account_phone ); ?>" />
</div>
</div>
</form>
- functions.php
<?php
add_action('woocommerce_save_account_details', 'save_phone_number_account_details', 20, 1);
function save_phone_number_account_details($user_id) {
if( isset( $_POST['account_phone'] ) ) {
update_user_meta( $user_id, 'account_phone', sanitize_text_field( $_POST['account_phone'] ) );
}
}
//custom field in admin console
add_action( 'show_user_profile', 'add_extra_custom_user_data', 1, 1 );
add_action( 'edit_user_profile', 'add_extra_custom_user_data', 1, 1 );
function add_extra_custom_user_data( $user )
{
?>
<h3><?php _e("Other details",'woocommerce' ); ?></h3>
<table class="form-table">
<tr>
<th><label for="account_phone"><?php _e( 'Custom phone', 'woocommerce' ); ?></label></th>
<td><input type="text" name="account_phone" value="<?php echo esc_attr(get_the_author_meta( 'account_phone', $user->ID )); ?>" class="regular-text" /></td>
</tr>
</table>
<br />
<?php
}
//save custom field value in admin console
add_action( 'personal_options_update', 'save_extra_custom_user_data' );
add_action( 'edit_user_profile_update', 'save_extra_custom_user_data' );
function save_extra_custom_user_data( $user_id )
{
if( ! empty($_POST['account_phone']) )
update_user_meta( $user_id, 'account_phone', sanitize_text_field( $_POST['account_phone'] ) );
}