Published
- 19 min read
WordPress to Astro Full Migration: Easy Step-by-Step Guide
Key Takeaways
- ✨ Understand the benefits of migrating from WordPress to Astro, including cost savings and improved performance.
- ✨ Learn the step-by-step process for a full migration, including content transfer and setting up a new CMS.
- ✨ Access useful scripts and tools for automating parts of the migration process.
Photo by Jonas Verstuyft on Unsplash
Advertisement
Welcome back! If you’ve read my previous blog on why I decided to migrate from WordPress to Astro, you’re probably eager to learn how to make the switch yourself. This guide is here to walk you through the process, step by step. For those who haven’t yet explored the reasons behind my decision, I recommend checking out my earlier article on Why I Migrated from Wordpress to Astro. It will help you decide if migrating to Astro is the right move for your blog. Plus, by making the switch, I managed to save almost $125 a year on hosting costs. Now, let’s dive into the “how” and get your blog running smoothly on Astro!
Two Choices for Migration
When you’re ready to migrate from WordPress to Astro, you have two primary paths to consider:
- Full Migration: This option involves transferring all your content and images to Astro, while adopting an open-source CMS. This approach allows you to fully transition away from WordPress, giving you complete control over your site and reducing hosting expenses. Spoiler Alert! It’s the path I chose, and it has been incredibly rewarding.
- Hybrid Approach: With this method, you continue using WordPress as your CMS for content management, but switch to Astro for the frontend. While this can be a viable option, it doesn’t completely eliminate the costs associated with WordPress hosting.
I opted for the full migration because it provided me with greater autonomy over my website and significant cost savings. The process involved carefully migrating each piece of content, ensuring that all images and media were correctly transferred, and setting up a new CMS that suited my needs. Although it required some effort and planning, the benefits of having a fully independent site were well worth it. The freedom to make changes without relying on WordPress’s limitations.
Framework Choices
Astro provides an exceptional level of flexibility, making it possible to integrate a variety of frameworks to meet your specific blogging requirements. Whether you prefer using React, Vue, or Svelte, Astro supports them all, allowing you to choose the framework that best aligns with your development style and project goals. During my transition to Astro, I opted to utilize Astro with MDX, which combines Markdown with JSX, to simplify and enhance my blogging workflow. This choice allowed me to write content in Markdown while still having the flexibility to include interactive components using JSX.
For the styling of my blog, I decided to incorporate Tailwind CSS, a utility-first CSS framework that significantly streamlined the design process. By using Tailwind CSS, I was able to quickly apply styles without writing extensive custom CSS, which saved time and effort. Additionally, I took advantage of some pre-designed themes and templates, which provided a solid foundation and helped me achieve a polished, professional look for my blog right from the start. This combination of tools and frameworks not only improved my writing experience by making it more efficient and enjoyable but also ensured that my blog had a modern and responsive design, capable of delivering a great user experience across different devices and screen sizes.
Prerequisites
Before you begin the migration process, ensure you have the following tools and resources ready.
- Node.js (
v18.17.1
orv20.3.0
or higher): Make sure you have Node.js installed on your computer. It’s a JavaScript runtime that you’ll need for running Astro. You can download it from the official Node.js website. - Package Manager: Choose a package manager like npm, pnpm, or yarn. These tools help you manage the software packages you’ll use in your project. npm comes bundled with Node.js, so it’s a good starting point.
- Git: Install Git, a version control system that helps you track changes in your project files. It’s essential for collaborating and managing your code. You can download it from the official Git website.
- Text Editor: Have a text editor ready, such as VS Code or Sublime Text. These editors make it easier to write and edit your code. VS Code is recommended with the official Astro Extension installed.
- Terminal: Get comfortable with basic command line operations, as you’ll use the terminal to run commands and manage your project, with many beginner tutorials available online if you’re new to this.
With these prerequisites in place, you’ll be well-prepared to start your migration journey from WordPress to Astro.
Migration Steps
In this section, I’ll walk you through each step I took to successfully transition my 4techloverz blog. Whether you’re a seasoned developer or a complete beginner, these clear and concise instructions will help you navigate the migration with confidence. Let’s get started!
Export Content from WordPress
The first thing I did when migrating this blog from WordPress to Astro was to export all my existing content. This step provided me with XML files that contained all my posts, pages, and media. Here’s how I went about it:
- Logged into My WordPress Dashboard: I started by logging into my WordPress admin panel, which I accessed by adding
/wp-admin
to my site’s URL. - Navigated to the Tools Section: In the left-hand menu, I found and clicked on
Tools
which brought up a dropdown menu. - Selected Export: From the dropdown, I clicked on
Export
. This took me to the export page where I could choose what content to export. - Chose What to Export: I had the option to export all content or select specific types like posts, pages, or media. For a full migration, I chose
All content
. - Downloaded the Export File: I clicked the
Download Export File
button, and WordPress generated an XML file with my selected content. I saved this file to my computer. - Verified the Export: After downloading, I opened the XML file with a text editor to ensure it contained all my content. This step was optional, but I did it to confirm the export was successful.
Woohoo! We’ve just exported our content like pros! This is the first big leap towards our new blogging adventure. Keep that energy up—we’re doing awesome!
Convert XML to Markdown
After exporting my content from WordPress, the next step was to convert the XML files into Markdown format, which is more compatible with Astro. Here’s how I accomplished this using an open-source library (wordpress-export-to-markdown):
- Open Terminal in the XML File’s Folder: I navigated to the folder containing my exported XML file and opened the terminal there.
- Run the Conversion Command: There’s no need to manually download or clone the tool on our machine. I used the below npx command to run the package directly.
npx wordpress-export-to-markdown
- Answer the Prompt Questions: During the conversion, the tool might ask you some questions about how you want to export your content. I answered these based on my preferences for the output format. No matter how you export, just ensure you have all the markdown files and images.
- Verify the Markdown Files: Once the conversion was complete, I checked the output directory to ensure all my content was successfully converted into Markdown files. I opened a few files to verify that the formatting and content were correct.
High five for converting to Markdown! We’re getting closer to a more flexible and fun blogging experience. Keep rocking it—we’re on fire!
Convert Markdown to MDX
Once I had my content in Markdown format, the next step was to convert these files into MDX, which allows for more dynamic content integration with Astro. Here’s how I handled this conversion:
- Decide on Conversion Method: I had two options for converting my
.md
files to.mdx
files. I could either manually rename each file or use a script to automate the process. - Manual Conversion: If you prefer a hands-on approach, you can manually change the file extension of each
.md
file to.mdx
. This method is straightforward but can be time-consuming if you have many files. - Bulk Conversion with a Script: To save time, I opted for a script that could convert all the files in bulk. You can name the script
convert-md-to-mdx.js
. Here’s a simple script you can use:
Place the convert-md-to-mdx.js
script in the folder where all the .md
files are located, or provide the path to the markdown files when running the command. This script goes through all the .md
files in the directory and renames them to .mdx
.
// convert-md-to-mdx.js
const fs = require('fs')
const path = require('path')
// Get the directory path from command line arguments or use cwd
const directoryPath = path.resolve(process.argv[2] || process.cwd())
// Function to convert .md files to .mdx
function convertMdToMdx(directory) {
fs.readdir(directory, (err, files) => {
if (err) {
return console.error('Unable to scan directory: ' + err)
}
files.forEach((file) => {
const filePath = path.join(directory, file)
const fileExtension = path.extname(file)
if (fileExtension === '.md') {
const newFilePath = filePath.replace(/\.md$/, '.mdx')
fs.rename(filePath, newFilePath, (err) => {
if (err) {
console.error('Error renaming file:', err)
} else {
console.log(`Renamed: ${file} -> ${path.basename(newFilePath)}`)
}
})
}
})
})
}
// Call the function
convertMdToMdx(directoryPath)
- Run the Script: Open your terminal, navigate to the directory containing your
convert-md-to-mdx.js
script, and execute the following command:
node convert-md-to-mdx.js
NOTE (Optional): If the script is not in the same folder as the markdown files, pass the relative path in the command like this:
node convert-md-to-mdx.js ./path/to/md/files
- Verify the Conversion: After running the script, check the directory to ensure all files have been successfully converted to
.mdx
. Open a few files to confirm that the content remains intact.
We’ve nailed the MDX conversion! This is where the magic happens, opening up a world of dynamic content. Our blog is transforming beautifully—stay pumped!
Initialize Astro Project
To kickstart your migration to Astro, you’ll need to initialize a new Astro project. This involves setting up a project based on a theme or template that suits your needs. Here’s how you can do it:
- Choose a Theme/Template: Decide whether you want to use a pre-existing template or create a custom one. For my project, I used a template that was well-suited for blogging. The template I used is danielcgilibert/blog-template.
- Run the Initialization Command: Open your terminal and navigate to the directory where you want to create your Astro project. Then, run the following command to initialize the project:
To initialize an Astro project using the same template I used from the GitHub repository, you can use the following command:
- Complete the Setup: Follow the remaining prompts to complete the setup process. This will include naming your project and configuring any initial settings.
- Verify the Setup: Once the setup is complete, navigate into your new project directory and run the development server to ensure everything is working correctly:
Your Astro project should now be running locally (http://localhost:4321/
), ready for you to start integrating your content.
Boom! Our Astro project is up and running! We’ve set a solid foundation for our blog’s new home. The sky’s the limit—keep building our dream!
Copy MDX Content Files
After converting your Markdown files to MDX and initializing the Astro project, the next step is to organize them within your Astro project. Here’s how to do it:
-
Access the Content Directory: Within your Astro project, find the
src/content/blog
directory. This is where your blog content should go.The path might vary slightly depending on the template you used. If you used the same template as I did, the path will be the same.
-
Copy the MDX Files: Move or copy all your
.mdx
files into thesrc/content/blog
directory. You can do this using your file explorer. -
Verify the File Placement: Once copied, double-check the
src/content/blog
directory to ensure all your.mdx
files are correctly placed. This will ensure that your blog content is properly integrated into your Astro project.
Our MDX files are all set and ready to dazzle! Our content is about to shine brighter than ever. Keep that momentum going—we’re unstoppable!
Copy Images
To ensure your blog’s visual content is properly integrated into your Astro project, you’ll need to organize your images. Here’s how to do it:
-
Access the Assets Directory: Within your Astro project, locate the
src/assets/images
directory. This is the designated folder for storing your blog’s images.If the path doesn’t exist in your template, you can create these folders. However, if you use the same template, it will already be there.
-
Copy the Images: Move or copy all your images into the
src/assets/images
directory. -
Verify the Image Placement: Once copied, double-check the
src/assets/images
directory to ensure all your images are correctly placed. This will ensure that your visual content is properly integrated into your Astro project.
Our images are in place, adding that perfect splash of color to our blog. It’s all coming together beautifully—great job!
Update Image References
After organizing your images in the Astro project, the next crucial step is to update the image paths in your blog posts. This ensures that all images display correctly on your site. Here’s how to do it:
-
Open Your MDX Files: Navigate to the
src/content/blog
directory where your.mdx
files are stored. Open each file in a text editor to update the image paths.The path might vary slightly depending on the template you used. If you used the same template as I did, the path will be the same.
-
Identify Old Image Paths: Look through your blog posts to find any references to images. These paths will likely point to the old location where your images were stored.
-
Update the Paths: Change each image path to point to the new location in the
src/assets/images
directory. For example, if an image was previously referenced as![Alt Text](old/path/image.jpg)
, update it to:
![Alt Text](/src/assets/images/image.jpg)
- Verify the Updates: After updating the paths, save the changes to each
.mdx
file. It’s a good idea to preview your blog posts locally to ensure all images are displaying correctly. - Repeat for All Posts: Make sure to update the image paths in all your blog posts to ensure consistency across your site.
We’ve updated those image paths like champs! Our visuals are now perfectly aligned and ready to impress. We’re almost at the finish line—keep it up!
Personalize the Blog Setup
This step is optional and should be followed in the same way only if you used the same template I did.
After initializing the project, I made a few updates to customize the template to fit my blog:
-
Configure: I edited the configuration file
src/data/site.config.ts
to set up the basic blog metadata, ensuring it reflected my blog’s identity. -
Update Domain: I updated the
astro.config.mjs
file located at the root of the project with my own domain, making sure all references were correct. -
Modify Public Files: In the
/public
folder, I made several changes:- Favicon: I replaced the default favicon with one that represents my blog.
- robots.txt: I updated the Sitemap URL to point to my own domain, ensuring search engines could find my content.
- Open-Graph: I customized the open-graph image, which is displayed when sharing the blog link. For individual posts, the preview image is the post cover.
-
Edit Social Networks: In the Header component (
src/components/Header.astro
), I changed the URLs to link to my social network profiles, making it easy for readers to connect with me.
Update Frontmatter Values
This step is optional and should be followed in the same way only if you used the same template I did.
I had to update the frontmatter to match the structure required by your Astro template I used. Here’s how I updated the frontmatter for my blog posts:
- Identify the Differences: The converted Markdown files had a frontmatter structure like this:
---
title: 'Top 12 Games Like GTA 6 You Should Try before 2025'
date: '2023-12-06'
categories:
- 'alternatives'
- 'latest-articles'
- 'list-of-best'
- 'pc-games'
tags:
- 'gta'
- 'gta-6'
- 'gta-vi'
coverImage: 'GTA-6.webp'
---
- Update to Match Template Requirements: I modified the frontmatter to align with the template’s structure, which looked like this:
---
title: Top 12 Games Like GTA 6 You Should Try before 2025
description: >-
Explore 12 alternative games to Grand Theft Auto 6, featuring immersive graphics, engaging narratives,
and open-world gameplay to keep you entertained until GTA 6's release in 2025. Includes trailers and descriptions.
pubDate: '2023-12-06'
heroImage: /src/assets/images/GTA-6.webp
category: Top Picks
tags:
- gta
- gta-6
- gta-vi
---
-
Make the Necessary Changes: Update each file’s frontmatter by:
- Adding a
description
field to provide a brief overview of the content. - Changing
date
topubDate
. - Renaming
coverImage
toheroImage
and updating the path to match the new image directory. - Simplifying
categories
to a singlecategory
field.
- Adding a
-
Verify the Updates: After making these changes, ensure that the frontmatter is correctly formatted and that all necessary fields are included. This will help maintain consistency across your blog and ensure compatibility with your Astro template.
Add a New Category
This step is optional and should be followed in the same way only if you used the same template I did.
To add a new category to your blog, you need to update the src/data/categories.ts
file by adding the new category to the array. Here’s how you can do it:
- Open the Categories File: Navigate to the
src/data/categories.ts
file in your Astro project. - Add the New Category: Locate the
CATEGORIES
array and add your new category to the list. For example:
// src/data/categories.ts
export const CATEGORIES = [
'JavaScript',
'React',
'new category here' // <--- Add your new category here
] as const
- Ensure Consistency: Make sure that all categories used in your blog posts are added here. The categories are case-sensitive, so ensure that the spelling and capitalization match exactly with those used in your markdown documents.
- Understand Zod Validation: Be aware that Zod, a schema validation library, checks whether the category is correctly written and exists in the properties of the markdown document. If the category is not correctly added or does not exist, Zod will throw an error when building the application.
Start the Development Server
Once you’ve set up your Astro project and organized your content, the next step is to start the development server. This allows you to preview your site locally and ensure everything is functioning as expected. Here’s how to do it:
- Open Your Terminal: Navigate to the root directory of your Astro project using your terminal.
- Run the Development Server Command: Execute the following command to start the development server:
This command will compile your project and start a local server.
- Access Your Local Site: Once the server is running, open your web browser and go to the following URL to view your site:
http://localhost:4321/
- Verify the Site: Browse through your site to ensure all pages and content are displaying correctly. Check for any issues with layout, images, or links.
- Make Adjustments as Needed: If you notice any problems, you can make changes to your project files and the development server will automatically update to reflect those changes.
Our site is live locally, and it’s looking fantastic! Take a moment to enjoy seeing our hard work come to life. We’re doing amazing—keep smiling!
CMS Integration
If you used the same template I did, it comes with Tina CMS, which is hosted locally and is free to use. Tina CMS provides a user-friendly interface for managing your content directly within your Astro project. However, if you prefer a different approach, you can remove it, as I did. I switched to using Frontmatter in VSCode, which integrates seamlessly with my workflow and offers a straightforward way to manage content. If you’re interested in making a similar switch, I’ll be writing a blog on how to set up and use Frontmatter in VSCode, and I’ll link it here once it’s ready.
Deployment Choices
When it comes to deploying your Astro site, you have several robust options to consider, each with its own set of features and benefits. Popular platforms include Vercel, Netlify, and Cloudflare Pages. These platforms offer seamless integration with Astro, making the deployment process straightforward and efficient.
Vercel is known for its ease of use and excellent support for frontend frameworks, providing automatic deployments and previews for every push. Netlify offers a powerful suite of tools for continuous deployment, serverless functions, and form handling, making it a versatile choice for developers. Cloudflare Pages stands out with its global CDN and edge network, ensuring fast load times and high availability.
I plan to write a detailed blog on deploying an Astro site to Cloudflare Pages efficiently. This is particularly important because all platforms have limited build minutes (500), and if your blog site has a lot of images that need optimization, it can consume a significant amount of build time. Initially, my site’s build time was 30 minutes, but I managed to reduce it to just 3 minutes per build. This optimization not only saves time but also resources, allowing for more frequent updates and a smoother workflow. I’ll share the strategies and techniques I used in an upcoming blog post and will link it here once it’s ready. Stay tuned for insights on optimizing your deployment process to make the most of your chosen platform.
Conclusion
Migrating my blog from WordPress to Astro was a game-changer. It boosted my site’s performance, cut down on maintenance, and saved me money. If you’re thinking about making the switch, I hope this step-by-step guide helps you out. Stay tuned for more tutorials on optimizing and deploying your Astro site. If you have any questions or need assistance with your migration, feel free to reach out!
Thank you for being part of this journey. Your support and engagement mean so much to me. If you have any questions or need help with your own transition, please don’t hesitate to reach out. I’m here to help and share what I’ve learned along the way.
Exciting Upcoming Astro Tutorials
I’m thrilled to let you know that I’ll be sharing a series of detailed tutorials to help you get the most out of your Astro blog setup! These resources will cover everything you need to take your blog to the next level. From deploying your site efficiently to optimizing images and setting up Frontmatter CMS, I’ve got you covered. I’ll also share tips on how to cut down build times from a long 30 minutes to a speedy 3 minutes, making your workflow as smooth as possible. Be sure to check out my previous blog post on “Why I Migrated to Astro” or look under the Astro tag for these exciting tutorials. I can’t wait to share these insights with you and help you make the most of your Astro blogging journey! Stay tuned!
Advertisement