Kilian Valkhof

Building tools that make developers awesome.

Popular posts for WordPress 2.6

Wordpress, 18 August 2008, 2 minute read

On my homepage, I have the three most popular posts. Finding a plugin that did what I wanted and that worked with WordPress 2.6 proved to be quite impossible.

I wanted something that wasn’t so common: display the title, category, date, comments and excerpt, so I had to make something for myself.

What it does

At the moment, it’s quite basic. It sorts the posts on comment count, and displays the top n articles. I have three on my homepage. It uses the excellent post plugin library to get the date, category and excerpt into shape. (so, the post plugin library is needed for this to work). The code is based off of this example from the WordPress forums.

The Code

I haven’t looked into making wordpress plugins yet, so my popular post solution is just a snippet you can include in your theme:

	$sql='SELECT post_title, comment_count, guid, post_date, post_content, ID
	      FROM wp_posts
	      ORDER BY comment_count DESC
	      LIMIT 3;';
	$popresults = $wpdb->get_results($sql);

	foreach ($popresults as $r) {
		echo '<div class="post">';
		echo '	<h3><a href="' . $r->guid . '">' . $r->post_title .'</a>';
		echo '		<span>'. otf_categorylinks($r->ID, $r,', ').',';
		echo '			<abbr title="'. oth_format_date($r->post_date, "j F Y") . '">'. oth_format_date($r->post_date, "j/m") . '</abbr>,';
		echo '			<abbr title="' . $r->comment_count . ' comments">' . $r->comment_count . '</abbr>';
		echo '		</span>';
		echo '	</h3>';
		echo '	<p>'. oth_trim_excerpt($r->post_content, '45') .'…</p>';
		echo '</div>';

This snippet can be improved in a lot of ways. For one, making it a plugin would be a good idea. Secondly, attaching a time-based element would be nice, so that it can become “the popular posts of last month” instead of the all-time popular posts. Even more interesting would be linking it to the WP-Stats plugin. That offers an “active posts” lists, which seems to be based off of comments and visits to a certain posts over a limited period of time.

Polypane browser for responsive web development and design Hi, I'm Kilian. I make Polypane, the browser for responsive web development and design. If you're reading this site, that's probably interesting to you. Try it out!