WordPress Tip – Highlight the current menu post link when on that post page

Sometime when editing your custom WordPress theme you may want to list the latest posts and highlight the post when your on that post / page.

This can be done by firstly setting up your CSS to style a link how you want it when its current

[sourcecode language=”css”]#latest-news h2 a.current{ color:black;}[/sourcecode]

Next you need to generate your list and of course in particular you will see the condition to flag the current post page current.

[sourcecode language=”php”]

$temp = $wp_query; // move original query to temp for later use in other loops

$currentpost = $post->ID;
$wp_query = null;
$wp_query = new WP_Query($args);

<div id="latest-news">
<img src="<?php bloginfo(‘template_directory’); ?/>/images/news_icon.png" />
<h2 class="title">News</h2>
< ?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<div id="post-<?php the_ID(); ?>" < ?php post_class(); ?>>
< ?php the_date(‘F Y’, ‘<p class="newsdate" style="margin-bottom:1px;text-transform:uppercase;">’, ”); ?>
<h2 class="entry-title "><a class="grey-txt no-deco <?php if($currentpost == $post->ID) { echo "current"; } ?>" href="< ?php the_permalink(); ?>" title="< ?php printf( esc_attr__( ‘Permalink to %s’ ), the_title_attribute( ‘echo=0’ ) ); ?>" rel="bookmark">< ?php the_title(); ?></a></h2>

< ?php endwhile; ?>


< ?php
$wp_query = $temp;

You will notice we are creating a new query, so storing the old one and its page id first before we over run it while in the loop.

[sourcecode]$currentpost = $post->ID;[/sourcecode]

And then comparing the ids in the loop against current page.

[sourcecode]< ?php if($currentpost == $post->ID) { echo "current"; } ?>[/sourcecode]


Related Posts