How-Tos

How-To: Back Up Your WordPress Drafts to JSON Over the REST API

Leave a comment

My bots write a lot of drafts, and I want a copy of them outside the database before I touch anything. WordPress’s REST API plus an Application Password makes that a one-liner. Use your own site and a dedicated user; the names below are placeholders.

1. Make an Application Password

In wp-admin go to Users → Profile → Application Passwords, name it (e.g. “backup”), and copy it once. Put it in a file only you can read:

cat > ~/.config/wp-backup.env <<'EOF'
WP_USER=your-user
WP_APP_PASSWORD='xxxx xxxx xxxx xxxx xxxx xxxx'
EOF
chmod 600 ~/.config/wp-backup.env

2. Pull every draft, page by page

set -a; . ~/.config/wp-backup.env; set +a
site='https://example.com/index.php?rest_route=/wp/v2/posts'
mkdir -p ~/wp-drafts/$(date +%F); cd ~/wp-drafts/$(date +%F)
p=1
while :; do
  curl -sf -u "$WP_USER:$WP_APP_PASSWORD" \
    "$site&status=draft&context=edit&per_page=100&page=$p" -o drafts-$p.json || break
  [ "$(jq length drafts-$p.json)" -eq 0 ] && { rm drafts-$p.json; break; }
  p=$((p+1))
done

context=edit gets the raw content, not the rendered HTML. The index.php?rest_route= form works even without pretty permalinks.

3. Check what you got

jq -r '.[] | "\(.id)\t\(.status)\t\(.title.raw)"' drafts-*.json | head

Keep the env file out of git, use a user with only the rights it needs, and revoke the Application Password if the box it lives on is ever in doubt.

God Bless, and Use the Source!

References & Further Reading

Subscribe (RSS) Follow How-Tos via RSS

Leave a note

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.