get_the_term_list( int $post_id, string $taxonomy, string $before = , string $sep = , string $after =  ): string|false|WP_Error

Retrieves a post’s terms as a list with specified format.

Description

Terms are linked to their respective term listing pages.

Parameters

$post_idintrequired
Post ID.
$taxonomystringrequired
Taxonomy name.
$beforestringoptional
String to use before the terms.

Default:''

$sepstringoptional
String to use between the terms.

Default:''

$afterstringoptional
String to use after the terms.

Default:''

Return

string|false|WP_Error A list of terms on success, false if there are no terms, WP_Error on failure.

Source

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;
}

Hooks

apply_filters( “term_links-{$taxonomy}”, string[] $links )

Filters the term links for a given taxonomy.

Changelog

VersionDescription
2.5.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    You can use this function with strip_tags function to print not linked term list:

    echo strip_tags( get_the_term_list( $post->ID, 'job_titles', '', ', ') )

    This prints something like this:

    Designer, Front-end Developer, Developer

  2. Skip to note 6 content

    Returning an HTML List

    Used inside the loop this outputs the terms from the styles taxonomy for a specific post as an (x)html list.

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

    This would return something like.

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

You must log in before being able to contribute a note or feedback.