Search code examples
pythonwordpresswordpress-rest-api

Putting a picture in wordpress post with python


I want to make a post in wordpress that has a photo, but it gives an error

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
url = 'http://my_website.blog/xmlrpc.php'
username = 'MY_username'
password = 'MY_password'
def send_post(title,content,url_image):
client = Client(url, username, password)
post = WordPressPost()
post.title = title
post.content = content
post.post_status = 'publish'
post.slug = ''
post.thumbnail = url_image
client.call(NewPost(post))

Everything works fine, but the picture does not It gives me this error

xmlrpc.client.Fault: <Fault 404: '\u0634\u0646\u0627\u0633\u0647\u0654 
\u067e\u06cc\u0648\u0633\u062a \u0646\u0627\u0645\u0639\u062a\u0628\u0631 
 \u0627\u0633\u062a.'>

Solution

  • The problem is likely with the way you're setting the thumbnail. The post.thumbnail expects the ID of the attachment post, not a direct URL. To set a post's thumbnail, you'll first have to upload the image to WordPress and get the attachment ID.

    from wordpress_xmlrpc.methods.media import UploadFile
    from wordpress_xmlrpc import Client
    
    # Your credentials
    url = 'http://my_website.blog/xmlrpc.php'
    username = 'MY_username'
    password = 'MY_password'
    
    client = Client(url, username, password)
    
    # Define your image and its properties
    data = {
        'name': 'filename.jpg',
        'type': 'image/jpeg',  # mimetype
    }
    
    # Read the binary file and let the XMLRPC library encode it into base64
    with open('path_to_your_image.jpg', 'rb') as img:
        data['bits'] = img.read()
    
    response = client.call(UploadFile(data))
    attachment_id = response['id']
    

    Now that you have the attachment_id, you can use it as the thumbnail for your post

    from wordpress_xmlrpc import WordPressPost
    from wordpress_xmlrpc.methods.posts import NewPost
    
    def send_post(title, content, attachment_id):
        post = WordPressPost()
        post.title = title
        post.content = content
        post.post_status = 'publish'
        post.thumbnail = attachment_id
        post_id = client.call(NewPost(post))
    
    # Call the function
    send_post("Your Title", "Your Content", attachment_id)