完全难倒。我在用户个人资料页面上有一个复选框,但它拒绝更新。它甚至不是数组设置值或任何东西,只是从不设置...似乎没有数据传递给post值...
根据@RST更新,现在按@ simon-pollard
更新 // This will show below the color scheme and above username field
add_action( 'profile_personal_options', 'extra_profile_fields' );
add_action( 'personal_options_update', 'update_field_value' );
add_action( 'edit_user_profile_update', 'update_field_value' );
function extra_profile_fields( $user ) {
// get the value of a single meta key
$user_id = $user->ID;
echo "user id: " . $user_id . "<br/>";
$meta_value = get_user_meta( $user->ID, 'emailPrefs', true ); // $user contains WP_User object
// do something with it.
echo "checked value: " . $meta_value. "<br/>";
?>
<h2>Email Settings</h2>
<table class="form-table">
<th scope="row" id="lbl-subtitle" for="email-settings">Email on Timer Reset</th>
<td><fieldset>
<form method='post' action="profile.php">
<input type="checkbox" id="email-settings" name='email-settings'
<?php if ($meta_value == '1'){ echo 'checked'; } ?> value ="<?php echo $meta_value?>" />
</form>
<?php submit_button(); ?>
</td>
</fieldset>
</table>
<?php
}
function update_field_value($user) {
$user_id =$user->ID;
if (isset($_POST['email-settings']) && $_POST['email-settings'] == 'on') {
update_user_meta( $user_id, 'emailPrefs', '1');
} else {
update_user_meta( $user_id, 'emailPrefs', NULL);
}
}
答案 0 :(得分:0)
谢谢@Simon。在他的帮助下,我看到在该更新挂钩上无法访问$user
对象,这意味着user_meta从未更新过。为了解决这个问题,我创建了一个隐藏的表单字段来存储我的userID,以便它可以作为post变量使用。
以下是最终守则:
// This will show below the color scheme and above username field
add_action( 'profile_personal_options', 'extra_profile_fields' );
add_action( 'personal_options_update', 'update_field_value' );
add_action( 'edit_user_profile_update', 'update_field_value' );
function extra_profile_fields( $user ) {
// get the value of a single meta key
$user_id = $user->ID;
echo "user id: " . $user_id . "<br/>";
$meta_value = get_user_meta( $user->ID, 'emailPrefs', true ); // $user contains WP_User object
// do something with it.
echo "checked value: " . $meta_value. "<br/>";
?>
<h2>Email Settings</h2>
<table class="form-table">
<th scope="row" id="lbl-subtitle" for="email-settings">Email on Timer Reset</th>
<td><fieldset>
<form method='post' action="profile.php">
<input type='hidden' name="user_id" value="<?php echo $user_id ?>" />
<input type="checkbox" id="email-settings" name='email-settings'
<?php if ($meta_value == '1'){ echo 'checked'; } ?> />
</form>
<?php submit_button(); ?>
</td>
</fieldset>
</table>
<?php
}
function update_field_value($user_id) {
$user_id = $_POST['user_id'];
// echo $user_id;
// echo $_POST['email-settings'];
// wp_die();
if ( isset($_POST['email-settings'], $_POST['user_id'] ) && $_POST['email-settings'] == 'on') {
update_user_meta( $user_id, 'emailPrefs', '1');
} else {
update_user_meta( $user_id, 'emailPrefs', NULL);
}
}
留出已注释掉的部分,以便将来的读者可以自行检查。