WordPress: how to get data from taxonomy?

When we develop a plugin for WordPress, one of the most common task, is to get data from the database. For the main objects, such as pages, posts, categories of posts, the WordPress’ API provides us a set of simple functions, allowing us to get what we want.
For other objects, functions are rare or less flexible to use. So, we often quickly decide to query the database directly, what is not recommended. I just discover two functions to get objects from the WordPress taxonomy, without querying the database directly.

Initialy I faced to two questions:

  • How to get the list of categories of links?
  • How to get the list of tags of specified list of posts?

In the both cases, I searched a function to avoid me to query the database directly. At the end, my search was failed, and I wrote SQL queries to get the data.

Some days after, I finally found two functions that give me responses to my questions. These two functions are wp_get_object_terms, and get_terms.

For wp_get_object_terms, the syntax is the following:
wp_get_object_terms( $object_id, $taxonomies, $args = array()))

With

  • $object_id (int or array), ID or list of ID,
  • $taxonomies (string or array), a taxonomy or a list of taxonomies. Available values depends on the recorded taxonomies. In the standard case, the list is the following:
    • category,
    • link_category
    • post_tag
  • $args (string or array), parameters defining the list we want (fields, order, …). List of possible values:
    • orderby, default value: name, possible values: count, name, slug, term_group, term_order,
    • order, default value: asc,
    • fields, list of fields, default value:all, possible values: all, ids, names, all_with_object_id,

For the function get_terms:
&get_terms($taxonomies, $args = array()))

With

  • $taxonomies (string or array), a taxonomy or a list of taxonomies. Available values depends on the recorded taxonomies. In the standard case, the list is the following:
    • category,
    • link_category
    • post_tag
  • $args (string or array), parameters defining the list we want (fields, order, …). List of possible values:
    • orderby, default value: name, possible values: count, name, slug, term_group, term_order,
    • order, default value: asc,
    • fields, list of fields, default value:all, possible values: all, ids, names,
    • hide_empty, default value: TRUE. Don’t return anything if no term is recorded in the specified taxonomy,
    • exclude, include, allow to specify terms, or list of excluded terms,
    • number maximum of terms to return (all terms by default),
    • slug allow to specify the text ID of the term we are searching,
    • Other parameters: parent, hierarchical, get, name__like, pad_counts, offset, search

If we try to answer to the two initial questions:

Get all the categories of links

With a direct SQL query to the database, the code is

global $wpdb;
$results = $wpdb->get_results('SELECT ter.term_id,ter.name FROM '.$wpdb->term_taxonomy.' AS tax, '.$wpdb->terms.' AS ter WHERE tax.taxonomy="link_category" AND ter.term_id=tax.term_id');
if ($results) {
   foreach ($results as $result) {
      echo $result->term_id.' '.$result->name.'
';
   }
}

By using get_terms, the code becomes:

$results = get_terms('link_category');
if ($results) {
   foreach ($results as $result) {
      echo $result->term_id.' '.$result->name.'
';
   }
}

Get all tags of a set of posts
The following example collects all the tags of the currently displayed list of posts.

global $posts;
foreach ($posts as $post_values) {
   $array_id[] = $post_values->ID;
}
$list_id = implode('","', $array_id);
$sql_query = 'SELECT DISTINCT name	'.
             'FROM '.$wpdb->term_relationships.' AS rel,'.
                     $wpdb->term_taxonomy.' AS tax,'.
                     $wpdb->terms.' AS ter '.
             'WHERE tax. taxonomy = "post_tag" '.
                    'AND rel.object_id IN ("'. $list_id.'") '.
                    'AND rel.term_taxonomy_id = tax.term_taxonomy_id '.
                    'AND tax.term_id = ter.term_id ORDER BY tax.count';
$results = $wpdb->get_results($sql_query);
If ($results) {
    echo 'Tags: '.implode(', ', $results);
}

With the function wp_get_object_terms, the code is the following:

global $posts;
foreach ($posts as $post_values) {
   $array_id[] = $post_values->ID;
}
$results = wp_get_object_terms($array_id, 'post_tag', 'fields=names' );
if ($results) {
    echo 'Tags: '.implode(', ', $results);
}

Conclusion

My initial searches was incomplete :- :$ . In fact, if we think a little bit carefully, it’s clear that WordPress has necessarily all the required functions to get data from its database, otherwise it wouldn’t work very well !
So, we have to persist in order to find the right function. Read the source code of WordPress can be usefull for that.
The two functions introduced in this post, allow us to get all the terms of WordPress’s taxonomies.