WordPress content relationships

In my web development practice, one of the most important missing features in current WordPress is the capacity to define relationships between content objects ā€“ the kind of situation the Posts 2 Posts plugin has been solving since 2010.

While thinking about strategies of implementing relationships in an upcoming project, I have been wondering: how does WP handle existing relationships between objects ?

Here are some of the object relationships we already have in WP core:

  • Comments, that are linked to posts
  • Child-pages, that are linked to a parent page
  • Attachments, that are attached to posts
  • Featured images, that are attached to posts

Let’s have a look at the inner workings:

Comments

Comments are a special type of content: they are stored in the "wp_comments" table in the database.
There’s a "comment_post_ID" column, that contains the ID of the related Post.

It’s a comment -> post (child -> parent) relationship.

Child-pages

Child pages, just as pages and posts, are stored the "wp_posts" table.
For child pages, the "post_parent" column holds the parent ID.

It’s a child -> parent relationship.

Attachments

Attachments are also stored in the the "wp_posts" table.
Just as for child-pages, the ID of the parent post (where the file was uploaded to) is stored in the "post_parent" field.

It’s a child -> parent relationship.

Featured images

If we define a “featured image” (ID 7537) for a page (ID 8089), what changes in the database?

The change occurs in the “wp_postmeta” table, the entry looks like this:

meta_id: 4953
post_id: 8089
meta_key: _thumbnail_id
meta_value: 7537

Basically, when defining the “featured image”, a custom field is created, that stores the ID of the image, under the _thumbnail_id field.

It’s a parent -> child relationship.


Conclusion

In WP core, there are two methods of registering content relationships.

  • “post_parent” field : for simple relationships: the “post_parent” field of the wp_posts table can store the parent ID.
  • “a custom field” : For more complicated cases, a custom field can store the ID of the linked item.