Skip to content
Advertisement

Get taxonomy link

I’m trying to create links of the taxonomies in WordPress so that when you click one it will take you to the WordPress page the lists all posts of that taxonomy, but I don’t quite get it right. How would you do it?

Current code:

    <?php
    $post_type = get_post_type(get_the_ID());   
    $taxonomies = get_object_taxonomies($post_type);   
    $taxonomy_names = wp_get_object_terms(get_the_ID(), $taxonomies,  array("fields" => "names")); 
    if(!empty($taxonomy_names)) :
      foreach($taxonomy_names as $tax_name) : ?>              
        <h2 class="text-lg"><?php echo $tax_name; ?> </h2>
        //planning to have the link here (<a href="?">?</a>)
      <?php endforeach;
    endif;
  ?>

All help is appreciated!

Advertisement

Answer

Try this code it’s working fine from my side

<?php
    $post_type = get_post_type(get_the_ID());   
    $taxonomies = get_object_taxonomies($post_type);   
    $taxonomy_names = wp_get_object_terms(get_the_ID(), $taxonomies);

    if(!empty($taxonomy_names)) :
        foreach($taxonomy_names as $tax_name) : 
            ?> 
            <h2 class="text-lg"><?php echo $tax_name->name; ?> </h2>         
            <a href="<?php echo get_term_link($tax_name->term_id); ?>">texonomy link </a>
            <?php
        endforeach;
    endif;
?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement