-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordpress_import.py
More file actions
65 lines (55 loc) · 2.3 KB
/
Copy pathwordpress_import.py
File metadata and controls
65 lines (55 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""aiseed web creator — WordPress WXR インポート"""
import re
import xml.etree.ElementTree as ET
def import_wordpress_xml(xml_path):
"""WordPress WXR (eXtended RSS) をパースしてブログ記事リストを返す"""
tree = ET.parse(xml_path)
root = tree.getroot()
ns = {
"content": "http://purl.org/rss/1.0/modules/content/",
"wp": "http://wordpress.org/export/1.2/",
"dc": "http://purl.org/dc/elements/1.1/",
"excerpt": "http://wordpress.org/export/1.2/excerpt/",
}
# WXRバージョンが異なる場合のフォールバック
for ver in ["1.0", "1.1", "1.2"]:
ns_wp = f"http://wordpress.org/export/{ver}/"
if root.find(f".//{{{ns_wp}}}wxr_version") is not None:
ns["wp"] = ns_wp
ns["excerpt"] = f"http://wordpress.org/export/{ver}/excerpt/"
break
posts = []
for item in root.findall(".//item"):
post_type = item.findtext(f"{{{ns['wp']}}}post_type", "post")
if post_type != "post":
continue
status = item.findtext(f"{{{ns['wp']}}}status", "publish")
title = item.findtext("title", "")
slug = item.findtext(f"{{{ns['wp']}}}post_name", "")
date_str = item.findtext(f"{{{ns['wp']}}}post_date", "")
date = date_str[:10] if date_str else ""
content_encoded = item.findtext(f"{{{ns['content']}}}encoded", "")
content = content_encoded.replace("\r\n", "\n")
excerpt = item.findtext(f"{{{ns['excerpt']}}}encoded", "")
categories = []
tags = []
for cat in item.findall("category"):
domain = cat.get("domain", "")
if domain == "category":
categories.append(cat.text or "")
elif domain == "post_tag":
tags.append(cat.text or "")
if not slug:
slug = re.sub(r'[^a-z0-9]+', '-', title.lower()).strip('-')
posts.append({
"title": title,
"slug": slug,
"date": date,
"category": ", ".join(categories) if categories else "",
"tags": ", ".join(tags) if tags else "",
"excerpt": excerpt or "",
"content": content,
"status": status,
})
posts.sort(key=lambda p: p.get("date", ""), reverse=True)
return posts