4

I've added a custom field to users profile using the following code:

/*** Adding extra field to get the the user who creates the another user during ADD NEW USER ***/

<?php

function custom_user_profile_fields($user){
    if(is_object($user))
        $created_by = esc_attr( get_the_author_meta( 'created_by', $user->ID ) );
    else
        $created_by = null;
    ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="created_by">Created By</label></th>
            <td>
                <input type="text" class="regular-text" name="created_by" value="<?php echo $created_by; ?>" id="created_by" /><br />
                <span class="description">The person who creates this user</span>
            </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){
    update_user_meta($user_id, 'created_by', $_POST['created_by']);
}
add_action('user_register', 'save_custom_user_profile_fields');
add_action('profile_update', 'save_custom_user_profile_fields');

?>

Now I see a field created by when I create a new user from the admin panel AND Now I want to get the users by the field created_by

Codex : https://codex.wordpress.org/Function_Reference/get_users

so as per the codex it should be somthing like this:

<?php 
get_users( $args ); 
$args = array(  
        'meta_key'     => '',
        'meta_value'   => '',
    )   
$blogusers = get_users( $args );
// Array of stdClass objects.
foreach ( $blogusers as  $my_users ) {
    echo  $my_users. '<br/>';
}
?>

I've tried various options for meta_key and meta_value But all returns just empty.

What is the exact meta_key and meta_value for the field I created using the function custom_user_profile_fields ?

How can get the users by the custom field created_by ?

1 Answer 1

8

What is the exact meta_key and meta_value for the field I created using the function custom_user_profile_fields ?

created_by and some user ID, for example:

$args = array(  
        'meta_key'     => 'created_by',
        'meta_value'   => 123,
)

You could use a meta_query for more complex searches.

$args = array( 
  'meta_query' => array(
    array(
        'key' => 'created_by',
        'compare' => 'EXISTS',
    ),
  ) 
);
var_dump(get_users($args));

Essentially, though, what you are doing is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.