我发现您的代码中有两个问题。第一个是用户能力级别,第二个是如何保存数据。
您可以通过在保存功能中设置更高的功能要求来修复第一个功能,这是一些只有管理员才具有的功能。关于edit_user
能力,WordPress Capabilities: edit_user vs edit_users
第二个问题可以通过添加isset()
检查是否发送自定义字段值$_POST
. 在当前表单中,如果未设置自定义字段值,则$_POST[\'field-key]
结果在null
值,该值覆盖以前保存的任何数据。一、 e。update_user_meta( $user_id, \'pin\', $_POST[\'pin\'] );
下面是一个如何改进代码的示例。在我的示例中,我添加了一个nonce检查,升级了功能需求,添加了isset()
检查和数据清理。
function extra_user_profile_fields( $user ) {
// add nonce field
wp_nonce_field( \'my_extra_user_profile_fields\', \'my_extra_user_profile_fields_nonce\', true, true );
?>
<!-- your html as it was -->
<?php
}
function save_extra_user_profile_fields( $user_id ) {
// Nonce checks to know the $_POST is coming from the right source
if ( empty( $_POST[\'my_extra_user_profile_fields_nonce\'] ) || ! wp_verify_nonce( \'my_extra_user_profile_fields_nonce\', \'my_extra_user_profile_fields\' ) ) {
return;
}
// Capabilities check
// create_users is administrator only capability
if ( ! current_user_can( \'create_users\', $user_id ) ) {
return;
}
// valid field keys with related data type
// update types as needed
$fields = array(
\'pin\' => \'string\',
\'street-address\' => \'string\',
\'suburb\' => \'string\',
\'postcode\' => \'string\',
\'phone\' => \'string\',
\'mobile\' => \'string\',
\'president-year\' => \'int\',
\'secretary-year\' => \'int\',
\'competition-secretary-year\' => \'int\',
\'treasurer-year\' => \'int\',
\'committee-member-year\' => \'int\',
\'joining-date\' => \'string\',
\'fees-paid\' => \'bool\',
\'life-member\' => \'string\',
\'comments\' => \'string\',
\'other-roles\' => \'string\',
\'year-left\' => \'int\',
);
// loop fields instead of typing each update separately
foreach ($fields as $key => $data_type) {
// check if field data is sent with $_POST
if ( isset( $_POST[$key] ) ) {
// update user meta with sanitized value
update_user_meta( $user_id, $key, my_sanitize_user_data($_POST[$key], $data_type) );
}
}
}
function my_sanitize_user_data( $value, string $type = \'\' ) {
switch ($type) {
case \'bool\':
return in_array( $value, array(true, \'true\', 1, \'yes\') ); // returns true, if value is in array otherwise false
case \'int\':
return is_numeric($value) ? absint( $value ) : 0;
default:
return sanitize_text_field( $value );
}
}
我想你也可以
add_action( \'personal_options_update\', \'save_extra_user_profile_fields\' );
像
add_action( \'edit_user_profile_update\', \'save_extra_user_profile_fields\' );
涵盖数据保存。