Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify theme.liquid using Shopify API

I am looking to add a javascript snippet for some analytics across the store using the Shopify API. I figured out that using admin/themes/:id/assets.json I can modify the theme.liquid to insert snippet but this changes the entire content of the page. The current API call that I do is

admin/themes/35073539/assets.json
{
  "asset": {
    "key": "layout\/theme.liquid",
    "value": "{{content_for_header}}<script>console.log('foo')</script>"
  }
}

This obviously doesn't work.

I just want to modify the <head> tag and insert some custom javascript. Also, ScriptTag won't be useful as I have to take some input from user, use that input in my javascript and then insert the snippet. Any help would be appreciated.

like image 694
Archit Verma Avatar asked Feb 09 '23 19:02

Archit Verma


1 Answers

First you want to get a list of all assets to make sure you are using the right ID in the Endpoint URL. (the long number before /assets.json)

GET /admin/themes/#{id}/assets.json

Then you want to save a copy of the current file to the server as a backup, just to be safe...

PUT /admin/themes/#{id}/assets.json
{
  "asset": {
    "key": "layout\/theme.bak.liquid",
    "source_key": "layout\/theme.liquid"
  }
}

Since the method you are using overwrites the existing file, you need to download the current file, pull the HTML into a javascript variable, modify that HTML, then send the HTML back as you were doing above.

First download theme.liquid....

GET /admin/themes/#{id}/assets.json?asset[key]=layout/theme.liquid&theme_id=828155753

This will return the HTML etc.. for that file, you need to add/change the content of this file and then send that content as you were already ...

PUT /admin/themes/#{id}/assets.json
{
  "asset": {
    "key": "layout\/theme.liquid",
    "value": "*****The HTML FOR THEME.LIQUID"
  }
}

And that should do it. If it's successful the code should now be added.

Hope this helps, let me know if you have any questions.

like image 179
Tech Savant Avatar answered Feb 12 '23 09:02

Tech Savant