WordPress at Your Fingertips

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
Hooks from the function

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

#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>,
...

Changelog

Since 2.5.0 Introduced.

Code of get_the_term_list() WP 5.8.1

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 filter name, `$taxonomy`, refers
	 * to the taxonomy slug.
	 *
	 * @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;
}

List (wp_list)

Term (taxonomies terms)

For posts

Taxonomies (category, tag)

vladlu 100vlad.lu
Editors: Kama 101
No comments
    Log In