Created
December 18, 2014 15:19
-
-
Save Sjouw/272ab09f2495d9be74d5 to your computer and use it in GitHub Desktop.
WordPress - Better latest posts sidebar menu widget with active states
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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