View/update 管理员 WP 用户页面中的 WooCommerce 用户自定义字段

View/update WooCommerce user custom field in admin WP user pages

我使用这个问题中给出的答案在 functions.php 中添加了一个自定义字段:

我的代码是:

// Add the custom field "ukara"
add_action( 'woocommerce_edit_account_form_start', 'add_ukara_to_edit_account_form' );
add_action( 'show_user_profile', 'add_ukara_to_edit_account_form' );
function add_ukara_to_edit_account_form() {
    $user = wp_get_current_user();
    ?>
        <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="ukara"><?php _e( 'Ukara No.', 'woocommerce' ); ?></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="ukara" id="ukara" value="<?php echo esc_attr( $user->ukara ); ?>" />
    </p>
    <?php
}

// Save the custom field 'ukara' 
add_action( 'woocommerce_save_account_details', 'save_ukara_account_details', 12, 1 );
function save_ukara_account_details( $user_id ) {
    // For Favorite color
    if( isset( $_POST['ukara'] ) )
        update_user_meta( $user_id, 'ukara', sanitize_text_field( $_POST['ukara'] ) );

}

如何将该字段添加到管理员视图中的用户部分,以便我可以看到该字段的特定用户数据?

您的代码中有一些错误。使用以下内容也可以 add/update 此用户自定义字段到 Wp 用户页面:

// Add the custom field "ukara" to WooCommerce my account - edit account
add_action( 'woocommerce_edit_account_form_start', 'add_ukara_to_edit_account_form' );
function add_ukara_to_edit_account_form() {
    $value = get_user_meta( get_current_user_id(), 'ukara', true );
    ?>
        <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="ukara"><?php _e( 'Ukara No.', 'woocommerce' ); ?></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="ukara" id="ukara" value="<?php echo $value; ?>" />
    </p>
    <?php
}

// Add the custom field "ukara" to wp user
add_action( 'show_user_profile', 'add_ukara_to_wp_user_pages' );
add_action ( 'edit_user_profile', 'add_ukara_to_wp_user_pages' );
function add_ukara_to_wp_user_pages( $user ) {
    $value = get_user_meta( $user->ID, 'ukara', true );
    ?>
        <table class="form-table"><tr>
            <th><label for="ukara"><?php _e( 'Ukara No.', 'woocommerce' ); ?></label></th>
            <td><input type="text" name="ukara" value="<?php echo esc_attr($value); ?>" class="regular-text" id="ukara" /></td>
        </tr></table><br />
    <?php
}

// Save the custom field 'ukara'
add_action( 'woocommerce_save_account_details', 'save_ukara_user_custom_field' );
add_action ( 'personal_options_update', 'save_ukara_user_custom_field' );
add_action ( 'edit_user_profile_update', 'save_ukara_user_custom_field' );
function save_ukara_user_custom_field( $user_id ) {
    if( isset( $_POST['ukara'] ) ) {
        update_user_meta( $user_id, 'ukara', sanitize_text_field( $_POST['ukara'] ) );
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。测试和工作。