• Resolved nthnlsmmrs

    (@nthnlsmmrs)


    Quick question, how would I go about returning a random user id #?

    Essentially I’m using the extra fields plugin and I want to be able to randomly display data from specific fields but from one user at a time. In order to do this I would need to find a way of generating a random user ID. I know how to generate random numbers between certain values… but I don’t know how to make it dynamic enough to account for an ever growing total of users or missing ID numbers (such as a gap where a member was… and then was deleted).

    Would there be a way to produce an array of all the id’s and then randomly pick from that array?

    I don’t need the actual code (although I would appreciate it), If anyone could at least point me towards some documentation, that would be awesome.

    Any help would be greatly appreciated.
    ~Nathaniel

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    global $wpdb; // if you're in a function
    $random_user_id = $wpdb->get_var("SELECT ID FROM $wpdb->users ORDER BY RAND() LIMIT 1");

    This will work fine as long as you don’t have a few hundred thousand users or something.

    Thread Starter nthnlsmmrs

    (@nthnlsmmrs)

    Oddly, when I use that code it breaks. Do I need to replace wpdb with the name of my database or is that a reference that is used standard by WP that will reference the DB specified in the config file?

    Either way, with or without the global declaration, it doesn’t seem to work. Not sure why.

    Thread Starter nthnlsmmrs

    (@nthnlsmmrs)

    Ok… after quite some fiddling around and a healthy helping of trial and error. I managed to get this to work… still not sure why.

    global $wpdb;
    $rid = $wpdb->get_var(“SELECT * FROM $wpdb->users ORDER BY RAND() LIMIT 1”);

    Thanks for the help, that was the last building block for my new site. I should be able to proceed with development of the content and functionality testing.

    Thanks,
    ~Nathaniel

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Random User ID #’ is closed to new replies.