WordPress.org

Ready to get started?Download WordPress

Forums

Return only top-level custom taxonomy term associated with posts in the loop (4 posts)

  1. Alex
    Member
    Posted 11 months ago #

    Hello,

    I have a loop of custom post types and I want to return the custom (hierarchical) taxonomy terms (with a link to the term archive) that are associated with each post in the loop.

    Some posts have multiple terms, and in such cases I only want to return the top-level term for that post.

    I've searched through the forums and tried numerous variations of 'get_terms', 'get_the_terms', and 'wp_get_object_terms'.

    They each work to get the terms and the term links, but I haven't figured out how to restrict them to returning only the top-level term.

    For example:

    <?php
    $terms = get_the_terms( $post->ID, 'countries' );
    
    $count = count($terms); $i=0;
    	if ($count > 0) {
    	    $cape_list = '<p class="my_term-archive">';
    	    foreach ($terms as $term) {
                     $i++;
    		 $term_list .= '<a href="'.get_term_link($term->slug, 'countries').'" title="' . sprintf(__('View all partner requests for %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '</a>';
    		  if ($count != $i) $term_list .= ' ยท '; else $term_list .= '</p>';
    	 }
            echo $term_list;
    }
    ?>

    works fine - but I want this to return only the top-level term.

    Any ideas? The loop I am referring to is the list of posts on the home page of http://trekkingpartners.com/.

    Thanks!
    Alex

  2. Alex
    Member
    Posted 10 months ago #

    just moving the post to the top again...

  3. stratocentric
    Member
    Posted 4 months ago #

  4. Alex
    Member
    Posted 4 months ago #

    with get_terms, I can limit the results to show just one term?

    I will check - thanks.

Reply

You must log in to post.

About this Topic