Reciprocal connections

g4ll4is edited this page Dec 12, 2012 · 21 revisions

An indeterminate connection type is one in which at least one post type appears both in the 'from' arg and in the 'to' arg:

p2p_register_connection_type( array(
	'name' => 'posts_to_posts',
	'from' => 'post',
	'to' => 'post'
) );

Because 'post' appears twice, when editing a post in the administration area, P2P can't tell if you want to create a connection from the current post or to the current post. There are two ways to handle this:

'reciprocal' => true

p2p_register_connection_type( array( 
	'name' => 'friendship',
	'from' => 'person',
	'to' => 'person',
	'reciprocal' => true,
	'title' => 'Friends with'
) );

'reciprocal' => true simply means that the direction is not important; it's always set to 'any'.

All connections will show up in a single box and you can use get_connected() and each_connected() as usual.

'reciprocal' => false (default)

p2p_register_connection_type( array( 
	'name' => 'employee_manager',
	'from' => 'employee',
	'to' => 'employee',
	'cardinality' => 'one-to-many',
	'title' => array( 'from' => 'Managed by', 'to' => 'Manages' )
) );

In this mode, when editing an employee, you will see two meta boxes, one titled 'Managed by' and another one titled 'Manages'.

Because this is an indeterminate post type, when calling get_connected(), the direction will always be 'from':

$connected = p2p_type( 'employee_manager' )->get_connected( $post_id );

$connected will always contain a list of employees that the current post manages.

To get the manager for the current post, you can do this:

$connected = p2p_type( 'employee_manager' )->set_direction( 'to' )->get_connected( $post_id );

If you only want to show a single box, you can set 'admin_box' => 'from' or 'admin_box' => 'to' when calling p2p_register_connection_type().