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 );
}
Just call
p2p_connect( $id_of_post_type_a, $id_of_post_type_b );
in the form handling code.