Adding ‘current_post_item’ class to current post in the loop

I’m using a loop in the sidebar of my site to show all the posts that are in that category.
Now I’d like to include a ‘current_post’ class to the current post that is being displayed to style that item in the list.

I’ve tried looking for conditional tags or this custom wp_list_post_types function but both haven’t worked.
Does anybody know if there’s a way to do this?

EDIT: Adding Loop from comment below

<?php foreach((get_the_category()) as $category) { 
$postcat= $category->cat_ID; 
$catname =$category->cat_name; } 
$args = array( 'cat' => $postcat ); 
$my_query = new WP_Query(); 
$my_query->query($args); // Equivalent of query_posts()

while($my_query->have_posts()) : $my_query->the_post(); 
$id=get_the_ID();   
$currentClass= ($post->ID == $id) ? "current_post": ""; ?>
<a class="<?php echo   $currentClass; ?>" href="https://wordpress.stackexchange.com/questions/14531/<?php the_permalink();?>">ni</a> 
<?php endwhile; ?>

2 Answers
2

You should be able to get the queried object id and use that for comparison inside your custom loop..

Before your existing loop code(what you have posted above), but obviously after the opening PHP tag..

global $wp_query;
$current_id = $wp_query->get_queried_object_id();

Then somewhere inside your custom WP loops..

if( $current_id == get_the_ID() ) {
    // This result is the current one
}
else {
    // Not current
}

Hope that helps..

Leave a Comment