Kevin Leary is a Web User Interface Designer and Front End Developer specializing in standards compliant XHTML, CSS and JavaScript.

Highlight current Wordpress post

I came across a dilemma recently. I wanted to highlight the Wordpress post that is currently shown in my sidebar menu. I couldn’t find a sound solution for this, so here’s what I came up with. Using JavaScript and jQuery 1.2.3 I was able to highlight the current post in the Wordpress navigation, or sidebar by dynamically adding the class “current” to the anchor tag.

JavaScript / jQuery

1
2
3
4
5
6
7
8
9
10
11
$(document).ready(function() {
	// Your base URL
	var baseUrl = "http://www.kevinleary.net";
	// You need to target your sidebar here, change #secondaryContent to your sidebar identifier (id)
	$("#secondaryContent a").each(function(){
		var href = $(this).attr('href').replace(baseUrl,'');
		if (href == document.location.pathname) {
			$(this).addClass('current');
		}
	});
});

CSS

1
2
3
4
5
#secondaryContent .current
{
	padding-left:15px;
	background:url(images/current-link.gif) 0 4px no-repeat;
}

Usage

First include your copy of jQuery within the HEAD section of the document. Next include the above snippet of JavaScript in your document. Let the script do the rest.

Note

Be sure to modify the baseUrl variable, making it equal to your domain name. Without this the script will NOT function.

Related links

Comments

One Response to “Highlight current Wordpress post”

  1. Alexander Hahn on April 13th, 2008 at 5:41 pm

    Hey! Your code didn’t work in my project, but I found out how to do it:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    $(document).ready(function() {
    	var baseUrl = document.URL;
    	// You need to target your sidebar here, change #sidebar to your sidebar identifier (id)
    	$("#sidebar a").each(function(){
    		var href = $(this).attr('href');
    		if (href == baseUrl) {
    			$(this).parent().addClass('current_post');
    		}
    	});
    });

Say something