Support » Developing with WordPress » Show Highest and Lowest Taxonomy term as a link

  • Resolved helmrict

    (@helmrict)


    I have from one to three levels of hierarchical taxonomies associated to a post through a related post (i.e. showing an event post, calling data from the venue post). I am able to get all taxonomies as links using this:

    $venue = tribe_get_venue_id();
    				 echo the_terms( $venue, 'location', 'Location: ', ', ', ' ' ); 

    and can get to showing the parent using this (although its not a link),

    $terms = get_terms('location');
    foreach ($terms as $term) {
    
    if($term->parent == 0 ){
    echo $term->name;
    }}

    What I’d like to do is show the parent (as a link) and the grandchild, if exists. If no grandchild, show the child, if exists. And if only a parent then that is all to be displayed.

    I’ve searched around and have been unable to find a recent solution to the primary challenges of (#1) show only parent taxonomy from a different post, and (#2) show furthest down child taxonomy if one exists.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    This topic is marked as resolved, which is great if that is the case. You may then ignore this post, it’s mainly to take your resolved topic off the “No Replies” list. If the resolution is a mistake, let me know. I think I can help you.

    Thread Starter helmrict

    (@helmrict)

    Thanks @bcworkz, I marked it as resolved because after working on this for a while, I cobbled some code together to get results… It seems to work but is not efficient and contains some excess calls. Would love some guidance on improvemwnt Here is what I’ve done…
    $venueloc= tribe_get_venue_id();

    <?php   // shouldn't need down to next comment
    $terms = get_the_terms( $venueloc, 'neighborhood' );
    // Loop over each item since it's an array
    if ( $terms != null ){
    foreach( $terms as $term ) {
    $term_link = get_term_link( $term, 'neighborhood' );
     } } ?>
     
    <!--- Here ---->
     <?php $parentsneighborhood ="";
    foreach((get_the_category($garbage)) as $category) {
    if ($category->category_parent == 0) {
    $parentsneighborhood .= ' <a href="' . get_category_link($category->cat_ID) . '" title="' . $category->name . '">' . $category->name . '</a>, ';
    }
    }
    echo substr($parentsneighborhood,0,-2); 
    
    // get all product cats for the current post
    $categories = get_the_terms( $venueloc, 'neighborhood' ); 
    
    // wrapper to hide any errors from top level categories or products without category
    if ( $categories && ! is_wp_error( $category ) ) : 
    
        // loop through each cat
        foreach($categories as $category) :
          // get the children (if any) of the current cat
    	  $children = get_categories( array ('taxonomy' => 'neighborhood', 'parent' => $category->term_id ));
    	  $term_link = get_term_link( $term );
    
          if ( count($children) == 0 ) {
              // if no children, then echo the category name.
    		  echo '<a href="' . esc_url( $term_link ) . '">' . ", ". $term->name . '</a>';
          }
        endforeach;
    endif;
    ?>

    My taxonomy contains parent, child, grandchild. This code is providing the desired output of:
    -PARENT (if no child or grandchild)
    -PARENT, CHILD (if no grandchild)
    -PARENT, GRANDCHILD (if all three are associated)

    Moderator bcworkz

    (@bcworkz)

    Maybe it makes sense to you, but using the label “category” for custom taxonomy terms is confusing to others who might be reading your code. Even if you will be the only one to ever read the code, it could be confusing to you as well a year later when it comes time to modify the code. Even though many category functions accept custom taxonomies, there generally are equivalent generic term functions that would be less confusing. Follow through with your variable names by not using category terminology. Use terminology that relates to the taxonomy, or at least use the abstract “taxonomy” and “term” labels.

    The first get_term_link() where you foreach $terms is problematic unless you only want the last link of whatever terms are assigned, as the previous links are discarded with each iteration. You generally would either push all the links into an array or concatenate them together in these situations. Or immediately echo out within the loop.

    In this line:
    foreach((get_the_category($garbage)) as $category)
    I’m not sure calling a function as the foreach source is good practice. I think get_the_category() is called on every iteration, though I may be wrong. I’d assign the terms to a variable before looping through them to ensure the function is only called once. Such constructs usually read a little better too. And now we are using actual categories here? Isn’t this all supposed to be for the neighborhood taxonomy?

    Outputting lists of things separated by characters always introduces the issue of trailing separators that need to be dealt with. Using substr() like you do is fine, but for the sake of discussion, another nice approach is to collect the list items into an array, then implode() the array. Then if you decide to change the length of the “glue” string, you don’t need to coordinate it anywhere else, just change the glue string and PHP handles the rest. Something like this:

    $neighborhood = [];
    $neighbors = wp_get_post_terms( get_the_ID(), 'neighborhood');
    foreach( $neighbors as $neighbor ) {
      $neighborhood[] = $neighbor->term_name;
    }
    echo implode(' | ', $neighborhood );

    This isn’t intended to replace anything you have, it’s just an example. You could actually get wp_get_post_terms to only return term_names in an array, which can then be immediately imploded. No need for a foreach structure.

    You’ve covered what to do when there is no parent term, but I don’t see anything to handle parent terms when they exist. There ought to be an else conditional for if ($category->category_parent == 0) to output parent links.

    Similar comments for getting child terms. Avoid category specific functions and names in favor of generic term functions and variable names that relate to the taxonomy. You’ve dealt with the no children condition, but not when children occur. I’m assuming it’s beyond the snippet you posted, but the same last link issue exists that I first mentioned (paragraph 2). Only the last term’s children will be available outside the loop. Previous term children are overwritten.

    Thread Starter helmrict

    (@helmrict)

    Thank you for the thorough analysis of my code, very kind of you! I will work with it to see if I can incorporate your suggestions and still get the results I’m after. A great learning opportunity for me, thanks again.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Show Highest and Lowest Taxonomy term as a link’ is closed to new replies.