简体   繁体   中英

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>

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.

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); 
?> 
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM