Search code examples
wordpresstaxonomy

Get the URL of the taxonomy's category in WordPress


I need help to retrieve the URL of the category in a taxonomy. I have a taxonomy called 'leagues' and it is displaying the image and the name of the category, I need to add the link so that people can go to that category when clicking the name. Here is the code I have below:

<ul>
    <?php
    $taxonomies = get_terms(array(
        'taxonomy'     => 'leagues',
        'orderby'      => 'name',
        'show_count'   => 0,
        'pad_counts'   => 0,
        'hierarchical' => 1,
    ));

    foreach ($taxonomies as $category) {
        if ($category->parent == 0) {
            $cat_id = $category->term_id;
            $logos = get_field('logo', 'term_' . $cat_id);
            //for image return format: Image Array
            $logo = $logos['sizes']['thumbnail']; //default WP image sizes: thumbnail, medium, large
            if ($logo) {
                echo '<li>';
                echo '<img src="';
                echo $logo;
                echo '" class="w-25 mr-4">';
                echo '<a href="';
                echo '#';
                echo '">';
                echo $category->name;
                echo '</a>';
                echo '</li>';
            }
        }
    }
    ?>
</ul>

Solution

  • Since you are getting the term object in your loop ( $category ), you can use get_term_link() https://developer.wordpress.org/reference/functions/get_term_link/

    get_term_link( $category->term_id )

    echo '<a href="';
    echo get_term_link( $category->term_id );
    echo '">';