Created
December 24, 2015 23:01
-
-
Save asharirfan/92d6ebd9eb9d280ca677 to your computer and use it in GitHub Desktop.
Similar posts by category in WordPress which excludes the current post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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