Home > database >  can you use a function to save lines during an ajax call?
can you use a function to save lines during an ajax call?

Time:02-17

Apologies if I didn't quite word my title correctly. I am currently finishing up this Wordpress AJAX challenge in which we needed to display particular user-types to the screen depending on a plugin's selection. The function below is whats being called in my AJAX call. I currently am running multiple instances of this code below, one for each user-type:

$user_roles = get_option( 'show_users' );
$count = 0;

if($user_roles['administrator']) {

    $users = get_users( array (
        'role' => 'administrator'
    ));

    foreach ($users as $user) {
        $result[$count] = $user->display_name;
        $count  ;
    }

}

However, I thought I might be able to create a function that can save me some code (and maybe even use a foreach later to save even more), but the code does not seem to work. Function I tried using (followed by calling the function) :

function save_time ($x) {
    if ($user_roles[$x]) {
        $users = get_users( array (
            'role' => $x
        ));

        foreach ($users as $user) {
            $result[$count] = $user->display_name;
            $count  ;
        }
    }
}

save_time('administrator');

Is there something I can do make this work? Am I forgetting how functions work in general? Thank you!

CodePudding user response:

You already have an array of roles so you could just use that.

foreach($user_roles as $role => $values) {
    $users = get_users( array (
        'role' => $role
    ));
    foreach ($users as $user) {
        $result[$count] = $user->display_name;
        $count  ;
    }
}

Then you don't even have to define one for each type.

  • Related