Finally got rid of the "General" category!

2008 January 27
by Joel

Alrighty then! I finally got rid of my pesky old “General” category! All this time I’ve always had this problem with my imported blog entries — my default category in my previous blogs was “General”, while my more recent blogs had “Life” as the default category. Now, as you can imagine, using WordPress’ admin facilities for manually editing the categories of each and every entry is just a damn chore! So what’s a geek with a newfound fondness for Ruby to do? Write a script to do the editing for him, that’s what!

And that’s exactly what I did!

Here’s the code I used to scan all posts for that “General” category, and edit those posts to change the “General” category to “Life” instead:


require 'blog_client' #this is where my BlogClient class is

def print_post(mypost)
  puts "============================================"
  mypost.each do |key,value|
    puts "key = #{key}"
    puts "value = #{value}"
  end
  puts "============================================"
end

#parameters are: blog id, blog xml-rpc url, username, password
client = BlogClient.new("xxxxxx","http://samildanach.wordpress.com/xmlrpc.php","yyyyy", "zzzzz")

#get_recent_posts() takes the number of posts as a parameter.
#If you specify a number equal to or larger than the
#total number of posts, you get the contents of your entire blog.
#The method returns an array of hash maps representing your posts
myposts = client.get_recent_posts(900)
post_ctr = 0
myposts.each do |mypost|
  found = false
  print_post(mypost)
  categories = mypost["categories"] #get an array of strings representing categories
  n = categories.size
  #check categories, change "General" to "Life"
  for i in 0..n-1 do
    if categories[i] == "General"
      found = true
      puts "FOUND POST!"
      print_post(mypost)
      categories[i] = "Life"
      break
    end
  end
   if found
     post_ctr+=1
      puts "EDITED POST"
      print_post(mypost)
      #specify post id, and pass the mypost hashmap
      client.edit_post(mypost["postid"],mypost)
   end

end

puts "#{post_ctr} POSTS EDITED!!!" #print number of posts edited

And that’s how I changed all my old posts to have “Life” as the default category! I know, I know — its just a category, its just an effin’ blog, who the hell cares, right? I know! But that damn old category is just… annoying.Now if only I can make a script that’ll scan for broken links to my old blog entries and replace it with links to the current one…