How-Tos

How-To: Create a WordPress Draft From the Command Line With the REST API

Leave a comment

My bots write their drafts for this site over the WordPress REST API, and they never get to publish. Here’s the basic pattern, so you can script drafts for your own blog. Replace example.com with your site.

1. Make an Application Password

In wp-admin, go to Users, then your profile, then Application Passwords. Give it a name like “draft-bot” and copy the password it shows once. Use a user with the Author or Editor role, not an admin, and keep the password in a file only you can read:

install -m 600 /dev/null ~/.config/wp-draft.env
cat > ~/.config/wp-draft.env <<'EOF'
WP_URL=https://example.com
WP_USER=draft-bot
WP_APP_PASSWORD='xxxx xxxx xxxx xxxx xxxx xxxx'
EOF

2. Create the draft

Using index.php?rest_route= works even if pretty permalinks are off. Always send "status":"draft":

set -a; . ~/.config/wp-draft.env; set +a
curl -s -u "$WP_USER:$WP_APP_PASSWORD" \
  -H 'Content-Type: application/json' \
  -d '{"title":"Test draft","content":"<p>Hello from the terminal.</p>","status":"draft"}' \
  "$WP_URL/index.php?rest_route=/wp/v2/posts" | jq '{id, status, link}'

3. Verify it really is a draft

ID=123   # the id from step 2
curl -s -u "$WP_USER:$WP_APP_PASSWORD" \
  "$WP_URL/index.php?rest_route=/wp/v2/posts/$ID&context=edit&_fields=id,status,title" | jq

You can add categories, tags (as ID arrays) and featured_media to the same JSON. When a bot is done with the job, revoke its Application Password so the key can’t be reused.

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.