Skip to content

Instantly share code, notes, and snippets.

@digitalbricklayer
Last active October 19, 2020 09:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save digitalbricklayer/7d90eb578cd14a13ca03dda469a8692e to your computer and use it in GitHub Desktop.
Simple Python scriptl for exporting Wordpress posts as Hugo posts. The script reads the posts from the database and exports the resulting Hugo posts to the output directory.
import mysql.connector
from datetime import datetime
class Post:
"""A wordpress blog post."""
def __init__(self, post_id, title, slug, content, created_at):
self.post_id = post_id
self.title = title.encode("utf-8")
self.slug = slug
self.content = content.encode("utf-8")
self.created_at = created_at
wordpress_db = mysql.connector.connect(
host="localhost",
user="<<db user>>",
password="<<db password>>",
database="<<database name here>>"
)
db_cursor = wordpress_db.cursor()
db_cursor.execute("select wp_posts.ID,wp_posts.post_title,wp_posts.post_date_gmt,wp_posts.post_name,wp_posts.post_content from wp_posts where 1=1 and wp_posts.post_type = 'post' and (wp_posts.post_status = 'publish') order by wp_posts.post_date desc;")
post_results = db_cursor.fetchall()
all_posts = []
for post_result in post_results:
post = Post(post_result[0], post_result[1], post_result[3], post_result[4], post_result[2])
all_posts.append(post)
for post in all_posts:
post_file = open("./output/" + post.slug + ".md", "w")
print >>post_file, "---"
print >>post_file, "title: " + "\"" + post.title + "\""
print >>post_file, "date: " + "\"" + post.created_at.strftime("%Y-%m-%dT%H:%M:%S+00:00") + "\""
print >>post_file, "categories: []"
print >>post_file, "tags: []"
print >>post_file, "---"
print >>post_file, ""
print >>post_file, post.content
post_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment