WordPress get posts by taxonomy terms

With get_posts() you can do a lot of things, like creating multiple posts loops, retrieve posts by all sorts of criteria, etc.

One of the interesting part comes when you want to create a posts loop with only the posts from certain taxonomy term/terms.

On the codex page of the get_posts function, we find an example, which tells us to rename the ‘category’ argument with our taxonomy name, and it’s value is one of taxonomy’s terms name; but they don’t say anything about multiple terms. Well, it seems like it works if you pass a comma separated string of terms, the question now is how you can get a comma separated string of terms, of the current post, in single-posttype.php.

The get_the_term_list() seems to be just perfect for the job. The problem with this is that it also returns html anchor tags with the terms link; this can be solved with the strip_tags() php function.

$terms = strip_tags( get_the_term_list( $post->ID, 'taxonomy-name', '', ',', '' ) );

$arg = array(
	'numberposts' => 4,
	'orderby' => 'rand',
	'post_type' => 'post-type-name',
	'taxonomy-name' => $terms,
	'post_status' => 'publish'
$related_posts = get_posts ( $arg );

This can be a nice way to get random related posts who share same taxonomy terms.

Leave a Reply

Your email address will not be published. Required fields are marked *

× 6 = 42

This site uses Akismet to reduce spam. Learn how your comment data is processed.