My setup is as follows

I hava a custom post type named ‘events’ and a custom post type named ‘genres’ which I link with scribu’s Posts2Posts plugin. Each event can have multiple genres linked to it.

What I would like to do

On an event page, I’d like to show other, related, events based on the genres the current event has.

What I think I should do

  1. Run a query which gets all the genres IDs of the current event
  2. Pass these IDs in a second query which finds all the events which have one or more of these genres linked to it

I have a p2p query which I’d like to output all events which have one AND / OR more of the given genres in connected_items. I pass them as an array, just like in the documentation.

To illustrate my outcome, lets say that

  • event1 has linked genres with post ids 1240, 1241, 1242 and 1250
  • event2 has linked genres with post ids 1240, 1241 and 1260
  • event3 has linked genres with post ids 1241 and 1242

In the first query I get all the genre IDs, this works.

The second query which gets all the events with the given genres (I pass them as an array):

$args = array(
        'connected_type' => 'genres_to_events',
        'connected_items' => array(1240,1241,1242),
        'post_status' => 'publish',
        'posts_per_page' => -1,
    );

$query = new WP_Query($args);

The thing is that the output checks for each connection in the array, and therefor the output of the query is:

  • event1
  • event1
  • event1
  • event2
  • event2
  • event3
  • event3

But I’d like to output each event once based on if it has one or more of the genres connected to it. I don’t think this is explained in the documentation, any ideas?

2 Answers
2

Ah I think I understand. I think what you should do with your first loop, is get the connected genres as you say. Then you wish to get all events that are related to those, so you should gather only the IDs (collect them in one array) in a loop, and then use array_unique() to remove all the duplicates. Use this clean array in a loop to get just those posts then. Make sense?

So, something like this might work:

$args = array(
        'connected_type' => 'genres_to_events',
        'connected_items' => array(1240,1241,1242),
        'post_status' => 'publish',
        'posts_per_page' => -1,
    );

$query = new WP_Query($args);

$connected_out = array();

while($query->have_posts()) : $query->the_post();
    $connected_out[] = $post->ID;
endwhile;

$connected_out = array_unique($connected_out);
wp_reset_query();

$args = array(
    'post__in' => $connected_out;
);

$query = new WP_Query($args);
// go!

Leave a Reply

Your email address will not be published. Required fields are marked *