Post to WordPress with One Click Using Python

未分類

If you write every day, opening the WordPress admin, creating a new post, entering a title and content can become tedious.
The good news is: with Python + the WordPress REST API, you can create a system that lets you post articles with a single click from your PC.

In this article, I’ll show you how to set it up so you can write your title and content in text files, then post them instantly.


1. Overview

  • WordPress has a built-in REST API for posting articles.
  • With Python, you can send a POST request to /wp-json/wp/v2/posts and create a post.
  • If you keep your title and content in text files, Python can automatically read them and send them as a new article.

The flow looks like this 👇

  1. Write your title in title_u8.txt
  2. Write your content in content_u8.html (HTML allowed)
  3. Double-click the “One-Click Post” shortcut
  4. Your article is instantly posted! ✅

2. Requirements

  • Python 3.10 or higher
  • Install the requests library: pip install requests
  • A WordPress Application Password
    (Go to Users → Profile → Application Passwords in your WP admin)

3. Folder Structure

Create a folder, for example C:\kijisakusei, with these files:

C:\kijisakusei
  ├ post_to_wp.py        ← Main Python script
  ├ .env                 ← Store your username & app password
  ├ title_u8.txt         ← Title (UTF-8 text)
  └ content_u8.html      ← Content (UTF-8, HTML supported)

4. The .env File

This file holds your WordPress account info:

WP_URL=https://your-site.com/wp-json/wp/v2/posts
WP_USER=your-username
WP_APP_PASSWORD=xxxx xxxx xxxx xxxx
CATEGORY_IDS=8
STATUS=draft
  • CATEGORY_IDS → target category ID (comma separated if multiple)
  • STATUSdraft, publish, private, etc.

5. The Python Script (post_to_wp.py)

Here’s the script that reads your files and posts them:

# -*- coding: utf-8 -*-
import json, os, sys
import requests
from requests.auth import HTTPBasicAuth

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def load_env(path):
    env = {}
    if os.path.exists(path):
        with open(path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                env[k.strip()] = v.strip()
    return env

def read_text(path):
    with open(path, "r", encoding="utf-8") as f:
        return f.read()

def main():
    env = load_env(os.path.join(BASE_DIR, ".env"))
    WP_URL  = env.get("WP_URL")
    WP_USER = env.get("WP_USER")
    WP_APP  = env.get("WP_APP_PASSWORD")
    STATUS  = env.get("STATUS", "draft")
    cats    = [int(x) for x in env.get("CATEGORY_IDS", "1").split(",")]

    title   = read_text(os.path.join(BASE_DIR, "title_u8.txt")).strip()
    content = read_text(os.path.join(BASE_DIR, "content_u8.html"))

    payload = {"title": title, "content": content, "status": STATUS, "categories": cats}

    res = requests.post(WP_URL, json=payload, auth=HTTPBasicAuth(WP_USER, WP_APP))
    print("HTTP Status:", res.status_code)
    try:
        data = res.json()
        print(json.dumps(data, ensure_ascii=False, indent=2))
        if res.status_code == 201:
            print("✅ Success:", data["link"])
    except Exception:
        print(res.text)

if __name__ == "__main__":
    main()

6. One-Click Execution

Create a batch file oneclick_post.bat in the same folder:

@echo off
chcp 65001 >nul
cd /d "%~dp0"

notepad title_u8.txt
notepad content_u8.html

python post_to_wp.py
pause

Then place a shortcut to this .bat file on your desktop.
Now, just double-click → edit your files → instant post.


7. Daily Workflow

  1. Write your title in title_u8.txt
  2. Write your article body in content_u8.html
  3. Double-click your desktop shortcut
  4. Python posts it to WordPress, and the console shows the post URL 🎉

✅ Conclusion

With this setup:

  • You don’t need to log into WordPress every morning
  • Posting becomes as easy as writing two text files and double-clicking an icon
  • It saves time and makes daily publishing smooth and efficient

👉 Now you’ve got a one-click posting system for WordPress with Python.


コメント