# WordPress Automated Content Uploader

This utility automates the process of uploading content to a self-hosted WordPress website. It reads text files from a specified directory, treats the first line as the title and the rest as the body, and uploads them as **Drafts** via the WordPress REST API. It supports uploading as either blog **posts** or static **pages**.

**Modules Used:**
*   [[programming/python/modules/requests-module|requests]]: To interact with the WordPress REST API.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.
*   `os`: To navigate the file system.

## Prerequisites

1.  **WordPress Site**: A self-hosted WordPress site (version 4.7+).
2.  **Application Password**:
    *   Go to your WordPress Dashboard -> **Users** -> **Profile**.
    *   Scroll down to **Application Passwords**.
    *   Enter a name (e.g., "Python Uploader") and click **Add New Application Password**.
    *   Copy the generated password. **Do not use your login password.**

## Installation

```bash
pip install requests
```

## The Code

Save this as `wp_uploader.py`.

```python
import requests
import os
import argparse
import sys

def upload_to_wordpress(folder, site_url, username, app_password, post_type="posts"):
    # 1. Construct API Endpoint
    # Ensure site_url is clean and append the API path
    api_base = site_url.rstrip('/')
    if "/wp-json" not in api_base:
        api_base += "/wp-json/wp/v2"
    
    endpoint = f"{api_base}/{post_type}"

    # 2. Scan Folder
    if not os.path.exists(folder):
        print(f"Error: Folder '{folder}' not found.")
        return

    files = [f for f in os.listdir(folder) if f.endswith('.txt')]
    if not files:
        print("No .txt files found in the directory.")
        return

    print(f"Found {len(files)} files. Uploading to {endpoint}...")

    # 3. Process and Upload
    for filename in files:
        filepath = os.path.join(folder, filename)
        
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                
            if not lines:
                print(f"Skipping empty file: {filename}")
                continue

            # Assumption: First line is Title, rest is Content
            title = lines[0].strip()
            content = "".join(lines[1:])

            post_data = {
                'title': title,
                'content': content,
                'status': 'draft'  # Upload as draft for safety
            }

            print(f"Uploading '{title}'...")
            
            # Basic Auth using Application Password
            response = requests.post(endpoint, auth=(username, app_password), json=post_data)

            if response.status_code == 201:
                print(f"  [Success] ID: {response.json().get('id')}")
            else:
                print(f"  [Failed] {response.status_code} - {response.text}")

        except Exception as e:
            print(f"Error processing {filename}: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="WordPress Bulk Content Uploader")
    parser.add_argument("folder", help="Folder containing .txt files")
    parser.add_argument("--url", required=True, help="WordPress Site URL (e.g., https://mysite.com)")
    parser.add_argument("--user", required=True, help="WordPress Username")
    parser.add_argument("--password", required=True, help="Application Password")
    parser.add_argument("--type", default="posts", choices=['posts', 'pages'], help="Upload type (default: posts)")

    args = parser.parse_args()

    upload_to_wordpress(args.folder, args.url, args.user, args.password, args.type)
```

## Usage

1.  **Prepare Content**: Create a folder (e.g., `articles`) and add `.txt` files.
    *   **Format**: The first line of the text file will be the **Title**. Everything else will be the **Body**.

2.  **Run the Script**:

    ```bash
    # Upload as Blog Posts (Drafts)
    python wp_uploader.py ./articles --url https://example.com --user myusername --password "abcd 1234 efgh 5678"

    # Upload as Pages
    python wp_uploader.py ./pages --url https://example.com --user myusername --password "..." --type pages
    ```

[[programming/python/python]]