random posts from category

December 3rd, 2006

The other day I was thinking it would be nice to have a little space below every blog entry that displays past entries from this same category, but in random. So this would be a cool way to explore old entries for someone who hasn't seen the blog before, but no less for me since I wrote that stuff at one point and forgot all about it. It was actually seeing KeyBi's blog that inspired me to do this, cause he has a random posts feature on his.

I used an existing plugin and modified it for my needs to look exactly as you can see at the bottom of this post.

So now it's easier to browse old posts, but this brought out an old problem, namely that entries posted before the migration to WordPress were not input with their comments counted, so although these old entries have comments, WordPress doesn't seem aware of this. I fixed that with the simple script below.

<?

$user = '';
$pass = '';
$db = '';
$host = '';

$link = mysql_connect($host, $user, $pass) or die("kernel panic");
mysql_select_db($db);

$sql = "select ID from wp_posts where post_status = 'publish'";
$result = mysql_query($sql);

$IDs = array();
while ($row = mysql_fetch_row($result)) {
	$IDs[] = $row[0];
}

foreach ($IDs as $i) {
	$sql  = "update wp_posts set comment_count = ";
	$sql .= "(select count(*) from wp_comments where comment_post_ID = $i ";
	$sql .= "and comment_approved = '1') ";
	$sql .= "where ID = $i";
	mysql_query($sql);
}

mysql_close($link);

echo "Comments updated.";
?>

:: random entries in this category ::

2 Responses to "random posts from category"

  1. [...] Leonid Mamchenkov for his excellent Nucleus2Wordpress Perl script Martin Matusiak for the blog entry describing his migration [...]

  2. Dorian says:

    Nice modify of the plugin... I was looking for something like this.

    The only change I made was I put back in the $show_excerpt function.

    I had to hack around a bit but finally got it to work (not a programmer).

    Anyway... thanks.