Skip to content

Instantly share code, notes, and snippets.

@rodica-andronache
Last active December 28, 2015 09:49
Show Gist options
  • Select an option

  • Save rodica-andronache/7481601 to your computer and use it in GitHub Desktop.

Select an option

Save rodica-andronache/7481601 to your computer and use it in GitHub Desktop.
Related posts - by tags and categories
<?php
$max_articles = 7; // How many articles to display
echo '<h3>Related Topics</h3><ul class="related-topics">';
$cnt = 0;
$article_tags = get_the_tags();
$tags_string = '';
if ($article_tags) {
foreach ($article_tags as $article_tag) {
$tags_string .= $article_tag->slug . ',';
}
}
$tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
$used = array();
array_push($used, $post->ID);
if ($tag_related_posts) {
foreach ($tag_related_posts as $related_post) {
$cnt++;
echo '<li class="child-' . $cnt . '">';
echo '<a href="' . get_permalink($related_post->ID) . '">';
echo $related_post->post_title . '</a></li>';
array_push($used,$related_post->ID);
}
}
// Only if there's not enough tag related articles,
// we add some from the same category
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = '';
foreach($article_categories as $category) {
$category_string .= $category->cat_ID . ',';
}
$args=array(
'cat' => $category_string,
'post__not_in' => $used,
'showposts'=>$max_articles,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ):
while ($my_query->have_posts()) : $my_query->the_post();
$cnt++;
if ($cnt > $max_articles) break;
echo '<li class="child-' . $cnt . '">';
echo '<a href="' . get_permalink() . '">';
the_title();
echo '</a></li>';
endwhile;
endif;
wp_reset_postdata();
}
echo '</ul>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment