Skip to content

Instantly share code, notes, and snippets.

@AtsushiA
Last active April 1, 2026 01:58
Show Gist options
  • Select an option

  • Save AtsushiA/a7fb2f8c3af808cb1d62e33433d0fde2 to your computer and use it in GitHub Desktop.

Select an option

Save AtsushiA/a7fb2f8c3af808cb1d62e33433d0fde2 to your computer and use it in GitHub Desktop.
make_redirect.py

make_redirect.py

WordPress の Redirection プラグイン 向けリダイレクトCSVを生成するスクリプトです。

概要

旧サイトと新サイトの投稿一覧CSVを比較し、記事タイトルをキーにマッチングして、旧URLから新URLへの301リダイレクトリストを出力します。

必要環境

  • Python 3.x(標準ライブラリのみ使用。追加インストール不要)

使い方

python make_redirect.py -old=old.csv -new=new.csv -o=redirect.csv
引数 説明
-old 旧サイトの投稿一覧CSV
-new 新サイトの投稿一覧CSV
-o 出力先ファイルパス

入力CSVのフォーマット

-old-new には以下の列を含むCSVを指定してください。

列名 説明
post_id 投稿のID
post_title 投稿のタイトル

BOM付きUTF-8(utf-8-sig)にも対応しています。

post_id,post_title
123,サンプル記事タイトル
456,別の記事

出力CSVのフォーマット

Redirection プラグインのインポート形式に対応したCSVを出力します。

列名
source /news/{旧ID}/
target /news/{新ID}/
regex 0
code 301
type url
hits 0
title (空)
status active

動作の流れ

  1. 旧・新CSVをそれぞれ読み込み、post_title をキーにした辞書を作成
  2. 旧CSVの各タイトルを新CSVと照合
  3. タイトルが一致した投稿を /news/{旧ID}//news/{新ID}/ のリダイレクトとして出力
  4. 一致しなかった投稿はターミナルに警告として表示(出力CSVには含まれない)

実行例

✅ マッチ: 42 件 → redirect.csv
⚠️  未マッチ: 3 件
   ID:789 / 削除された記事タイトル
   ...

Redirection プラグインへのインポート方法

  1. WordPress 管理画面 → ツールRedirection
  2. 上部メニューの インポート/エクスポート を開く
  3. 出力された redirect.csv をアップロードしてインポート
#!/usr/bin/env python3
"""
リダイレクトCSV生成スクリプト
Usage: python make_redirect.py -old=old.csv -new=new.csv -o=redirect.csv
"""
import csv
import sys
import os
def parse_args(args):
params = {}
for arg in args[1:]:
if '=' in arg:
key, value = arg.split('=', 1)
params[key.lstrip('-')] = value
return params
def load_csv(filepath):
posts = {}
with open(filepath, encoding='utf-8-sig', newline='') as f:
for row in csv.DictReader(f):
title = row['post_title'].strip()
post_id = row['post_id'].strip()
posts[title] = post_id
return posts
def main():
params = parse_args(sys.argv)
# 引数チェック
for required in ('old', 'new', 'o'):
if required not in params:
print(f"Error: -{required}= が指定されていません")
print("Usage: python make_redirect.py -old=old.csv -new=new.csv -o=redirect.csv")
sys.exit(1)
old_file = params['old']
new_file = params['new']
out_file = params['o']
# ファイル存在チェック
for f in (old_file, new_file):
if not os.path.exists(f):
print(f"Error: ファイルが見つかりません: {f}")
sys.exit(1)
# CSV読み込み
old_posts = load_csv(old_file)
new_posts = load_csv(new_file)
# マッチング
matched = []
unmatched = []
for title, old_id in old_posts.items():
if title in new_posts:
matched.append((old_id, new_posts[title], title))
else:
unmatched.append((old_id, title))
# 出力
with open(out_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['source', 'target', 'regex', 'code', 'type', 'hits', 'title', 'status'])
for old_id, new_id, title in matched:
writer.writerow([f'/news/{old_id}/', f'/news/{new_id}/', 0, 301, 'url', 0, '', 'active'])
print(f"✅ マッチ: {len(matched)} 件 → {out_file}")
if unmatched:
print(f"⚠️ 未マッチ: {len(unmatched)} 件")
for old_id, title in unmatched:
print(f" ID:{old_id} / {title}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment