Introduction

Alt tags are essential for accessibility and SEO, yet they’re often overlooked when managing blog content. Recently, I realized many images on my blog lacked alt tags. To address this, I wrote a script using the Ghost CMS API and Cheerio to identify posts with missing alt tags and log the results.

In this article, I’ll share the process and script to help you streamline this task on your own Ghost blog.

Why Alt Tags Matter

Alt tags serve two critical purposes:

  • Accessibility: They provide descriptive text for screen readers, making content more inclusive for visually impaired users.
  • SEO: Alt tags help search engines understand image content, contributing to improved search rankings.

Missing alt tags can negatively impact both user experience and discoverability. By identifying and addressing missing alt tags, you ensure your blog is accessible and optimized.

The Script

Here’s the Node.js script I used. It fetches all posts from your Ghost CMS, scans the HTML for image tags, and checks if the alt attribute is missing or empty. I excluded card-specific images since Ghost CMS currently doesn’t allow adding alt tags to them.

const GhostContentAPI = require('@tryghost/content-api');
const cheerio = require('cheerio');

// Replace with your Ghost CMS details
const contentApi = new GhostContentAPI({
  url: 'https://your-ghost-cms-url.com', // Your Ghost CMS URL
  key: 'your-content-api-key', // Your Content API key
  version: "v5.0" // API version
});

async function checkImagesWithoutAlt() {
    try {
        // Fetch all posts
        const posts = await contentApi.posts.browse({ limit: 'all', fields: 'title,html,url' });
        const results = [];
        let postsWithMissingAlts = 0;

        posts.forEach(post => {
            const $ = cheerio.load(post.html); // Parse the post's HTML
            const images = $('img'); // Select all image tags
            let imagesWithoutAltCount = 0;
            const missingAltLinks = [];

            images.each((index, img) => {
                const alt = $(img).attr('alt');
                const src = $(img).attr('src');
                const parent = $(img).closest('.kg-card.kg-header-card'); // Exclude certain card images

                if (!parent.length && (!alt || alt.trim() === '')) {
                    imagesWithoutAltCount++;
                    if (src) {
                        missingAltLinks.push(src); // Collect image URLs without alt tags
                    }
                }
            });

            if (imagesWithoutAltCount > 0) {
                postsWithMissingAlts++;
                results.push({
                    title: post.title,
                    url: `${post.url}edit`,
                    count: imagesWithoutAltCount,
                    missingAltLinks
                });
            }
        });

        // Sort by posts with the most missing alt tags
        results.sort((a, b) => b.count - a.count);

        // Log the results
        console.log('🖼️ Posts with Missing Image Alt Tags:');
        results.forEach(result => {
            console.log(`🔗 Post: ${result.title}`);
            console.log(`🔍 Edit URL: ${result.url}`);
            console.log(`❌ Images Missing Alt Tags: ${result.count}`);
            result.missingAltLinks.forEach(link => console.log(`   - ${link}`));
            console.log('');
        });

        // Print summary statistics
        console.log('📊 Summary Statistics:');
        console.log(`✅ Total Posts Checked: ${posts.length}`);
        console.log(`❌ Posts with Missing Alt Tags: ${postsWithMissingAlts}`);
        console.log(`🎯 Percentage: ${((postsWithMissingAlts / posts.length) * 100).toFixed(2)}%`);
    } catch (err) {
        console.error('Error fetching posts:', err);
    }
}

checkImagesWithoutAlt();

Setup and Usage

  1. Install the required packages:
npm install @tryghost/content-api cheerio
  1. Replace placeholders: Update the url and key values in the script with your Ghost CMS details.
  2. Run the script: Execute the script with Node.js:
node checkImagesWithoutAlt.js

Results

The script outputs:

  • The total number of posts checked.
  • Posts with missing alt tags, including the number of missing tags and the images’ URLs.
  • A percentage summary for quick insights.
📊 Summary Statistics:
✅ Total Posts Checked: 73
❌ Posts with Missing Alt Tags: 56
🎯 Percentage of Posts with Missing Alt Tags: 76.71%

Next Steps

Once you have the results, you can manually edit the posts in Ghost CMS to add meaningful alt tags. This improves accessibility and enhances the overall quality of your blog.

If you’re managing a large number of posts, consider automating the addition of alt tags using AI or predefined rules in a future project.

Share this post