get_the_term_list()WP 2.5.0

Displays a list of links to taxonomy elements (e.g. tags) related to a specified post.

The function can be used within the WordPress Loop, for example, to display each post's tags, separated by commas.

Instead of ordinary WordPress tags, you also can output elements of any custom taxonomy.

1 time — 0.004471 sec (very slow) | 50000 times — 5.31 sec (fast) | PHP 7.1.2, WP 4.7.3

Return

String|false|WP_Error.

  • string — a list of taxonomy elements as links to the corresponding archive pages.

  • false — if no taxonomy elements were retrieved.

  • WP_Error — if it failed to get a link to any of the received taxonomy elements. This is a rare case and is related to a bug in the WordPress structure.

Usage

get_the_term_list( $post_id, $taxonomy, $before, $sep, $after );
$post_id(int) (required)
Post ID.
$taxonomy(string) (required)
Taxonomy name.
$before(string)
String to use before the terms.
Default: ''
$sep(string)
String to use between the terms.
Default: ''
$after(string)
String to use after the terms.
Default: ''

Examples

0

#1 Display List of taxonomy items

You can use code like this inside the WordPress Loop to display "heroes" taxonomy elements (tags) for each post:

<?php echo get_the_term_list( $post->ID, 'people', 'Celebrities: ', ',', '' ); ?>

The result will be roughly the following list for each post:

Celebrities:
<a href="person1">Eminem</a>,
<a href="person2">Dwayne Johnson</a>,
...
0

#2 Get a UL list

This example shows how to output the elements of styles taxonomy as a bulleted list (non-numbered) list.

echo get_the_term_list( $post->ID, 'styles', '<ul class="styles"><li>', ',</li><li>', '</li></ul>' );

Get this:

<ul class="styles">
	<li><a href="person1">Style 1</a>,</li>
	<li><a href="person2">Style 2</a></li>
</ul>

Changelog

Since 2.5.0 Introduced.

get_the_term_list() code WP 6.5.2

function get_the_term_list( $post_id, $taxonomy, $before = '', $sep = '', $after = '' ) {
	$terms = get_the_terms( $post_id, $taxonomy );

	if ( is_wp_error( $terms ) ) {
		return $terms;
	}

	if ( empty( $terms ) ) {
		return false;
	}

	$links = array();

	foreach ( $terms as $term ) {
		$link = get_term_link( $term, $taxonomy );
		if ( is_wp_error( $link ) ) {
			return $link;
		}
		$links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
	}

	/**
	 * Filters the term links for a given taxonomy.
	 *
	 * The dynamic portion of the hook name, `$taxonomy`, refers
	 * to the taxonomy slug.
	 *
	 * Possible hook names include:
	 *
	 *  - `term_links-category`
	 *  - `term_links-post_tag`
	 *  - `term_links-post_format`
	 *
	 * @since 2.5.0
	 *
	 * @param string[] $links An array of term links.
	 */
	$term_links = apply_filters( "term_links-{$taxonomy}", $links );  // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

	return $before . implode( $sep, $term_links ) . $after;
}