Retroactively add keywords for your existing Octopress posts

less than 1 minute read

At the moment, I am exploring the world of SEO, and so I thought I could start with my blog. I found SEO for Octopress websites that I followed to add keywords and descriptions to this blog.

To fill actual keywords for all my existing posts, I had 2 options :

  • edit around 60 posts by hand
  • write a script to parse Yaml post descriptions and extract and inject keywords

Sorry, I chose the geeky solution …

desc "add keywords to posts"
task :add_keywords do
Dir.glob(File.join(File.dirname(__FILE__),"source/_posts/*.markdown")) do |file|
yaml = YAML.load_file(file)
keywords = yaml['categories'] || []
title = yaml['title']
keywords += title.scan(/'.*'/).map {|kw| kw.gsub("'",'')}
keywords += title.scan(/\S+[\sv~>]+?\d+\.\d+\.?\d*/)
title = title.gsub(/[\sv~>]+?\d+\.\d+\.?\d*/,'')
title = title.gsub(/['\?:\d\.]/,'')
keywords += title.split()
keywords_hash = {}
keywords.each do |keyword|
keywords_hash[keyword.downcase] = keyword
end
%w(# a an i on of to in my from how for the just best own after full if ~> and with when do does not are et up way first set like be there only can one per).each do |word|
keywords_hash.delete(word)
end
system "sed -i '1 a\
keywords: \"#{keywords_hash.values.join(', ')}\"
' #{file}"
end
end
view raw Rakefile hosted with ❤ by GitHub

Just add this code to your toplevel Rakefile, and run bundle exec rake add_keywords and keywords will be added to your existing posts.

I usually write about 15 minutes worth of reading per month. I won't transfer your email. No Spam, unsubscribe whenever you want.

As a gift for subscribing, you'll receive an illustrated mini-ebook "How to start a team coding dojo"!

Leave a comment