How to display related post by category
Paste this below code into post-single.php
/********** CODE BLOCK2 (BASED ON ALL COMMON CATEGORIES) *********
* @Author: Boutros AbiChedid
* @Credit: http://bacsoftwareconsulting.com/blog/
* @Date: May 24, 2011
* Tested on WordPress version 3.1.2
* @Description: Code that shows other "Related Posts" to a post
* based on ALL COMMON categories.
*******************************************************************/
//Retrieve the list of categories for a post.
$categories = get_the_category($post->ID);
//If categories exist for the post.
if ($categories) {
$category_ids = array();
//retrieve the category_ids for the post.
foreach($categories as $each_category)
$category_ids[] = $each_category->term_id;
//WP_Query arguments.
$args = array(
'category__in' => $category_ids, //An array of category IDs to be included.
'post__not_in' => array($post->ID), //An array of post IDs to be excluded from the results.
'orderby'=> 'rand', //Lists Related posts Randomly. *** MODIFY IF YOU LIKE ***
'showposts' => 10, //*** MODIFY TO WHAT YOU LIKE.*** Number of related posts to show.
//'caller_get_posts' => 1 //*** USE THIS IF YOU ARE RUNNING WordPress Version < 3.1 ***
'ignore_sticky_posts' => 1 //*** USE THIS for WordPress Version >= 3.1 ***
);
//WP_Query is a class defined in wp-includes/query.php
$query = new WP_Query($args);
//If there are related posts.
if( $query->have_posts() ) {
echo ' ';
}
}
//Destroy the previous query. This is a MUST, otherwise you will get the WRONG comments
//(comments assigned to the wrong post), and sometimes categories and tags are for the wrong post.
wp_reset_query();
?>
Paste this below code into style.css
/* Styling Related Posts Section by BOUTROS ABICHEDID */
.related {
padding:5px 0 10px 0;
margin:30px 0 0 0;
clear: both;
border-top:2px solid #EFE7D1;
border-bottom:0;
border-left:0;
border-right:0;
}
.related li{
padding:0 0 5px 0;
}