Introduction

If you’re like me and love working with Ghost CMS, you know how flexible and powerful it is. Recently, I decided to refresh the look of my blog by changing the theme. However, I quickly realized that many of my older blog posts weren’t using the correct post template. Rather than manually updating each post, I turned to the Ghost CMS API to automate the process.

In this blog post, I'll share my journey and the script I developed to analyze and automatically update blog post templates to match my new theme.

The Challenge

Ghost CMS allows you to assign custom templates to posts, making it easy to tailor the look and feel of individual pages. However, when you switch themes or standardize templates across your blog, updating every post manually can be time-consuming and error-prone.

The Solution

By leveraging the Ghost CMS Content API, I created a script to:

  1. Analyze all blog posts and identify those not using the desired template.
  2. Automatically update these posts to use the correct template.

The Script

Here's the updated script that not only identifies mismatched templates but also fixes them using the Admin API:

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

// 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
});

const adminApi = new GhostAdminAPI({
  url: 'https://your-ghost-cms-url.com', // Your Ghost CMS URL
  key: 'your-admin-api-key', // Your Admin API key
  version: "v5.0" // API version
});

// Desired template name
const desiredTemplate = 'custom-post-classic';

// Function to analyze and update post templates
async function updatePostTemplates() {
  let allPosts = [];
  let page = 1;

  try {
    while (true) {
      // Fetch posts page by page
      const posts = await contentApi.posts.browse({
        limit: 5,
        page: page,
        include: 'tags,authors',
      });

      if (posts.length === 0) break;

      allPosts = allPosts.concat(posts);
      page++;
    }

    let updatedCount = 0;
    for (const post of allPosts) {
      const currentTemplate = post.custom_template || 'Default Template';

      // Check if template needs updating
      if (currentTemplate !== desiredTemplate) {
        console.log(`Updating post: ${post.title} (Current template: ${currentTemplate})`);

        // Update the post template using Admin API
        await adminApi.posts.edit({
          id: post.id,
          custom_template: desiredTemplate,
          updated_at: post.updated_at,
        });

        updatedCount++;
      }
    }

    console.log(`\nTotal posts analyzed: ${allPosts.length}`);
    console.log(`Posts updated to '${desiredTemplate}': ${updatedCount}`);
  } catch (err) {
    console.error('Error processing posts:', err);
  }
}

updatePostTemplates();

Setup: Installing Required Packages

Before running the script, you'll need to install the required Node.js packages. In your project directory, run the following command to install the Ghost Content API and Admin API packages:

npm install @tryghost/content-api @tryghost/admin-api

These packages will allow you to interact with your Ghost CMS instance and update the post templates programmatically.

How It Works

  1. Fetch Posts: The script uses the Content API to retrieve all blog posts, including metadata like tags and authors.
  2. Analyze Templates: It checks the custom_template field of each post to determine its assigned template.
  3. Update Templates: If a post doesn’t match the desired template, it updates the post using the Admin API.

Final Thoughts

Working with Ghost CMS has been super easy, and its APIs have empowered me to manage my blog with ease. If you're using Ghost CMS and want to standardize your templates, I hope this script saves you time and effort.

Do you have a favorite Ghost CMS trick or a challenge you'd like to solve? Share it in the comments - I’d love to hear from you!

Happy blogging!

Share this post