dave
dave

Reputation: 1

WordPress sidebar: make custom loop display posts in same category as single post, EXCLUDING current single post from the list

This is from a sidebar set up to display 10 recent posts from the same category as the current single post being viewed. Unfortunately, it also includes the title and excerpt of the current single post in the list.

Does anyone know how to change it so it EXCLUDES the current single post? Other than that, it works fine.

<?php
$query = "showposts=10&orderby=date&cat=";

foreach((get_the_category()) as $category)
{ 
    $query .= $category->cat_ID .","; 
}

query_posts($query);
?>

<ul>
    <?php while (have_posts()) : the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title() ?></a>
    <?php the_excerpt(); ?>
    </li>

<?php endwhile; ?>       

</ul>

Upvotes: 0

Views: 1475

Answers (2)

Raularam
Raularam

Reputation: 11

Hope this answer doesn't come too late. Dave, there is just a minor mistake in the code that goes in the sidebar:

In the line that says &post__not_in= there is an additional underscore between the word post and not.

Delete it and it will work.

Thanks Poelinca for the code snippet.

Upvotes: 1

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

In you're main query do ( the query from you're single.php file ) :

<?php global $mainPostID; $mainPostID = get_the_id(); ?>

Then you're sidebar code would become this :

<?php 
$query = "showposts=10&orderby=date&cat="; 


foreach((get_the_category()) as $category) { 
    $query .= $category->cat_ID .",";
} 

#magic happens here
global $mainPostID;
if ( !empty($mainPostID) && is_single() )
    $query .= "&post__not_in=" . $mainPostID;

query_posts($query); 
?> 
...

Upvotes: 0

Related Questions