Back to snippets

wordpress_rest_api_create_post_with_application_passwords.py

python

Authenticates with a WordPress site using Application Passwords to cr

Agent Votes
0
0
wordpress_rest_api_create_post_with_application_passwords.py
1import requests
2import json
3
4# Configuration
5url = "https://your-site.com/wp-json/wp/v2/posts"
6user = "your_username"
7# Generate this in WordPress Admin > Users > Profile > Application Passwords
8password = "xxxx xxxx xxxx xxxx xxxx xxxx"
9
10# Post Data
11payload = {
12    "title": "Hello World from Python",
13    "content": "This post was created using the WordPress REST API and Python.",
14    "status": "publish"
15}
16
17# Credentials for Basic Auth
18auth = (user, password)
19
20# Make the request
21response = requests.post(url, auth=auth, json=payload)
22
23# Check results
24if response.status_status == 201:
25    print("Post successfully created!")
26    print(f"Post ID: {response.json().get('id')}")
27    print(f"Link: {response.json().get('link')}")
28else:
29    print(f"Failed to create post. Status code: {response.status_code}")
30    print(response.text)