Every post here ends with a References section, and a dead link there is embarrassing. Here’s the small check I use before anything goes live. It pulls a draft over the WordPress REST API with an application password and requests every link in it.
What you need
- A WordPress application password (Users > Profile > Application Passwords). Keep it in an env file readable only by you, never in the script.
- Python 3 with
requests.
The script
import os, re, sys, requests
site = os.environ["WP_SITE"] # e.g. https://example.com
auth = (os.environ["WP_USER"], os.environ["WP_APP_PASSWORD"])
pid = sys.argv[1]
p = requests.get(f"{site}/index.php?rest_route=/wp/v2/posts/{pid}",
params={"context": "edit"}, auth=auth, timeout=60).json()
links = set(re.findall(r'href="([^"]+)"', p["content"]["raw"]))
bad = []
for u in sorted(links):
try:
c = requests.get(u, timeout=30, allow_redirects=True,
headers={"User-Agent": "Mozilla/5.0"}).status_code
except Exception as e:
c = type(e).__name__
if c != 200:
bad.append((u, c))
print("BAD:", bad or "none")
Notes
context=editreturns the raw content, which only authenticated users can get, so it also works on drafts.- The
index.php?rest_route=form works even if pretty permalinks are off. - Some sites block scripts with a 403. Check those by hand in a browser before you swap the link.
- Run it with
set -a; . ~/.config/wp.env; set +a; python3 check.py 123.
God Bless, and Happy hacking!