I am trying to add a new field to my user edit page but I get this error
Notice: Object of class WP_User could not be converted to int in C:\xampp\htdocs\wordpress\wp-includes\capabilities.php on line 49
Here is the code I use for the functions,
static function my_extra_user_fields( $user_id ) {
echo $user_id->ID;
$user_meta = get_user_meta($user_id);
if (!empty ($user_meta['_is_post_agent'][0])) {
$check_true = $user_meta['_is_post_agent'][0];
}
else {
$check_true="false";
}
?>
<h3>Agent Author</h3>
<table class="form-table">
<tr>
<th><label for="agent_author">Agent Author</label></th>
<td>
<input type="checkbox" name="agent_author" value="is_author_agent" <?php if($check_true == 'true') echo 'checked="checked"';?> >
</td>
</tr>
</table>
<?php }
static function save_my_extra_user_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}else{
if(isset($_POST['agent_author']) && $_POST['agent_author'] == true) {
update_user_meta( $user_id, '_is_post_agent', 'true');
}
elseif(isset($_POST['agent_author']) && $_POST['agent_author'] == false) {
update_user_meta( $user_id, '_is_post_agent', 'false');
}
}
}
I would appreciate any help as to what I am doing wrong here!
get_user_meta()
expects the first parameter to be an integer (or something that can be converted to an integer. If that parameter can't be converted to an integer, you will get that error.
Try switching line 3 above to:
$user_meta = get_user_meta($user_id->ID);
As per the Wordpress documentation, it is expecting that to be an integer.
This is the right way to add a checkbox field "Agent Author" to user edit screen:
add_action( 'show_user_profile', 'brg_agent_author_field' );
add_action( 'edit_user_profile', 'brg_agent_author_field' );
function brg_agent_author_field( $user ) {
$is_agent = get_the_author_meta( 'agent_author', $user->ID );
?>
<h3>Agent Author</h3>
<table class="form-table">
<tr>
<th><label for="agent_author">Agent Author</label></th>
<td>
<input type="checkbox" name="agent_author" <?php if ($is_agent) echo 'checked="checked"'; ?>>
</td>
</tr>
</table>
<?php }
And that's how you save it:
add_action( 'personal_options_update', 'brg_save_agent_author_field' );
add_action( 'edit_user_profile_update', 'brg_save_agent_author_field' );
function brg_save_agent_author_field( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
update_usermeta( $user_id, 'agent_author', $_POST['agent_author'] );
}
The simplest way to make it work is to add this code to your theme's functions.php
.