因此,您不需要创建这些字段,这就是为什么它们被称为元字段,因为它们不需要任何设置。
我已经改进了代码并确保它正常工作,在这里和那里应用了一些好的实践,并添加了一些注释。
function custom_user_profile_fields( $user = null ) {
global $wpdb;
// This will check if we are dealing with the New User Page
if ( $user instanceof WP_User ){
// It\'s better to Just leave if the person doenst have permission
if ( ! $user->exists() || ! current_user_can( \'edit_users\', $user->ID ) ) {
return;
}
} elseif ( ! current_user_can( \'edit_users\' ) ) {
return;
}
$meta = (object) array(
\'client\' => \'\',
\'group\' => \'\',
);
if ( $user instanceof WP_User ) {
// Fetch the meta
$meta->client = get_user_meta( $user->ID, \'client\', true );
$meta->group = get_user_meta( $user->ID, \'user_groups\', true );
}
// Don\'t try to get info in the middle of the HTML (makes it harder to read the code later on)
$usergroups = $wpdb->get_results( \'SELECT usergroup_name FROM wp_usergroup;\' );
?>
<table class="form-table">
<tr>
<th><label for="company">Client Name</label></th>
<td>
<input type="text" class="regular-text" name="client" value="<?php echo esc_attr( $meta->client ); ?>" id="client" /><br />
</td>
</tr>
<tr>
<th><label for="company">User groups</label></th>
<td>
<select name="user_groups">
<option>None</option>
<?php foreach ( $usergroups as $group ) { ?>
<option <?php selected( $meta->group, $group ); ?> value="<?php echo esc_attr( $group->usergroup_name );?>"><?php echo esc_html( ucfirst( $group->usergroup_name ) ); ?></option>
<?php } ?>
</select>
</td>
</tr>
</table>
<?php
}
add_action( \'show_user_profile\', \'custom_user_profile_fields\' );
add_action( \'edit_user_profile\', \'custom_user_profile_fields\' );
add_action( \'user_new_form\', \'custom_user_profile_fields\' );
function save_custom_user_profile_fields( $user_id ) {
// again do this only if you can
if ( ! current_user_can( \'edit_users\', $user_id ) ) {
return;
}
if ( isset( $_POST[\'client\'] ) ) {
update_user_meta( $user_id, \'client\', sanitize_text_field( $_POST[\'client\'] ) );
} else {
delete_user_meta( $user_id, \'client\' );
}
if ( isset( $_POST[\'user_groups\'] ) ) {
update_user_meta( $user_id, \'user_groups\', sanitize_text_field( $_POST[\'user_groups\'] ) );
} else {
delete_user_meta( $user_id, \'user_groups\' );
}
}
add_action( \'user_register\', \'save_custom_user_profile_fields\' );
add_action( \'personal_options_update\', \'save_custom_user_profile_fields\' );
add_action( \'edit_user_profile_update\', \'save_custom_user_profile_fields\' );