1 Answer
1

Yes, what you are planning is one of the easier ways to accomplish a relationship between post where the user defines the relationship through a shared value.

There are several ways you could make this work but since WordPress doesn't give you an easy single query way to do it easily I decided to subclass WP_Query named Place_Trip_Query for you so that you can accomplish this with one SQL query. Normally I like to avoid SQL queries but this is an area where I don't think it can be helped.

The class uses the 'posts_where' and 'posts_join' hooks to let us modify the SQL query to associate the Place and Trip posts that have been tagged by the same Location term for a given place name (the query uses a "starts with" query so "Grand" will match "Grand Canyon").

You can place this code in your theme's functions.php file or in a PHP file of a plugin you might be writing:

You can use this class just like you might use the WP_Query with these args. Here's a standalone file you could call test.php and drop in the root of your website to test the class and show you how it works:

And for others reading this who would like to test this here's some code to create the Places and Trips custom post types and the Location custom taxonomy. You can also place this in your theme's functions.php file:

I don't see the difference between your code and the built-in get_posts( array( 'post_type' => 'trip', 'taxonomy' => 'location', 'term' => 'grand-canyon' ) ). Can you explain what your code does extra, or why get_posts() would not work?
–
Jan FabryDec 31 '10 at 15:35

@Jan Fabry - That's what I almost wrote, then I realized what he was asking. Grand Canyon is not a term, it's a custom post type where post_type='place' and it is matched to custom post types of post_type='trip' by both having the Location term 'Arizona'. Does that explain?
–
MikeSchinkelDec 31 '10 at 18:26

OK, I assumed this would be used on a single-place.php file, so while displaying the Grand Canyon post. Then you can ask for the location trip term that post is attached to, and use these to do your get_posts query. Of course, I should not have used grand-canyon as the term, but arizona.
–
Jan FabryJan 1 '11 at 10:36

@Jan Fabry - Yes, I think that could work too albeit with more queries to the database.
–
MikeSchinkelJan 1 '11 at 21:06