Skip to content

Instantly share code, notes, and snippets.

@asharirfan
Created December 24, 2015 23:01
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 asharirfan/92d6ebd9eb9d280ca677 to your computer and use it in GitHub Desktop.
Save asharirfan/92d6ebd9eb9d280ca677 to your computer and use it in GitHub Desktop.
Similar posts by category in WordPress which excludes the current post
<?php
/**
* Similar posts loop
*/
$categories = get_the_category(); //get all categories for this post
$cat_id = $categories[0]->cat_ID;
echo $cat_id;
$args = array(
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'posts_per_page' => 2,
'post__not_in' => array($post->ID),
'category__in' => $cat_id,
); // post__not_in will exclude the current post
$wt_query = new WP_Query( $args );
if($wt_query->have_posts()) :
while ($wt_query->have_posts()) :
$wt_query->the_post();
the_title();
endwhile;
wp_reset_postdata();
else :
echo '<p>'.<?php _e( 'Sorry, no posts matched your criteria.' ); ?>.'</p>'
endif;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment