WordPress terms can be ordered hierarchical, but there is no built-in easy way to output them in hierarchical order.

Say, for example, that you have this structure of terms for the “category” taxonomy:

-- Films
 -- Comedy
 -- -- '70
 -- -- '90
 -- -- modern
 -- Historical
 -- Science Fiction

And for a post that belogs to Film, Comedy and modern you want to print categories like so:

Posted in: Films, Comedy, modern.

Functions like wp_get_post_terms() or wp_get_object_terms() doesn’t help us if you expect this result. They, by default, output the terms ordered by name, and get_the_term_list() uses the same default, so the result will be like:

Posted in: Comedy, Films, modern.

Other available order settings (term_id, term_group, term_order) doesn’t produce our desidered output either.

WBF Approach

WBF, on the other hand, has a very quick utility function to do just that (and something more): \WBF\components\utils\Terms::get_post_terms_hierarchical()

The function accepts 5 parameters:

$post_id

(int) (required)

The post ID

$taxonomy

(string) (required)

The taxonomy name

$args

(array) (optional) Default: []

The arguments that will be fetched (internally) to wp_get_post_terms.

$flatten

(bool) (optional) Default: True

If TRUE, the function returns a one-dimensional array of terms; if FALSE terms are nested accordingly to their parent so the function returns a multidimensional array where the first level is composed of top-level terms only.

$convert_to_wp_term

(bool) (optional) Default: False

If TRUE, and $flatten is also TRUE, the resulting array will be an array of WP_Term, otherwise it will be an array of stdClass.

The function automatically fills the array with missing parents (for example, if our post is assigned to Films and modern but not to Comedy) and label these terms with a property called not_assigned with a value of True.

Waboot Approach

Waboot implements this WBF function and make available a get_the_term_list() equivalent called \Waboot\template_tags\get_the_terms_list_hierarchical() that can easily display the desidered ordered list of terms.

The function accepts the same parameters as get_the_term_list()$id, $taxonomy, $before, $sep, and $after, with the addition of $linked parameter.

$linked

(bool) (optional) Default: True

If TRUE, the terms will be linked to their archive page.

Leave a Reply

Your email address will not be published. Required fields are marked *