You can automate publishing a post on WordPress using Python by using the WordPress REST API.
Here is a basic outline of how you could accomplish this:
- Enable the REST API in WordPress: WordPress has a REST API built in that you can use to interact with the site via Python. The REST API is enabled by default in WordPress 4.7 and later. You can check if it’s available by visiting
http://your-site-url/wp-json/
. - Authentication: To publish a post, you need to be authenticated. The most common way of doing this is through Basic Auth, which WordPress doesn’t support out of the box. You will need to install a plugin to enable it. There are multiple plugins available that provide this capability. One option is to use the Application Passwords plugin. After installation, generate a new application password for your user in the WordPress dashboard.
- Use Python to Publish a Post: Once you’ve set up the API and the authentication, you can use the Python
requests
library to send HTTP requests to the WordPress server. Here is a basic example of how to publish a new post:
import requests import json # The URL for the API endpoint url = 'http://your-site-url/wp-json/wp/v2/posts' # Your WordPress username username = 'your-username' # The application password you generated password = 'your-application-password' # The post data data = { 'title': 'My New Post', 'content': 'This is the content of my new post.', 'status': 'publish' # Use 'draft' to save the post as a draft } # Send the HTTP request response = requests.post(url, auth=(username, password), json=data) # Check the response if response.status_code == 201: print('Post created successfully') else: print('Failed to create post: ' + response.text)
Replace 'http://your-site-url'
, 'your-username'
, and 'your-application-password'
with your WordPress site URL, your WordPress username, and the application password you generated.
β‘ Warning: Basic Auth sends the username and password in clear text with each request, so you should only use it over HTTPS in a production environment. For a more secure method, you should look into using a more secure authentication method such as OAuth (see below).
How Can You Format the Post Content (e.g., Background Color, Bold, Italic, …)?
π‘ The WordPress REST API accepts content in HTML format. So you can add formatting to your content by using appropriate HTML tags.
For instance, to add an image you can use the <img>
tag, and to create a blue background for a paragraph you can use the <p>
tag with inline CSS. Here’s an example:
data = { 'title': 'My New Post', 'content': ''' This is a paragraph with no special formatting. <p style="background-color: blue; color: white;">This is a paragraph with a blue background and white text.</p> <img src="http://your-site-url/path-to-your-image.jpg" alt="My Image"> This is another paragraph with no special formatting. ''', 'status': 'publish' }
In the above example, replace 'http://your-site-url/path-to-your-image.jpg'
with the actual URL of the image you want to insert.
For more advanced formatting, you might want to use a page builder that supports more advanced layouts and then view the resulting HTML to see how it’s done.
π‘ Note: If you want to upload a new image through the API and use it in a post, that would require a separate API request to first upload the image, and then you can use the returned URL to insert the image into your post. The process of uploading images via the WordPress REST API is somewhat more complicated and beyond the scope of this question. You may want to refer to the WordPress REST API documentation for more details.
A Few Words on Safe Authentication π
The WordPress REST API supports OAuth authentication. To use OAuth, you first need to register an application in WordPress. The OAuth process is somewhat more complex than basic authentication, and it requires a plugin to enable it, such as the WordPress OAuth Server plugin.
Once you have registered your application and obtained your client ID and client secret, you can use a library like requests-oauthlib
to perform the OAuth flow and make authenticated requests to the WordPress REST API.
Here’s a simplified example:
from requests_oauthlib import OAuth1Session # Your WordPress site URL site_url = 'http://your-site-url' # Your client ID and client secret client_id = 'your-client-id' client_secret = 'your-client-secret' # Get a request token request_token_url = f'{site_url}/oauth1/request' oauth = OAuth1Session(client_id, client_secret=client_secret) fetch_response = oauth.fetch_request_token(request_token_url) resource_owner_key = fetch_response.get('oauth_token') resource_owner_secret = fetch_response.get('oauth_token_secret') # Redirect the user to the authorization URL base_authorization_url = f'{site_url}/oauth1/authorize' authorization_url = oauth.authorization_url(base_authorization_url) print('Please go to the following URL and authorize the app: ' + authorization_url) # The user will be redirected to a callback URL with a verifier in the query string verifier = input('Please input the oauth_verifier: ') # Get an access token access_token_url = f'{site_url}/oauth1/access' oauth = OAuth1Session(client_id, client_secret=client_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) oauth_tokens = oauth.fetch_access_token(access_token_url) # You can now use oauth to make requests to the API url = f'{site_url}/wp-json/wp/v2/posts' data = { 'title': 'My New Post', 'content': 'This is the content of my new post.', 'status': 'publish' } response = oauth.post(url, json=data)
In this code, replace 'http://your-site-url'
, 'your-client-id'
, and 'your-client-secret'
with your WordPress site URL, your client ID, and your client secret.
This code initiates the OAuth 1.0a three-legged flow.
- It first fetches a request token, then it prints an authorization URL for the user to visit and authorize the app.
- After the user has authorized the app, they will be redirected to a callback URL with an
oauth_verifier
in the query string. The user needs to copy this verifier and input it into the Python script. - The script then fetches an access token and uses it to make authenticated requests to the API.
Please note that this is a simplified example and might not cover all cases. For a complete OAuth flow, you would need to implement a callback URL to automatically receive the verifier and complete the flow without manual intervention. Also, you should handle errors and edge cases appropriately in your production code.
Also, this code uses OAuth 1.0a, as it’s supported by the WordPress OAuth Server plugin. Some plugins or installations may support OAuth 2.0, which has a slightly different flow. Please refer to the documentation of your specific OAuth server for more information.
If you’re not familiar with OAuth, it’s a complex protocol, and it might be worthwhile to read up on it before implementing it in your application. There are many resources available online, including the official OAuth guide.
Do you want to keep learning and improving your Python skills? Check out our free cheat sheets here: