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

$(document).ready(function() {
	// Your base URL
	var baseUrl = "";
	// 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

#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 Articles

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.