0

Im currently displaying the custom taxonomy term for my post on a single-resources.php page. However I need it to link to the taxonomy category page and not the link of the page.

This is what I currently have:

<?php
    $term_list = wp_get_post_terms($post->ID, 'resourcecategory', array("fields" => "all"));
    foreach($term_list as $term_single) {
            echo '<a class="icon-hv-link" href="' . esc_url( $term_link ) . '"><i class="icon-left-open-big"></i><span>' . $term_single->name . '</span></a>';
    }
?>

I was previously doing this which does work however its displaying every taxonomy term rather than the one specific to the post, so it doesn't work :(

<?php $terms = get_terms( 'resourcecategory' );
        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
             foreach ( $terms as $term ) {
               echo '<a class="icon-hv-link" href="' . esc_url( $term_link ) . '"><i class="icon-left-open-big"></i><span>' . $term->name . '</span></a>'; 
             }
         }?>

Does anyone have any idea on someway to combine the two?

codewario
  • 19,553
  • 20
  • 90
  • 159
probablybest
  • 1,403
  • 2
  • 24
  • 47

1 Answers1

1

For anyone else having an issue with this I managed to achieve what I was after with the following code:

  <?php
    $terms = get_the_terms( $post->ID, 'resourcecategory');
    foreach($terms as $term) {
        echo '<a class="icon-hv-link" href="' . get_term_link($term) . '"><i class="icon-left-open-big"></i><span>' . $term->name . '</span></a>';
    }
  ?>

You need to use get_the_terms instead of get_terms. As mentioned in the comments, dont use wp_get_post_terms as this causes unnecessary calls to the database

probablybest
  • 1,403
  • 2
  • 24
  • 47
  • 1
    Use `get_the_terms()`. `wp_get_post_terms()` is not cached, so you are making unnecessary db calls. `get_the_terms()` is cached, so you can call it a hundred times and it would not cost you any db calls. ;-) – Pieter Goosen Dec 09 '15 at 10:46
  • BTW +1 for passing the term object to `get_term_link()`. This safes on unnecessary db calls. If you only pass the term ID, the db needs to be queried to get the term object to build the link – Pieter Goosen Dec 09 '15 at 10:48
  • 1
    Thank you for the feedback. I have updated my answer :) – probablybest Dec 09 '15 at 11:14