Support

Account

Home Forums General Issues Related Posts by Taxonomy

Helping

Related Posts by Taxonomy

  • I’m trying to list the titles of related posts using the taxonomy field.

    I’m using the following code below from the docs that links to all the posts in the taxonomy, but is it possible to show the list of posts on single.php and if it is how would I do that?

    Thanks

    <?php 
    
    $terms = get_field('taxonomy_field_name');
    
    if( $terms ): ?>
    
    	<ul>
    
    	<?php foreach( $terms as $term ): ?>
    
    		<h2><?php echo $term->name; ?></h2>
    		<p><?php echo $term->description; ?></p>
    		<a href="<?php echo get_term_link( $term ); ?>">View all '<?php echo $term->name; ?>' posts</a>
    
    	<?php endforeach; ?>
    
    	</ul>
    
    <?php endif; ?>
  • Hi @leanda,

    Thanks for the post.

    The above code should list the Taxonomy terms, but if you are calling the Tax field outside the main posts loop, you might need to add a second parameter to the get_field() function and this should be a string containing the post->ID that the field is referenced in.

    Your overall snippet should then look like so:

    <?php 
    
    $terms = get_field('taxonomy_field_name', 123); //123 is the numerical post id identifier
    
    if( $terms ): ?>
    
    	<ul>
    
    	<?php foreach( $terms as $term ): ?>
    
    		<h2><?php echo $term->name; ?></h2>
    		<p><?php echo $term->description; ?></p>
    		<a href="<?php echo get_term_link( $term ); ?>">View all '<?php echo $term->name; ?>' posts</a>
    
    	<?php endforeach; ?>
    
    	</ul>
    
    <?php endif; ?>
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Related Posts by Taxonomy’ is closed to new replies.