Roswell Studios

139 Fulton Street, Ste 132
New York, NY 10038

Shopify images for blog posts

— February 16, 2018

It is unfortunate that the Files doesn’t have an upload API that people have been asking for for at least 4 years, and apparently existed at one point.

Here’s a sample solution for when you have copied the blog posts (there are several apps that do that), but now the linked images don’t work. You will need to put the images somewhere. One could use the Shopify Settings Files upload to manually upload the files. Or get another hosting service for just images so the directory structure can stay the same and you can do bulk uploads. Amazon S3 is a good solution for that. One note: you will need an https host.

Either way, there’s still the issue of changing all the img src links in years of blog posts. You could do that by hand, but here’s a sample javascript to do that for you. (NOTE: never execute random scripts in your admin page’s console without understanding what they do. You will need to edit this to fit your site, so it needs some Javascript knowledge. If you do hire a developer, this will at least save them some time.)


var blogid = '1234567';//copy this number off the url when you are looking at the admin "Edit blog" page
var replaceFrom = 'https://www.oldsite.com/wp-content/uploads/';
var replaceTo = 'https://cdn.shopify.com/s/files/1/1234/4321/files/';
var page = 1;
var looper = true;
while(looper) {
$.ajax({
async: false,
url:'/admin/blogs/'+blogid+'/articles.json',
data:{fields:'id,body_html', limit:50, page:page},
dataType : 'json',
error: function () {looper=false;},
success: function(data) {
if (!data.articles || data.articles.length==0) {
looper = false;
}
$.each(data.articles, function (i, art){
var body_html = art.body_html.split(replaceFrom).join(replaceTo);

//any other edits to body_html here, for example Shopify search links:

//body_html = body_html.replace(/\/catalogsearch\/result\/\?q=(.*?)\&.*?"/g, '/search?q=$1"');

if (art.body_html != body_html) {
$.ajax({
method: 'PUT',
async: false,
url:'/admin/blogs/'+blogid+'/articles/'+art.id+'.json',
data:{article:{body_html:body_html}},
dataType : 'json',
error: function () {looper=false;}
})
}
})
}
});
page = page +1 ;
if (page > 100) {//some reasonable max number
looper = false;
}
}

Back to all