Skip to content

Instantly share code, notes, and snippets.

@Sjouw
Created December 18, 2014 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sjouw/272ab09f2495d9be74d5 to your computer and use it in GitHub Desktop.
Save Sjouw/272ab09f2495d9be74d5 to your computer and use it in GitHub Desktop.
WordPress - Better latest posts sidebar menu widget with active states
<?php
// Get the poststype of the current post
$posttype = get_post_type();
$obj = get_post_type_object( $posttype );
$args = array (
'post_type' => $posttype,
'post_status' => 'publish',
'post_count' => 5
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : ?>
<nav id="subnavi" class="widget">
<header class="widget-header">
<h3>
Latest <span class="posttype-name"><?php echo $obj->labels->name; ?></span>
</h3>
</header>
<ul class="sub-menu">
<?php while ( $query->have_posts() ) :
$query->the_post();
$queried_object = get_queried_object();
if( $queried_object->ID == get_the_ID() ):
// Add active class if this is the current post
$class = 'current_page_item';
else:
// Add no class if this is not the current post
$class = '';
endif;
?>
<?php // print the list items with the correct classes ?>
<li<?php echo $class !='' ? ' class="' . $class . '"' : '';?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
</nav>
<?php endif;
wp_reset_postdata();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment