Skip to content

Instantly share code, notes, and snippets.

@aosipov
Created November 17, 2017 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aosipov/45d34939b3e25fb00351ed75cdc8e33e to your computer and use it in GitHub Desktop.
Save aosipov/45d34939b3e25fb00351ed75cdc8e33e to your computer and use it in GitHub Desktop.
related posts snippets
<div class="relatedposts">
<h3>Related posts</h3>
<?php
global $post;
setup_postdata( $post );
echo "Post's ID: " . get_the_ID();
?>
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>4, // Number of related posts to display.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
while( $my_query->have_posts() ) {
$my_query->the_post();
?>
<div class="relatedthumb">
<a rel="external" href="<? the_permalink()?>"><?php the_post_thumbnail(array(150,100)); ?><br />
<?php the_title(); ?>
</a>
</div>
<?php }
}
$post = $orig_post;
wp_reset_query();
?>
</div>
<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo '<h2 class="display">Related posts</h2>';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'posts_per_page'=>8,
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="related-thumb">
<a rel="external" href="<? the_permalink()?>">
<h2><?php the_title(); ?></a></h2>
</div>
<?php
endwhile;
}
wp_reset_query();
}
?>
<!-- You may also like related posts -->
<div class="row related-posts-after-content">
<h2 class="display col-md-12">You Might Also Like</h2>
<?php
global $post;
setup_postdata( $post );
echo "Post's ID: " . get_the_ID();
?>
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>8, // Number of related posts to display.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
while( $my_query->have_posts() ) {
$my_query->the_post();
?>
<div class="col-md-12 related-thumb">
<h2><a rel="external" href="<? the_permalink()?>">
<?php the_title(); ?></a></h2>
</div>
<?php }
}
$post = $orig_post;
wp_reset_query();
?>
</div>
<!-- End of you may also like related posts -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment