WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I programmatically create a connection between one custom post type, cpt, (with post id known) to another on cpt on publish?

I am using VoodooPress's front-end posting method to publish a post type called post-type-A. One input field in the post-type-A form is the public inventory number, which through some wp_query love gives me the post id of the post-type-B that I wish to create a relationship with.

I know that I can use this function to create a one-way connection from post-type-A to post-type-B using a custom field.

add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'field-name', 'custom value', true);

But how do I programmatically create a connection using @Scribu's Posts 2 Posts plugin? A two-way relationship would reduce a lot of hassle and programming time. :)

For reference, the snippet below is the connect api reference for the plugin...

 * Connect a post to another one
 * @param int $post_a The first end of the connection
 * @param int $post_b The second end of the connection
 * @param bool $bydirectional Wether the connection should be bydirectional
function p2p_connect( $post_a, $post_b, $bydirectional = false ) {
        add_post_meta( $post_a, P2P_META_KEY, $post_b );

        if ( $bydirectional )
                add_post_meta( $post_b, P2P_META_KEY, $post_a );
share|improve this question
up vote 6 down vote accepted

Just call p2p_connect( $id_of_post_type_a, $id_of_post_type_b ); in the form handling code.

share|improve this answer
Thanks Scribu~~ – mattrepublic Jul 24 '11 at 23:42
Update: as seen on here: link this has changed to: p2p_type( 'YOUR_CONNECTION_TYPE' )->connect. More on the p2posts wiki: link – Álex Acuña Viera Jun 20 '12 at 3:18
@ÁlexAcuñaViera You should post that as an answer, as my answer is clearly outdated. :) – scribu Jun 20 '12 at 16:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.