<?
function ns_get_related_posts($post, $post_type = 'post', $taxonomy = 'tag', $max_posts = null) {
$terms = get_the_terms($post->ID , $taxonomy);
$term_ids = array();
$result = array();
# If max_posts isn't provided, fall back to global posts_per_page option
if ($max_posts == null) {
$max_posts = get_option('posts_per_page');
}
# Map array of term ojects to an array of term ID's
if (!empty($terms)) foreach ($terms as $term) {
array_push($term_ids, $term->term_id);
}
if (!empty($term_ids)) {
$related_posts = new WP_Query(array(
'post_type' => $post_type,
'posts_per_page' => $max_posts,
'post__not_in' => array($post->ID),
'tax_query' => array(array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $term_ids
))
));
if($related_posts->have_posts()) {
foreach ($related_posts->posts as $related_post) {
array_push($result, $related_post);
}
}
}
return $result;
}