Skip to content

Instantly share code, notes, and snippets.

@johanbrook
Created January 13, 2012 15:34
Show Gist options
  • Select an option

  • Save johanbrook/1606996 to your computer and use it in GitHub Desktop.

Select an option

Save johanbrook/1606996 to your computer and use it in GitHub Desktop.
Get related posts in Wordpress
function get_related_posts($options = array("numberposts" => 4)) {
global $post;
$defaults = array(
"post__not_in" => array($post->ID)
);
$args = array_merge($options, $defaults);
$tags = wp_get_post_tags($post->ID);
$cats = wp_get_post_terms($post->ID, "category", array("fields" => "ids"));
function getID($tag){
return $tag->term_id;
}
$args['tax_query'] = array(
'relation' => 'OR',
array(
"taxonomy" => "category",
"field" => "id",
"terms" => $cats
),
array(
"taxonomy" => "post_tag",
"field" => "id",
"terms" => array_map("getID", $tags)
)
);
return get_posts($args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment