List Posts, Highlight Current

Avatar of Chris Coyier
Chris Coyier on (Updated on )

WordPress lacks a wp_list_posts() function that might seem logical go with the robust and useful wp_list_pages() function. You can simulate it though, by using the get_posts() function and running your own loop through the results.

The parameters for get_posts() below are just examples, replace with your needs.


        $lastposts = get_posts('numberposts=5&orderby=rand&cat=-52');
        foreach($lastposts as $post) :
        setup_postdata($post); ?>

        <li<?php if ( $post->ID == $wp_query->post->ID ) { echo ' class="current"'; } else {} ?>>
            <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>

    <?php endforeach; ?>


wp_list_pages() also has the feature of adding a class name of “current_page_item” to the list element when that page is the active one. Notice the opening list tag above, which replicates that functionality by seeing if the ID from the current query matches the ID from the current iteration of the loop.