wordpress taxonomy explained by vlad madejczyk

WordPress taxonomy explained, tables wp_terms, wp_term_taxonomy and wp_term_relationships

WordPress taxonomy is one of the main reasons for which WordPress is so popular CMS framework not only for blogs but for e-commerce too. Sorting out online shop’s products in different categories is one of examples taxonomy usage. Taxonomy as such means classification of things, in fact – classification of whatever.

In WordPress database exist three tables responsible for sorting out taxonomy relationships:

  1. wp_terms
  2. wp_term_taxonomy
  3. wp_term_relationships

At start there is a post. But, post can belong to some category, or can have some useful tags, or can be a product in online shop etc. – all this we call taxonomies: be it category, post-tag or other method of classification of our posts/pages.

The most important thing to understand how taxonomy in WordPress works is to show relationship between the main WordPress table: wp_posts and the above mentioned three tables. So, let’s ask how to find all taxonomies a post/page belongs to? To do it, we go to:

      • table wp_posts where we get post id (column ID
      • with post id we go to table wp_term_relationships, where object_id is the same as our post id. In wp_term_relationships we can find many entries for our post id, which means, that our post can belong to many taxonomies. Let’s assume, that we found two entries for object_id and we got term_taxonomy_id=45 and term_taxonomy_id=46.
      • with term_taxonomy_id=45 and term_taxonomy_id=46 we go to table wp_term_taxonomy where – not by accident – we have column named term_taxonomy. There we find in column “taxonomy” that – for instance – number 45 has taxonomy=category and 46 has taxonomy=post_tag. It means, that our post belongs to some category it belongs to and has some post tag, but we still don’t know to which category and what tag is involved. To find to what category post belongs, and what tag was used for this post, we read from the table wp_term_taxonomy values under column term_id for two our numbers 45 and 46. Let’s assume, that for term_taxonomy_id=45 we got term_id=34 and another one we got term_id=39.

Now, we go to table wp_terms , where we find column “term_id” for our numbers, and in column “name” we can read exact name for post category – for instance – for term_id=39 we got “wordpress for beginners” and for term_id=39 we got post tag – for instance – “wp_config file”.

As we can see, there are 4 steps needed to find very useful information about a post. Because taxonomy is so important, in WordPress exists special function which helps to find all taxonomies for a given post: wp_get_post_terms.

So, to cut it short: start with post id from table wp_posts, go to table wp_term_relationships, after that to table wp_term_taxonomy and finally to table wp_terms.