Skip to content

Creating connections programmatically

Anca Mosoiu edited this page Jan 21, 2015 · 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

$from and $to are post or user objects or IDs:

<?php
// Create connection
p2p_type( 'YOUR_CONNECTION_TYPE' )->connect( $from, $to, array(
	'date' => current_time('mysql')
) );

This function returns the ID of the new connection, or WP_Error if it fails.

// Delete connection
p2p_type( 'YOUR_CONNECTION_TYPE' )->disconnect( $from, $to );

This function returns the number of connections deleted, or WP_Error if it fails.

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

<?php
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.

Also see Connection metadata.