get_term_link()
Gets the URL for the archive page of a term (taxonomy item). The same as the link to the category page.
The function returns a permanent link to the page of a particular taxonomy element (term).
The function is useful when a custom taxonomy is created and you need to get a link to any element of this custom taxonomy.
If you pass a term ID to the $term parameter, make sure that you pass a number (int) type. For example, if you pass $term_id variable, process it like so (int) $trem_id. If the variable contains a number string '5', the function will look for a term with a slug 5, and not term with ID 5 - this can cause an incomprehensible error.
Hooks from the function
Returns
String|WP_Error.
String- A URL to the taxonomy element.- WP_Error - if the element does not exist.
Usage
get_term_link( $term, $taxonomy );
- $term(string/integer/object/WP_Term) (required)
- ID/object/name of the taxonomy element whose link should be retrieved.
- $taxonomy(string)
Name of the taxonomy whose element link should be retrieved.
The taxonomy is required if the slug is provided:
get_term_link( 'term-slug', 'category' );
You can omit it if you pass an ID (integer) or WP_Term:
get_term_link( (int) $term_id ); get_term_link( $wp_term );
The ID must be cast to
int, otherwise the string will be treated as a slug.Default: ''
Examples
#1 Display a link to the archive page of the taxonomy item
5 is ID of the taxonomy item, tax_name is the name of the taxonomy.
$term_id = 5; $term_link = get_term_link( $term_id, 'tax_name' ); echo '<a href="'. $term_link .'">link to section with ID '. $term_id .'</a>';
#2 Display the link of the term by its name
$term_slug = 'other'; // you need to pass a slug $term_link = get_term_link( $term_slug, 'tax_name' ); echo '<a href="'. $term_link .'">link to section '. $term_slug .'</a>';
#3 $term_id must be an int type if it is an ID (numeric)...
Suppose that $term_id is already known and passed as a string, then it must be converted to an integer, otherwise, the function will interpret it as a term slug, not as a term ID.
$term_id = '5'; $term_link = get_term_link( (int) $term_id, 'tax_name' ); echo '<a href="'. $term_link .'">link to section with ID '. $term_id .'</a>';
Notes
- Global. WP_Rewrite.
$wp_rewriteWordPress rewrite component.
Changelog
| Since 2.5.0 | Introduced. |