Themergency

Setup Post Relationships In Your Plugins With Posts 2 Posts

In a plugin I recently wrote, I needed a nice way to associate custom post types to other custom post types created within the plugin. I have previously done something similar using post meta and taxonomies, but I have since found a better way to do this. I now use the brilliant Posts 2 Posts plugin by Scribu.

What is Posts 2 Posts?

Quoted from the WP.org repo, Posts 2 Posts is a way to create “Efficient many-to-many connections between posts, pages, custom post types, users“. So in a nutshell, it lets you setup relationships between your post types (and users) and provides a very intuitive UI, so that your users (and yourself) can easily manage the relationships. Just spend a couple minutes going through the documentation to see how powerful this plugin really is!

A simple example connection

p2p_register_connection_type( array( 
	'name' => 'friendship',
	'from' => 'person',
	'to' => 'person',
	'reciprocal' => true,
	'title' => 'Friends with'
) );

How do I include it in my plugins?

Well, you can’t physically include the Posts 2 Posts plugin within your own plugin, but you can make your plugin depend on it. I have written a small helper class that you can drop directly into your plugins “includes” folder and then intialize with a few lines of code:

require_once( plugin_dir_path( __FILE__ ) . 'includes/p2p.php' );
new myfirstplugin_post_relationships('My First Plugin', 'myfirstplugin');

You will need to change the name of the helper class to something more appropriate. And obviously, you will need to edit the actual Posts 2 Posts connections to be specific to your plugin.

Also note that you need to pass in your plugin name and slug to the constructor when you instantiate the class. These are used for the admin notice and localisation of strings.

What it gives you out of the box

  • Checks that the Posts 2 Posts plugin is activated and running the latest version.
  • Displays a friendly admin notice if the above check is false, with a quick link to install it from within the backend.
  • A single place to create connections using Posts 2 Posts within your plugin. (If you ever change them in future or remove the dependency altogether, it will be easy to manage)

Give posts relationships a chance!

The fact that Posts 2 Posts is not a part of WordPress Code still baffles my mind. Surely a plugin like this opens so many doors to developers? But in the mean time, while we wait, use the helper class and add post relationships to your plugin today!