Skip to content

Instantly share code, notes, and snippets.

@jackabox
Created August 12, 2014 15:50
Show Gist options
  • Select an option

  • Save jackabox/757b5fc2f2b0bd9b9086 to your computer and use it in GitHub Desktop.

Select an option

Save jackabox/757b5fc2f2b0bd9b9086 to your computer and use it in GitHub Desktop.
WordPress: related posts by tags
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) { ?>
<div class="related-posts">
<?php
$first_tag = $tags[0]->term_id;
$tagsIDs = array();
foreach ($tags as $tag):
$tagIDs[] = $tag->term_id;
endforeach;
$args=array(
'tag__in' => $tagIDs,
'post__not_in' => array($post->ID),
'posts_per_page'=> 4,
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
if (has_post_thumbnail()) {
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'blog-element', true);
$thumb_url = $thumb_url_array[0];
$class = '';
} else {
$thumb_url = '';
$class = 'no-image';
}
?>
<div class="blog-element <?php echo $class; ?>" style="background-image: url(<?php echo $thumb_url; ?>);">
<a class="back-drop" href="<?php the_permalink() ?>" title="Link to <?php the_title_attribute(); ?>">
<h4><?php the_title(); ?></h4>
<div class="meta">
<p class="date"><?php the_time('j F, Y'); ?></p>
<?php
if(in_category('inspiring')) {
echo "<p class='category'><span>all.</span>inspiring</p>";
} elseif(in_category('news')) {
echo "<p class='category'><span>all.</span>news</p>";
}
?>
</div>
</a>
</div>
<?php
endwhile;
} ?>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment