Bootstrap Templates Bundle

Wednesday, January 23, 2013

How to display related post by category

Paste this below code into post-single.php 
    <!--start of related post-->  
* @Author: Boutros AbiChedid
* @Credit:
* @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 '<div class="related">';
        echo '<h3>আরো খবর:</h3><ol>'; //*** MODIFY TITLE IF YOU LIKE ***
        //loop through the posts and list each until done.
        while ($query->have_posts()) {
            <li type="circle"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to: <?php the_title_attribute(); ?>">
            <?php the_title(); ?></a></li>
        echo '</ol>';
        echo '</div>';
//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.
<!--end of related post-->

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;
.related li{
    padding:0 0 5px 0;

No comments:

Post a Comment

Wokiee React eCommerce Template