Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

how to add a .current_post_item class to a sidebar item? WordPress

  • SOLVED

I need to be able to style the current post item in a sidebar recent posts list but the standard wordpress widget doesn't add a specific class to the current post when you're on a single.php post, so I'm looking to hard code something into the sidebar or use exec php to stick some php in a text widget.

Starting with this as a basis, can anyone give me the code i need please:

<ul>
<?php
$number_recents_posts = 5;//Can be how much you want
$recent_posts = wp_get_recent_posts( $number_recents_posts );
foreach($recent_posts as $post){
echo '<li><a href="' . get_permalink($post["ID"]) . '" title="Look '.$post["post_title"].'" >' . $post["post_title"].'</a> </li> ';
} ?>
</ul>

Answers (3)

2011-01-07

John Cotton answers:

How about:



<ul>

<?php

$number_recents_posts = 5;//Can be how much you want

$recent_posts = wp_get_recent_posts( $number_recents_posts );

global $post;

foreach($recent_posts as $single_post){
if ( $single_post["ID"] == $post->ID ) {
echo '<li class="currentPost"><a href="' . get_permalink($single_post["ID"]) . '" title="Look '.$single_post["post_title"].'" >' . $single_post["post_title"].'</a> </li> ';
} else {
echo '<li><a href="' . get_permalink($single_post["ID"]) . '" title="Look '.$single_post["post_title"].'" >' . $single_post["post_title"].'</a> </li> ';
}

} ?>

</ul>


Dave Smith comments:

brill, exactly what i needed, thanks John, quick on the draw!

2011-01-07

S├ębastien | French WordpressDesigner answers:

use the widget "recent post"

[[LINK href="http://your-site.com/wp-admin/widgets.php"]]http://your-site.com/wp-admin/widgets.php[[/LINK]]

2011-01-07

Nathan Parikh answers:

Try this:

<ul>

<?php

$IDOutsideLoop = $post->ID;

global $post;

$number_recents_posts = 5;//Can be how much you want

$recent_posts = wp_get_recent_posts( $number_recents_posts );

foreach($recent_posts as $post){ ?>

<li <?php if(is_single() && $IDOutsideLoop == $post->ID) {echo " class=\"current\"";}?>><?php echo'<a href="' . get_permalink($post["ID"]) . '" title="Look '.$post["post_title"].'" >' . $post["post_title"].'</a> </li> ';

} ?>
<?php endforeach; ?>

</ul>