Linking Two Post Types

Scribu’s posts-to-posts is a great and simple plugin, I’m sure we can help you get it working. The basic usage is pretty straightforward.

assuming your custom post types are named 'place' and 'event', the following code would go into your theme’s functions.php file:

function my_connection_types() {
    p2p_register_connection_type( array(
        'name' => 'events_to_places', 
        'from' => 'event',
        'to' => 'place',
    ) );
}
add_action( 'p2p_init', 'my_connection_types', 100 );

this will make the meta boxes to assign relationships available in your custom post edit screens.

for your single place and event pages, you can create custom templates in your theme following the WordPress template hierarchy single-{post_type}.php, so in your case single-event.php and single-place.php. you can duplicate these from the single.php template.

to list connections, we just need a bit of code within theses templates wherever we want to output the list. this would go in the place template and output connected events:

<?php
$connected = new WP_Query( array(
    'connected_type' => 'events_to_places', 
    'connected_items' => get_queried_object()
) );

echo '<p>Related events:</p>';
echo '<ul>';
while( $connected->have_posts() ) : $connected->the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;
echo '</ul>';

wp_reset_postdata();
?>

Leave a Comment

error code: 523