Linking Two Post Types

and thanks in advance for your help.

I’ve done some searching, and this question has been answered a couple of times with reference to the “posts 2 posts” plugin, but the documentation on that is very “coder-centric” — I am able to and comfortable getting my hands dirty, but I do require better Step-by-Step documentation than what is available there. 🙂

Read More

Here’s what I need. I am using gPress to generate “Places” using their custom post type. This is working amazingly well. What I need to do is to be able to add “Events” to a Place. I can use a custom post type to capture all event details, but then I’d like to be able to attach Events to a specific Place, and vice-versa. If someone was viewing the Event post, there would be a somewhat easy way to also pull the Place information related to the Event.

Any suggestions are appreciated!

Related posts

Leave a Reply

1 comment

  1. 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();
    ?>