Easily restore your project to a previous version with our new Instant One-click Backup Recovery

Migrating from WordPress to Hygraph: A how-to guide

We’ll walk you through the key steps in transitioning from a traditional CMS to a headless one and show you how easily you can migrate your content from WordPress to Hygraph.
Malomo Demola

Malomo Demola

Jun 13, 2024
Migrating from WordPress to Hygraph: A how-to guide

You are not alone if you feel that the traditional CMSs you used to rely on, such as WordPress, Joomla, and Drupal, no longer meet your needs, especially when other technologies in your stack outgrow them. This means your CMS is holding you back from modernizing your stack.

The older a WordPress project is, for example, the more likely it is to cause problems. There may be too many plugins installed, and it's unclear what can be removed, or there may be too much outdated custom code that breaks every time you change it.

However, if you’ve stayed with a traditional CMS long enough, migrating to a headless CMS can seem like a leap of faith. As you migrate, you want to ensure you are doing everything right.

That's why in this post, we’ll walk you through the key steps in transitioning from a traditional CMS to a headless one and show you how easily you can migrate your content from WordPress to Hygraph.

For this walk-through, we will introduce you to Hygraph, a next-generation content platform that goes beyond headless CMS. It helps you power many-to-many relationships between different content sources and devices. We’ll use a WordPress news website as our traditional CMS to launch our content on Hygraph’s platform.

Editor's Note

Not sure whether to make the move to headless CMS? Check out Hygraph’s guide on why and how to select the best headless CMS for your needs. It will talk you through how to define your organization’s needs, address technological bottlenecks, and how a headless CMS can address your biggest challenges.

#Before we start

While headless CMS can help make development a breeze, migrating from a traditional CMS to a headless CMS can feel more like a challenging headwind. Thus, you’ll need a carefully planned migration strategy to make sure your content transfer is smooth sailing. You’ll need to follow a few important steps as you plan your content migration, but don’t worry, we’ll walk you through it step by step.

Start by downloading the files for our sample WordPress news website below. We’ve already exported these for you, but if you’re following along with your own WordPress site, you’ll need to install the WordPress data to XML/CSV plugin to facilitate the export.

Editor's Note

You might have to download assets manually to modify them further, as the plugin only exports the asset metadata.

Once you’ve got these files ready to go, we can set sail on our migration journey!

#Migrating to Hygraph’s headless CMS

This section shows five quick steps to migrating WordPress’s traditional CMS content to Hygraph’s headless CMS.

Step 1: Content audit

A comprehensive content audit will help you identify what needs to be migrated, archived, or updated. Assessing the content's volume, structure, and quality will inform the migration process on Hygraph.

To get started, you'll need to analyze the existing content on the sample news website and determine how it can be represented in Hygraph. In this case, we have a Post with associated Author(s). The Post has a Date, Title, and Author, while the Author has a Name and Location.

Sample news website

Step 2: Content mapping

It is important to carefully map out the data structure and relationships between elements in the existing CMS to consider how Hygraph’s features can represent them. Additionally, prioritizing the order of migration is important. For instance, in the case of our sample news website, migrating news Authors before their Posts is essential, as Posts will reference already created Authors.

With the audit in mind, you can map the audited content using Hygraph’s features. For the news website, you’ll create two models (Post and Author) with corresponding fields as shown below:

Content nameFieldField type
date (Post model)Single line text fieldDate
title (Post model)Single line text fieldString
Name (Author model)Single line text fieldString
Location ((Author model)Single line text fieldString

Furthermore, you must create a relationship between the Post and the Author models, linking the authors to their posts. Further details on this will be provided during the implementation step.

Step 3: Content export

Having a detailed migration plan outlining the methods to use (such as Hygraph’s UI or Management SDK), roles, and permissions is crucial. This is important because non-technical users can leverage Hygraph’s intuitive UI to facilitate migration, while technical users can utilize the SDK. Additionally, Hygraph provides flexibility in setting permissions, allowing users to collaborate on content and ship it as needed.

By default, WordPress will only allow you to export your data in XML format. You'll need to install a plugin to export it as CSV or in other formats. (You can skip this step if you’re using our provided CSV files from the introduction to this guide.)

Install plugin

In the admin panel, go to Plugins > Add New Plugin. Search for WordPress data to XML/CSV and install.

Install plugin

Export the data

On install, you’ll see a new All Export menu; click it, select the entity you want to export, and export.

Export data

Step 4: Set up the project on Hygraph

Log into your Hygraph console and create a project. Projects and associated contents on Hygraph are secure unless you explicitly define permissions. Since you’ll be importing contents into Hygraph, you must set the required permissions. To do this, navigate to the Project settings menu, under the API Access submenu, navigate to the Permanent Auth Token, click the “+ Add token” button, input the token name, and Add & configure permissions.

Add token Input token name and create

Next, you must update the created token permission to enable assets and content upload. Navigate to the Content API section, click the Yes, initialize defaults button, and modify the defaults by adding more permissions to perform operations, as shown below.

Add more permissions Added permissions

Similarly, navigate to the Management API section and initialize default permissions by clicking the Yes, initialize defaults button. Additionally, modify the permissions by adding the permission options for Update existing fields, Update existing models, and Update, as these options are not included in the default permissions and are needed for the migration process.

Modify default permissions Select and update

Step 5: Migrate the content to Hygraph (implementation step)

To get started, initialize an empty Node.js project by running the command below:

npm init -y

Install the required dependency.

npm i @hygraph/management-sdk csvtojson graphql-request dotenv
  • @hygraph/management-sdk is a helper that is used to execute operations without the UI.
  • csvtojson is a package for converting CSV data to JSON.
  • graphql-request is a minimal GraphQL client.
  • dotenv is a package for loading environment variables.

Next, update the package.json file by adding "type": "module". This will allow you to use the import statement in your code.

Set up the environment variables

Create a .env file in your project directory and add the snippet below:

HYGRAPH_ENDPOINT=<REPLACE WITH CONTENT API>
HYGRAPH_TOKEN=<REPLACE WITH PERMANENT TOKEN>

You can get the Content API and Token from your project settings.

Copy Content API Copy Token

Add sample data

Create a data folder and add the downloaded sample data.

Create the project schema

Before you move your data, you need to set up a structure to store it in Hygraph. Think of this as creating a table with columns to store your data in a database. In Hygraph, you'll use Model and Fields to define and represent your data.

To do this, create a src/schema-creation.js and add the snippet below:

import 'dotenv/config';
import {
Client,
SimpleFieldType,
RelationalFieldType,
} from '@hygraph/management-sdk';
const client = new Client({
authToken: process.env.HYGRAPH_TOKEN,
endpoint: process.env.HYGRAPH_ENDPOINT,
});
// create model for news post and authors
client.createModel({
apiId: 'Post',
apiIdPlural: 'Posts',
displayName: 'Post',
});
client.createModel({
apiId: 'Author',
apiIdPlural: 'Authors',
displayName: 'Author',
});
// add fields to post
client.createSimpleField({
apiId: 'title',
displayName: 'Title',
modelApiId: 'Post',
type: SimpleFieldType.String,
});
client.createSimpleField({
apiId: 'date',
displayName: 'Date',
modelApiId: 'Post',
type: SimpleFieldType.Date,
});
// add fields to author
client.createSimpleField({
apiId: 'name',
displayName: 'Name',
modelApiId: 'Author',
type: SimpleFieldType.String,
});
client.createSimpleField({
apiId: 'location',
displayName: 'Location',
modelApiId: 'Author',
type: SimpleFieldType.String,
});
// add relation to News for Author posts
client.createRelationalField({
parentApiId: 'Post',
apiId: 'author',
displayName: 'Written By',
type: RelationalFieldType.Relation,
reverseField: {
modelApiId: 'Author',
apiId: 'posts',
displayName: 'Posts',
isList: true,
},
});
client.run();

The snippet above does the following:

  • Imports the required dependencies
  • Creates a Post and Author models with required fields
  • Adds an Author relationship to the Post model and then run the migration

With that done, run the script in your terminal.

node src/schema-creation.js

You should see the created model and associated fields in your Hygraph console.

Model and Schema

Upload assets to Hygraph

To upload your asset, create an asset-upload.js file inside the src directory and add the snippet below:

import 'dotenv/config';
import { GraphQLClient, gql } from 'graphql-request';
import csv from 'csvtojson';
const client = new GraphQLClient(process.env.HYGRAPH_ENDPOINT, {
headers: {
authorization: `Bearer ${process.env.HYGRAPH_TOKEN}`,
},
});
function createImageMutation(data) {
const mutation = gql`
mutation assetUpload {
createAsset(
data: {
uploadUrl: "${data.url}"
}
) {
id
url
}
}
`;
return mutation;
}
const processQueue = async (data) => {
try {
console.log(`[PROCESSING]: ${data.id}`);
const assetMutation = createImageMutation(data);
await client.request(assetMutation).then((response) => {
console.log(response);
});
console.log(`[SUCCESS]: ${data.id}`);
} catch (error) {
console.error(`[ERROR]: ${data.id} - ${error.message}`);
}
};
const run = async () => {
try {
const data = await csv().fromFile('src/data/news_images.csv');
for (const obj of data) {
await processQueue(obj);
}
} catch (error) {
console.error(error);
}
};
run();

The snippet above does the following:

  • Imports the required dependencies
  • Creates a mutation to upload assets using the URL
  • Creates a helper function to use a queue to upload the assets and return appropriate responses
  • Converts the assets' sample data to JSON, loops through it, and uploads individual items

With that done, you can run the script and check the Hygraph console to see uploaded assets.

node src/asset-upload.js

Uploaded assets

Editor's Note

Depending on the size, you may need to wait a bit for uploaded assets to appear in the console (Uploaded assets must not be larger than 100MB).

Import contents

Next, you must upload sample data for the news website posts and their author. To do this, create a content-upload.js file inside the src directory and add the snippet below:

import 'dotenv/config';
import { GraphQLClient, gql } from 'graphql-request';
import csv from 'csvtojson';
const client = new GraphQLClient(process.env.HYGRAPH_ENDPOINT, {
headers: {
authorization: `Bearer ${process.env.HYGRAPH_TOKEN}`,
},
});
// Function to create the mutation for creating the author
function createAuthorMutation(authorData) {
const mutation = gql`
mutation createAuthor {
createAuthor(
data: {
name: "${authorData.name}"
location: "${authorData.location}"
}
) {
id
name
}
}
`;
return mutation;
}
// Function to create the mutation for creating a post
function createPostMutation(postData, authorId) {
const date = new Date(postData.date).toISOString();
const mutation = gql`
mutation createPost {
createPost(
data: {
title: "${postData.title}"
date: "${date}"
author: { connect: { id: "${authorId}" } }
}
) {
id
title
}
}
`;
return mutation;
}
const run = async () => {
const authorList = await csv().fromFile('src/data/news_author.csv');
const postList = await csv().fromFile('src/data/news_posts.csv');
let authorId = null;
// Create the author
const authorMutation = createAuthorMutation(authorList[0]);
await client.request(authorMutation).then((response) => {
authorId = response.createAuthor.id;
console.log(`Author created with ID: ${authorId}`);
});
// Create posts
postList.forEach((postData, index) => {
setTimeout(() => {
console.log(`Running mutation ${index + 1} of ${postList.length}`);
const postMutation = createPostMutation(postData, authorId);
client.request(postMutation).then((response) => {
console.log(response);
});
}, (index + 1) * 1000);
});
};
run();

The snippet above does the following:

  • Imports the required dependencies
  • Creates a GraphQL mutation for Post and Authors with corresponding fields
  • Creates a run function to get sample data, loops through the data, and uses it to create the required entity.

With that done, run the script and check Hygraph’s console for the uploaded contents.

node src/content-upload.js

Author Post

And that’s it! Now, your original content has found its new home in Hygraph’s headless CMS, where you won’t have to worry about your content getting left in the wake of technological shifts and slow lags to market.

#Beyond migration: Publishing content, caching, and integration with frontend

Hygraph allows you and your team to release content instantly or schedule it for later using either the intuitive UI or the API. When contents are published, you can access them from a wide range of applications across multiple platforms.

Published contents are delivered through Hygraph's globally distributed edge cache. When users query your Hygraph-powered applications, responses are cached across multiple data centers worldwide, resulting in a faster user experience. Additionally, Hygraph offers a High-Performance Content API.

High performance API

The endpoint also lets you distribute and integrate content across various front-end web and mobile frameworks and libraries. Explore this repository for integration examples; the complete source code can be found on GitHub.

#Wrap-up

Congratulations! You’ve now successfully migrated your traditional CMS content to Hygraph’s headless platform. (Or at least get some practice with the sample data we provided!) Migrating to a headless CMS is just the first step in taking your content to the next level. You can join the Slack community to stay updated on the latest developments and connect with fellow Hygraph developers. Plus, check out these guides on Migrating to Hygraph and Content modeling on Hygraph for more information.

Hygraph offers you the high-performance, futureproof severability your organization needs in the ever-evolving technological world. By migrating to Hygraph, you’re liberating your developers and unlocking your content’s greatest potential.

Download eBook: Future of Content

Insights from 400 tech leaders on CMS pain points and trends.

Download eBook

Blog Author

Malomo Demola

Malomo Demola

Technical Writer

Demola is an experienced product designer, software developer, and technical writer who is passionate about building products and creating engaging content. Beyond his professional career, Demola loves to cook, explore new places, and watch movies.

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.