Skip to content

Users 2 Users

landwire edited this page Mar 4, 2014 · 5 revisions

To set-up a connection type:

p2p_register_connection_type( array(
        'name' => 'user_to_user', // you can use any name here
        'from' => 'user',
        'to' => 'user',
		'fields' => array( // this creates extra meta fields that can be added to a connection - use to distinguish between connections by meta
					'role' => array(
					    'type' => 'text',
					),
		)
    ) );

Then to make a connection:

// Create connection
$from = 1; // user ID
$to = 2; // user ID
p2p_type( 'user_to_user' )->connect( $from, $to, array(
    'role' => 'Friend'
) );

To display information:

$user = 1; // set $user ID

// query gets all users connected to $user
$user_query = new WP_User_Query( array(
        'connected_type' => 'user_to_user',
        'connected_items' => $user,
) );

// User Loop
if ( ! empty( $user_query->results ) ) {
	foreach ( $user_query->results as $user ) {
		echo '<p>' . $user->display_name . '</p>';
		echo 'Role: ' . p2p_get_meta( $user->p2p_id, 'role', true );		
        }
} else {
	echo 'No users found.';
}