Shopify Tutorial: Easy Captions for Images in Blog Posts and Pages using Alt Text
In this tutorial, we’re going to write some script that will automatically generate captions for images on blog posts and pages in Shopify using the image’s alt tag.
I wrote this quick tutorial because I was seeing a lot of questions in the forums about how to captions to blog posts. Instead of having customers add captions manually (which would require knowledge of HTML/CSS), I think this method is a lot easier as you can just insert alt text to images through the RTE.
You can see a demo of this here.
How it works
The script works by checking the alt text of every image in a blog article of page. If that image has an alt tag, the script will wrap the it in an <figure> tag and append a <figcaption> tag containing the alt tag of the image.
We’re also going to be adding some nice theme settings to spice up the captions 🙂
Let’s get started!
Adding alt text to an image
If you’re unsure of how to add alt text via the RTE, here’s a quick refresher.
Go to a page or blog article, and in the RTE click Insert > Image. Browse your computer for an image of your choice and click the “Insert Image” button.
Once you’ve added the image, click on it and you’ll see a little “edit” link at the bottom. Click on “edit” to open up that image’s options. You can then enter some text to describe the image in the “Description” field. This becomes the alt text of the image.
1. Wrap the page and/or article content with a unique div
The first step is to wrap the RTE content with a div that has a unique class so that we can target it with jQuery. It’s up to you whether you want the captions to show in the blog articles *and* pages. Refer to the list below to see which Liquid variable you need to look for in which template.
- page.liquid – {{ page.content }}
- blog.liquid – {{ article.content }}
- article.liquid – {{ article.content }}
We’re going to be wrapping the page/article content with a special div class called “caption”. Below is an example of wrapping the page content in page.liquid of the Radiance theme.
Before:
{{ page.content }}
After:
{{ page.title }}
{{ page.content }}
2. Add the jQuery and CSS Snippet
Create a new snippet called “captions”. Add the content of this gist.
At the bottom of theme.liquid, you should see a closing </body> tag. Right above it, place the following code in red:
{% include 'captions' %}