Function and usage of get_term_link() in wordpress


Answers ( 1 )


    The get_term_link() function in WordPress is used to generate a permalink (URL) for a taxonomy term archive. This function is particularly useful when you want to provide a link to a specific category, tag, or custom taxonomy term on your website. Here's a detailed explanation of its usage:

    Function Signature

    get_term_link( WP_Term|int|string $term, string $taxonomy = '' ): string|WP_Error


    1. $term (WP_Term|int|string) [required]:

      • This is the term for which you want to generate the URL.
      • It can be provided in three forms:
        • As a WP_Term object.
        • As an integer representing the term ID.
        • As a string representing the term slug.
    2. $taxonomy (string) [optional]:

      • This specifies the taxonomy of the term.
      • It is an optional parameter. If omitted, WordPress will try to identify the taxonomy automatically.
      • Common examples of taxonomy include 'category', 'post_tag', or any custom taxonomy name.

    Return Value

    • The function returns either of the two:
      • String: The URL of the taxonomy term archive, if the term exists and is valid.
      • WP_Error: An error object if the term does not exist or if there are other problems in generating the link.

    Sample Usage

    Here's how you might use get_term_link() in a WordPress template:

    // Assuming you have a term ID
    $term_id = 4; // Example term ID
    $link = get_term_link( $term_id );
    if ( !is_wp_error( $link ) ) {
        echo '<a href="' . esc_url( $link ) . '">Visit the term archive</a>';
    } else {
        // Handle the error
        echo 'Error: ' . $link->get_error_message();

    In this example:

    • We're trying to get the link for a term with ID 4.
    • We check if the returned value is not a WP_Error.
    • If it's a valid URL, we create an anchor tag to the term archive.
    • If there's an error, we handle it by displaying the error message.


    • It's important to always check if get_term_link() returns an error to avoid issues on your site.
    • Escaping the URL using esc_url() is a good practice for security.

    This function is a part of WordPress's template tags, allowing theme developers to create dynamic links to various content types on a WordPress site.

Leave an answer