WordPress: better post dates with jQuery

WordPress: better post dates with jQuery

A simple and effective way to create stylish and sticky post dates with jQuery on WordPress.

Imagine that your WordPress site features post dates as stylized inline elements at the bottom of each post. This is correct, because from a SEO perspective all the relevant content must come first. So far so good. Anyway, you want something more stylish, such as a post date wrapped by a cool badge just near each post title. Of course you can't modify the underlying markup of your theme because you don't want to alter your structure, thus potentially losing all the SEO benefits mentioned above. Here's where jQuery comes into play.

First of all, define how your dates should look like in your CSS:

.date-widget {
	width: 100px;
	height: 100px;
	background: url(images/date-badge.png) no-repeat 0 0;
	color: #fff;
	font-family: serif;
	position: absolute;
}

.date-widget span {
	display: block;
	text-align: center;
	font-size: 1.4em;
}

.date-widget span.day {
	padding-top: 24px;
	font-size: 1.6em;
}

.date-widget span.month {
	padding-top: 8px;
} 

Our dates will be injected into the main body element and absolutely positioned by taking the top and left offsets of each post:

(function($) {

	function prettyDate() {
	
	
		$('div.post').each(function() {
    		
    			var post = $(this);
    			var meta = $('ul.post-meta', post);
    			var date = $('li:first', meta).text();
    			var parts = date.split(' ');
    			var day = parts[0];
    			var month = parts[1].substring(0, 3);
    			
    			$('<div class="date-widget"/>').
    							 html('<span class="day">' + day + '</span>' +
    							 '<span class="month">' + month + '</span>').css({
    							 top: post.offset().top,
    							 left: post.offset().left - 120
    							 }).appendTo('body');
    		
    		
    		});
    	
    	

	
	
	
	}
	
	
	$(function() {
	
		prettyDate();
	
	
	});


})(jQuery);

Date parts, namely day number and month, have been taken by our post meta element by splitting its text contents. As you can see, we've used the top and left properties of the offset() method for each post to exactly position our elements.

Demo

Take a look around. ;-)