1.wp_post最佳化
刪除不需要分類下文章
DELETE p FROM wp_posts p INNER JOIN wp_term_relationships tr ON p.ID = tr.object_id INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.term_id = 236
2.wp_term_relationships最佳化
刪除沒有文章引用的term
DELETE tr FROM wp_term_relationships tr LEFT JOIN wp_posts p ON tr.object_id = p.ID WHERE p.ID IS NULL;
3.檔案最佳化
查詢未被引用的附近
SELECT * FROM wp_posts WHERE post_type = 'attachment' AND ID NOT IN ( SELECT post_id FROM wp_postmeta WHERE meta_key IN ('_thumbnail_id', '_wp_attached_file') )
python刪除檔案指令碼(需要替換自己的資料庫連線資訊以及檔案上傳位置)
import os import pymysql import datetime def delete_unused_attachments(db_conn, upload_dir): """刪除未使用的 WordPress 附件 Args: db_conn: 資料庫連線物件 upload_dir: 上傳目錄 Returns: None """ cursor = db_conn.cursor() # 執行 SQL 查詢,獲取未使用的附件資訊 sql = """ SELECT ID, post_title, post_date FROM wp_posts WHERE post_type = 'attachment' AND ID NOT IN ( SELECT post_id FROM wp_postmeta WHERE meta_key IN ('_thumbnail_id', '_wp_attached_file') ) """ cursor.execute(sql) results = cursor.fetchall() for result in results: attachment_id = result[0] post_title = result[1] # 使用 post_title 作為檔名 post_date = result[2] # 直接獲取 post_date,假設是 datetime.datetime 物件 # 檢查 post_date 的型別並進行處理 if isinstance(post_date, datetime.datetime): # 如果是 datetime 物件,直接使用 year = post_date.year month = post_date.month elif isinstance(post_date, str): # 如果是字串,嘗試解析 try: post_date = datetime.datetime.strptime(post_date, '%Y-%m-%d %H:%M:%S') # 調整格式字串 year = post_date.year month = post_date.month except ValueError: print(f"日期格式錯誤: {post_date}") continue else: print(f"不支援的資料型別: {type(post_date)}") continue # 將年份和月份格式化為雙數格式 year_str = str(year) month_str = f"{month:02d}" # 將月份格式化為雙數格式 # 構建完整檔名,直接使用 post_title file_name = post_title # 不再新增副檔名 # 構建完整路徑 full_path = os.path.join(upload_dir, year_str, month_str, file_name) print(f"full_path: {full_path}") # 刪除檔案 if os.path.exists(full_path): try: os.remove(full_path) # 刪除資料庫記錄 (根據實際情況調整) # ... print(f"已刪除附件 ID: {attachment_id}, 檔案: {full_path}") except OSError as e: print(f"刪除檔案失敗: {e}") else: print(f"檔案 {full_path} 不存在") # 連線到資料庫 db = pymysql.connect( host='xxxxx', user='xxx', password='xxxx', database='xxxx' ) # 設定上傳目錄 upload_dir = "/alidata2/html/wordpress/wp-content/uploads" # 呼叫函式刪除附件 delete_unused_attachments(db, upload_dir) # 關閉資料庫連線 db.close()
安裝python3
yum install Python3
執行Python3指令碼
python3 delete_unuse_file.py
刪除成功後,刪除資料庫記錄
delete FROM wp_posts WHERE post_type = 'attachment' AND ID NOT IN ( SELECT post_id FROM wp_postmeta WHERE meta_key IN ('_thumbnail_id', '_wp_attached_file') )
刪除關係關係
DELETE tr FROM wp_term_relationships tr LEFT JOIN wp_posts p ON tr.object_id = p.ID WHERE p.ID IS NULL;