WordPress更改資料庫

編寫 wordpress 文章時,若要連結到本站的某個圖片或是文章,有時會不小心把整個絕對網址都輸入,比如

<a href="http://mahaljsp.asuscomm.com/tiger.jpg">老虎</a>

其實 “http://mahaljsp.asuscomm.com” 是多餘的,因為只要輸入如下網址即可

<a href="/tiger.jpg">老虎</a>

為何要改連結

如果有上百篇文章,每章都有 http://mahaljsp.asuscomm.com/xxx.jpg。
然後某天需要變更網址為 http://mahaljsp.ddns.net 時,那~~~ wordpress 的所有文章就有得改了,每篇文章都需改一遍。

使用Python更改資料庫

本例說明如何使用Python更改文章的連結,wordpress發表的文章資料表為 wp_posts

import mysql.connector as mysql
conn=mysql.connect(host="ip", user="account", password="password", database="wordpress")
cursor=conn.cursor()
cmd="select id, post_content from wp_posts"
cursor.execute(cmd)
rs=cursor.fetchall()
for r in rs:
content=r[1]
if("http://mahaljsp.asuscomm.com/" in content):
s=content.replace("http://mahaljsp.asuscomm.com/","/")
s=s.replace("\\","\\\\").replace("'","\\'")
id=r[0]
print(f"============================={id}============================")
#print(s)
cmd=f"update wp_posts set post_content='{s}' where ID={id}"
print(cmd)
cursor.execute(cmd)
conn.commit()
print("==============================end=============================")

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *