Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm wondering how I can show recent posts from the same taxonomy as the post that's currently being viewed (working with custom post types and custom taxonomies).

If it was simply a category of a regular post, it would look like this:

<?php global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<h3>More News From This Category</h3>
<ul>
<?php
$posts = get_posts('numberposts=20&category='. $category->term_id);
foreach($posts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
<li><strong><a href="<?php echo get_category_link($category->term_id);?>" title="View all posts filed under <?php echo $category->name; ?>">ARCHIVE FOR '<?php echo $category->name; ?>' CATEGORY &raquo;</a></strong></li>
<?php endforeach; ?>
</ul>

But with custom posts/taxonomies, there has to be a different sort of solution. Couldn't find anything useful so far in the wordpress codex.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Have you tried using get_the_terms()?

Quick-and-dirty, from your code example:

<?php 
global $post;
$terms = get_the_terms( $post->ID, 'some-term' );
foreach ($terms as $category) :
?>
<h3>More News From This Category</h3>
<ul>
<?php
$posts = get_posts('numberposts=20&category='. $category->term_id);
foreach($posts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
<li><strong><a href="<?php echo get_category_link($category->term_id);?>" title="View all posts filed under <?php echo $category->name; ?>">ARCHIVE FOR '<?php echo $category->name; ?>' CATEGORY &raquo;</a></strong></li>
<?php endforeach; ?>
</ul>

See also: the_terms() and get_the_term_list()

share|improve this answer

To get the terms (from a custom taxonomy called 'my-taxonomy-name') associated with to a post with ID $post_id:

$terms = get_the_terms( $post_id, 'my-taxonomy-name' );

That returns an array of term objects. (see Codex) Pick the first one, say: $term-slug = $terms[0]->slug;

And then query using get_posts, it accepts our taxonomy as a key (see

$args = array(
   'numberposts' => 20,
   'my-taxonomy-name' =>  $term-slug 
);
$posts = get_posts ( $args );

See the Codex on custom taxonomies and get_posts

share|improve this answer
    
Heh, our answers dropped at almost exactly the same time, and are almost exactly the same. So, upvote for you. :) –  Chip Bennett Jan 19 '12 at 17:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.