User Relationship

I have created a custom registration page, whereby a person will receive a code from another user and type in a code upon registering. If the code matches, i need the user who has just registered to become related to the user who they received the code from. Note i am saving these codes in a custom plugin table.

So you will have a one to many relationship, where a user can have many sub users. If possible i need to be able to extend that further so that a sub user could also have many sub users. So the first relationship and my priority right now would be:

USER
 |
SUB-USER

I would then like to be able to do this:

USER - A
 |
SUB-USER B  -------
    |             |
 SUB-USER C    SUB-USER D

User B is related to User A. User C and D are related to B.

I know we can make use of the and Update User Meta and query these relationships with the following query, i would just like some advice about creating this sort of relationship going forward.

$users_sub_users = new WP_User_Query( array(
   'meta_key' => 'user',
   'meta_value' => $user_id
) );

1 Answer
1

if I were you, I would use the wp_usermeta table. it is possible to add information to this table easily:

add_user_meta(NEW_USER_ID, "PARENT_USER_ID",USER_ID,true);

USER_ID: the Id of top level user, (In your case id of user A)
“PARENT_USER_ID”: some key that you could search and find result based on
NEW_USER_ID: The Id of sub_user
true: To let many user be sub user of the same user

for instance if USER A id is 41, and the Id of new user (which is B) is 82 your code look like:

add_user_meta(82, "PARENT_USER_ID",41,true);

then you can search for all users which their PARENT_USER_ID is user_id (in our example 41) and then you will get all sub users for that user.

sample query:

$user_query = new WP_User_Query( array( 'meta_key' => 'PARENT_USER_ID', 'meta_value' => '41' ) );

Leave a Comment