get_term_parents_list() WordPress Function

The get_term_parents_list() function is used to get a list of the parent terms for a given term. This can be useful for creating a breadcrumb trail for a term. The function takes two parameters: the term ID and the taxonomy. The term ID is used to identify the term, and the taxonomy is used to specify which taxonomy the term belongs to. If successful, the function will return an array of the parent terms. If there are no parent terms, or if the term does not exist, the function will return an empty array.

get_term_parents_list( int $term_id, string $taxonomy, string|array $args = array() ) #

Retrieves term parents with separator.


Parameters

$term_id

(int)(Required)Term ID.

$taxonomy

(string)(Required)Taxonomy name.

$args

(string|array)(Optional)Array of optional arguments.

  • 'format'
    (string) Use term names or slugs for display. Accepts 'name' or 'slug'. Default 'name'.
  • 'separator'
    (string) Separator for between the terms. Default '/'.
  • 'link'
    (bool) Whether to format as a link. Default true.
  • 'inclusive'
    (bool) Include the term to get the parents for. Default true.

Default value: array()


Top ↑

Return

(string|WP_Error) A list of term parents on success, WP_Error or empty string on failure.


Top ↑

Source

File: wp-includes/category-template.php

function get_term_parents_list( $term_id, $taxonomy, $args = array() ) {
	$list = '';
	$term = get_term( $term_id, $taxonomy );

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

	if ( ! $term ) {
		return $list;
	}

	$term_id = $term->term_id;

	$defaults = array(
		'format'    => 'name',
		'separator' => '/',
		'link'      => true,
		'inclusive' => true,
	);

	$args = wp_parse_args( $args, $defaults );

	foreach ( array( 'link', 'inclusive' ) as $bool ) {
		$args[ $bool ] = wp_validate_boolean( $args[ $bool ] );
	}

	$parents = get_ancestors( $term_id, $taxonomy, 'taxonomy' );

	if ( $args['inclusive'] ) {
		array_unshift( $parents, $term_id );
	}

	foreach ( array_reverse( $parents ) as $term_id ) {
		$parent = get_term( $term_id, $taxonomy );
		$name   = ( 'slug' === $args['format'] ) ? $parent->slug : $parent->name;

		if ( $args['link'] ) {
			$list .= '<a href="' . esc_url( get_term_link( $parent->term_id, $taxonomy ) ) . '">' . $name . '</a>' . $args['separator'];
		} else {
			$list .= $name . $args['separator'];
		}
	}

	return $list;
}


Top ↑

Changelog

Changelog
VersionDescription
4.8.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.