Support

Account

Home Forums General Issues Looping through custom post types showing custom taxonomy term field

Solved

Looping through custom post types showing custom taxonomy term field

  • My aim is to loop through two custom post types, showing the following for each:

    • featured image
    • title (linked)
    • all associated terms from custom taxonomy (linked to their respective taxonomy archives)
    • a custom field withineach term (in this case a hexidecimal colour)

    So far I have the following working:

    <div class="course-listing">
    
    <?php 
    $courseloop = new WP_Query( array( 
    'post_type' 		=> array(
    'apprenticeship', 'qualification'
    ), 
    'posts_per_page' 	=> 100, 
    'post_parent' 		=> 0, 
    'order' 			=> 'ASC', 
    'orderby' 			=> 'title' 
    ) 
    );
    
    if ( $courseloop->have_posts() ) : ?>
    
    <div class="row small-up-1 medium-up-3">
    
    <?php while ( $courseloop->have_posts() ) : $courseloop->the_post(); ?>
    
    <div class="column column-block">
    
    <a class="image-link <?php foreach( $terms as $term ) echo ' ' . $term->slug; ?>" href="<?php the_permalink(); ?>">
    <?php
    if ( has_post_thumbnail() ) {
    the_post_thumbnail('listing');
    }
    else {
    $image = get_field('default_course_post_image', 'option');
    
    echo wp_get_attachment_image( $image, 'listing' );
    } ?>
    </a>
    
    <h3>
    <a href="<?php the_permalink(); ?>">
    <?php 
    $title = get_the_title();
    echo $title;
    ?>
    </a>
    </h3>
    
    <p><?php
    $terms = get_the_terms( $post->ID, 'course_type' );
    if ($terms && ! is_wp_error($terms)): ?>
    <?php foreach($terms as $term): ?>
    <a href="<?php echo get_term_link( $term->slug, 'course_type'); ?>" rel="tag" class="term-tag <?php echo $term->slug; ?>"><?php echo $term->name; ?></a>
    <?php endforeach; ?>
    <?php endif; ?></p>
    
    <a class="float-left button" href="<?php the_permalink(); ?>">Details</a>
    
    </div><!-- end .columns -->
    
    <?php endwhile; ?>
    
    </div><!-- end .row -->
    
    <?php else: ?>
    
    <p>Nothing found</p>
    
    <?php endif; // End of the course loop ?>
    
    </div>

    Everything’s working pretty well so far, but I don’t know how to pull in the custom field that is attached to each term. It’s called course_colour and I’ve tried adding $color = get_field('course_colour', $term); alongside the term slug, but it won’t work.

    Any suggestions?

  • 
    $color = get_field('course_colour', 'term_'.$term->term_id);
    echo $color;
    

    or

    
    the_field('course_colour', 'term_'.$term->term_id);
    
  • Thanks @hube2, it was the second of those two that worked 🙂

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Looping through custom post types showing custom taxonomy term field’ is closed to new replies.