lewisdale.dev/src/blog/posts/2023/1/import-posts-from-an-rss-feed-into-wordpress.md
2023-12-26 14:35:09 +00:00

2.1 KiB

title date slug
Import posts from an RSS feed into WordPress 2023-01-07T22:15:06 import-posts-from-an-rss-feed-into-wordpress

I decided to migrate my blog to Wordpress, for the simple reason that I was finding updating Markdown files manually a headache, and I want to be able to write on devices that aren't my laptop.

But first I had to move my content over - so I used the Wordpress REST API to copy my content from my RSS feed.

Create an application password

In your Wordpress admin panel, go to Users -> Profile. Scroll down to the section that says "Application passwords", generate a new one, copy and store it somewhere.

## Consuming the feed and populating Wordpress

I used Deno to do this, but the code would be pretty similar for Node:

import { parse } from "https://deno.land/x/xml@2.0.4/mod.ts";

const root = `${process.env.WP_SITE_URL}/wp-json/wp/v2/posts`;
const password = process.env.WP_APP_PASSWORD; // This is your application password
const user = process.env.WP_USER; // This is the username of the user the application password belongs to
const auth = btoa(`${user}:${password}`);

const response = await fetch(process.env.SOURCE_RSS_FEED);
const feed = await response.text();
const document = parse(feed);

for (const entry of document.feed.entry) {
	const body = {
        title: entry.title,
        content: entry.content["#text"],
        status: 'publish',
        date: entry.published,
    };
	
	const res = await fetch(root, {
        method: "POST",
        body: JSON.stringify(body),
        headers: {
            "Authorization": `Basic ${auth}`,
            "Content-Type": "application/json",
        }
    });
    if (res.status >= 400) {
        console.error(`Request failed with status ${res.status}: ${res.statusText}`);
        console.error(await res.text());
    }
}

Screenshot of the website home page. Shows the title "LewisDale.dev" and a menu with Home, Blog, and Microblog options.