Support

Account

Home Forums Front-end Issues Pulling values from taxonomy array Reply To: Pulling values from taxonomy array

  • Hi Kyle, I recreated the situation over here and have some verified code. Here’s a complete, but simplified page template (‘single-project.php’):

    <?php get_header(); ?>
    
    	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    			
    			<h1><?php the_title(); ?></h1>
    				<?php the_content(); ?>
    
            <?php 
            // Grab all of the 'category' terms that have been applied to this 'project' and 
            // go through and output the category title and any posts that fall under the category.
            $categories = get_the_terms( $post->ID, 'category' );
            if ( $categories && ! is_wp_error( $categories ) ) : ?>
            
              <?php foreach ( $categories as $category ) : ?>
                
                <h3><?php echo $category->name; ?>:</h3>
               
                <?php // Generate a custom query using the category's slug
                $relatedPosts = new WP_Query( array('category_name' => $category->slug, 'posts_per_page' => -1) );
                if ( $relatedPosts->have_posts() ) : ?>
                
                  <ul>
                  
                  <?php while ( $relatedPosts->have_posts() ) : $relatedPosts->the_post(); ?>
                  
                    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
      
                  <?php endwhile; ?>
                  
                  </ul>
                
                <?php endif; 
                // Restore the global $post variable to the current post in the main query
                wp_reset_postdata(); ?>
              
              <?php endforeach; ?>
            <?php endif; ?>
    
    	<?php endwhile; endif; ?>
    
    <?php get_footer(); ?>

    As I was setting this up, I realized that it’s possible that the earlier snippet may not have worked for you because of the way the options may be set in the custom field definition. When adding the ‘taxonomy’ custom field, make sure that the field is set to return the ‘Term Object’ instead of the ‘Term ID’ so that it will work with the above code block.

    OK, let me know how this works.

    Thanks,

    Jeff