Skip to content

Instantly share code, notes, and snippets.

@andrewlaskey
Created November 26, 2013 00:18
Show Gist options
  • Save andrewlaskey/7651299 to your computer and use it in GitHub Desktop.
Save andrewlaskey/7651299 to your computer and use it in GitHub Desktop.
Display a Wordpress post's related posts.
<?php
function get_related_posts() {
$terms = get_the_terms(get_the_ID(), 'category');
$sub_cat = '';
if ( $terms && ! is_wp_error( $terms ) ) :
if (count($terms) >= 2) {
foreach ( $terms as $term ) {
if ($term->parent != 0) {
$sub_cat = $term->slug;
}
}
} else {
foreach ( $terms as $term ) {
$sub_cat = $term->slug;
}
}
$args=array(
'post_type' => 'post',
'category' => $sub_cat,
'post__not_in' => array($post->ID),
'posts_per_page'=>3,
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<div class="row">
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="large-4 columns">
<h5><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h5>
<p><?php the_excerpt(); ?></p>
</div>
<?php
endwhile;
}
wp_reset_query();
?>
</div>
<?php endif;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment