Skip to content

Instantly share code, notes, and snippets.

@ttscoff
Created October 22, 2012 13:18
Show Gist options
  • Save ttscoff/3931470 to your computer and use it in GitHub Desktop.
Save ttscoff/3931470 to your computer and use it in GitHub Desktop.
Routine to replace [gallery] shortcodes during Jekyll WordPress import
# create a 150x150 thumbnail of the passed image using `sips`
# img is an absolute path to the base image file
def thumbnail_image(img)
return_dir = Dir.pwd
Dir.chdir(File.dirname(img))
width = %x{sips -g pixelWidth #{img.strip}|tail -n 1}.gsub(/pixelWidth: /,'').strip.to_i
height = %x{sips -g pixelHeight #{img.strip}|tail -n 1}.gsub(/pixelHeight: /,'').strip.to_i
thumb_name = img.strip.gsub(/^(.*?)(\..{3,4})$/,"\\1-150x150\\2").strip
thumb = File.expand_path(thumb_name)
FileUtils.cp(File.expand_path(img),thumb)
type = width > height ? '--resampleHeight' : '--resampleWidth'
%x{sips #{type} 150 #{thumb} && sips -c 150 150 #{thumb}}
Dir.chdir(return_dir)
return thumb_name
end
# `content` is a passed string containing post_content
# `attachments` is an array of hashes containing 'title' and 'url' for each attachment on the post
# replace_galleries uses kramdown syntax for attributes and classes, adjust as needed
def replace_galleries(content, attachments)
images = "\n" # unordered list of thumbnails linked to images as references
imagerefs = "\n" # block of reference defenitions
counter = 1
content.gsub!(/\[gallery.*?\]/) do |gall|
attachments.each do |att|
image = att['url'].gsub(/^#{@domain}\/wp-content/,'').sub(/-\d+x\d+\./,'.')
thumb = image.sub(/(.*?)(\..{3,4})/,'\\1-150x150\\2')
assets_dir = Dir.pwd+"/source"
return gall unless File.directory?(assets_dir+File.dirname(thumb))
unless File.exists?(assets_dir+thumb)
thumb = thumbnail_image(assets_dir+image)
puts thumb
end
title = att['title']
images += %Q{* [![#{title}][img#{counter}thumb]{: width="150" height="150"}][img#{counter}]\n}
imagerefs += %Q{[img#{counter}thumb]: #{thumb}\n}
imagerefs += %Q{[img#{counter}]: #{image} '#{title}'\n}
counter += 1
end
images + "{:.gallery}\n" +imagerefs + "\n"
end
content
end
# `content` is the post_content field for the row of the WordPress database query being looped
# `px` is a variable containing the table prefix in the WordPress database
# `db` is a Sequel.mysql object
if content =~ /\[gallery/
attachments = []
gquery =
"SELECT
posts.guid AS `attachment`,
posts.post_title AS `title`
FROM
#{px}posts AS `posts`
WHERE
posts.post_parent = '#{post[:ID]}' AND
posts.post_type = 'attachment'"
db[gquery].each do |a|
attachments << { 'url' => a[:attachment], 'title' => a[:title] }
end
replace_galleries(content, attachments) unless attachments.empty?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment