函数文档

get_term_link()

💡 云策文档标注

概述

get_term_link() 函数用于生成分类法术语归档页面的永久链接。它接受术语对象、ID 或 slug 作为参数,并返回 URL 字符串或 WP_Error 对象。

关键要点

  • 参数 $term 可以是 WP_Term 对象、整数 ID 或字符串 slug,需注意类型转换以避免错误。
  • 可选参数 $taxonomy 指定分类法,默认为空。
  • 返回值:成功时返回术语归档 URL 字符串,失败时返回 WP_Error 对象。
  • 使用 is_wp_error() 检查返回值,防止打印错误对象导致 PHP 致命错误。
  • 支持多种分类法(如 category 和 post_tag),并应用相关过滤器(如 term_link、category_link)。
  • 函数内部处理了永久链接结构,包括分层分类法的 slug 替换。

代码示例

$terms = get_terms( 'species' );

echo '<ul>';

foreach ( $terms as $term ) {
    $term_link = get_term_link( $term );
    if ( is_wp_error( $term_link ) ) {
        continue;
    }
    echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
}

echo '</ul>';

注意事项

  • 传递数字参数时,应显式转换为整数(如 (int) $term_id),否则函数会将其视为 slug。
  • 避免直接打印 WP_Error 对象,使用 is_wp_error() 进行错误处理。
  • 对于对象参数,建议直接传递整个对象,而不是单独传递 slug 和分类法。

📄 原文内容

Generates a permalink for a taxonomy term archive.

Parameters

$termWP_Term|int|stringrequired
The term object, ID, or slug whose link will be retrieved.
$taxonomystringoptional
Taxonomy. Default empty.

Return

string|WP_Error URL of the taxonomy term archive on success, WP_Error if term does not exist.

More Information

  • Since the term can be an object, integer, or string, make sure that any numbers you pass in are explicitly converted to an integer (example: (int) $term_id). Otherwise the function will assume that $term is a slug instead of a term ID.
  • PHP may halt if you attempt to print an error result ("Catchable fatal error: Object of class WP_Error could not be converted to string"). You should always use is_wp_error() to check the result of this function, in case the term does not exist.

Source

function get_term_link( $term, $taxonomy = '' ) {
	global $wp_rewrite;

	if ( ! is_object( $term ) ) {
		if ( is_int( $term ) ) {
			$term = get_term( $term, $taxonomy );
		} else {
			$term = get_term_by( 'slug', $term, $taxonomy );
		}
	}

	if ( ! is_object( $term ) ) {
		$term = new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
	}

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

	$taxonomy = $term->taxonomy;

	$termlink = $wp_rewrite->get_extra_permastruct( $taxonomy );

	/**
	 * Filters the permalink structure for a term before token replacement occurs.
	 *
	 * @since 4.9.0
	 *
	 * @param string  $termlink The permalink structure for the term's taxonomy.
	 * @param WP_Term $term     The term object.
	 */
	$termlink = apply_filters( 'pre_term_link', $termlink, $term );

	$slug = $term->slug;
	$t    = get_taxonomy( $taxonomy );

	if ( empty( $termlink ) ) {
		if ( 'category' === $taxonomy ) {
			$termlink = '?cat=' . $term->term_id;
		} elseif ( $t->query_var ) {
			$termlink = "?$t->query_var=$slug";
		} else {
			$termlink = "?taxonomy=$taxonomy&term;=$slug";
		}
		$termlink = home_url( $termlink );
	} else {
		if ( ! empty( $t->rewrite['hierarchical'] ) ) {
			$hierarchical_slugs = array();
			$ancestors          = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
			foreach ( (array) $ancestors as $ancestor ) {
				$ancestor_term        = get_term( $ancestor, $taxonomy );
				$hierarchical_slugs[] = $ancestor_term->slug;
			}
			$hierarchical_slugs   = array_reverse( $hierarchical_slugs );
			$hierarchical_slugs[] = $slug;
			$termlink             = str_replace( "%$taxonomy%", implode( '/', $hierarchical_slugs ), $termlink );
		} else {
			$termlink = str_replace( "%$taxonomy%", $slug, $termlink );
		}
		$termlink = home_url( user_trailingslashit( $termlink, 'category' ) );
	}

	// Back compat filters.
	if ( 'post_tag' === $taxonomy ) {

		/**
		 * Filters the tag link.
		 *
		 * @since 2.3.0
		 * @since 2.5.0 Deprecated in favor of 'term_link' filter.
		 * @since 5.4.1 Restored (un-deprecated).
		 *
		 * @param string $termlink Tag link URL.
		 * @param int    $term_id  Term ID.
		 */
		$termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
	} elseif ( 'category' === $taxonomy ) {

		/**
		 * Filters the category link.
		 *
		 * @since 1.5.0
		 * @since 2.5.0 Deprecated in favor of 'term_link' filter.
		 * @since 5.4.1 Restored (un-deprecated).
		 *
		 * @param string $termlink Category link URL.
		 * @param int    $term_id  Term ID.
		 */
		$termlink = apply_filters( 'category_link', $termlink, $term->term_id );
	}

	/**
	 * Filters the term link.
	 *
	 * @since 2.5.0
	 *
	 * @param string  $termlink Term link URL.
	 * @param WP_Term $term     Term object.
	 * @param string  $taxonomy Taxonomy slug.
	 */
	return apply_filters( 'term_link', $termlink, $term, $taxonomy );
}

Hooks

apply_filters( ‘category_link’, string $termlink, int $term_id )

Filters the category link.

apply_filters( ‘pre_term_link’, string $termlink, WP_Term $term )

Filters the permalink structure for a term before token replacement occurs.

apply_filters( ‘tag_link’, string $termlink, int $term_id )

Filters the tag link.

apply_filters( ‘term_link’, string $termlink, WP_Term $term, string $taxonomy )

Filters the term link.

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    $terms = get_terms( 'species' );
    
    echo '<ul>';
    
    foreach ( $terms as $term ) {
    
        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );
       
        // If there was an error, continue to the next term.
        if ( is_wp_error( $term_link ) ) {
            continue;
        }
    
        // We successfully got a link. Print it out.
        echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
    }
    
    echo '</ul>';

  2. Skip to note 6 content

    /* check term and error */

    $dr_terms = get_terms( 'your_term_name' );
    if ( ! is_wp_error( $dr_terms ) && ! empty( $dr_terms ) ) {
        echo '<ul class="your-class-name">';
        foreach ( $dr_terms as $dr_term ) {
            echo '<li><a href="' . get_term_link( $dr_term->slug, 'your_term_name' ) . '">' . __( $term->name ) . '</a></li>';
        }
        echo '</ul>';
    }