Skip to content

Creating connections programmatically

scribu edited this page Nov 7, 2012 · 4 revisions

Say you want to connect two items using code, such as when you're developing your own admin box. There are two ways to go about it:

Connection type API

// Create connection
p2p_type( 'YOUR_CONNECTION_TYPE' )->connect( $from_id, $to_id, array(
	'date' => current_time('mysql')
) );

// Delete connection
p2p_type( 'YOUR_CONNECTION_TYPE' )->disconnect( $from_id, $to_id );

The advantage of using this API is that it enforces all the rules you set when defining the connection type, such as 'prevent_duplicates' and 'cardinality'.

Low-level API

p2p_create_connection( 'YOUR_CONNECTION_TYPE', array(
	'from' => $from_id,
	'to' => $to_id,
	'meta' => array(
		'date' => current_time('mysql')
	)
) );

"low-level" means that it does not enforce any logic checks; it doesn't even check if the connection type is registered. Use with caution.

Clone this wiki locally