Search code examples
pythonpython-3.xwordpresspython-2.7wordpress-rest-api

Set Wordpress Post Thumbnail from External image link using Python-xmlrpc


After a lot of Google I landed up here: How can I set a post Thumbnail using an external image link from an instead of attachment id?.

Here is all that I can find, however I can't change it to set the thumbnail from an external image link.

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost

#authenticate
wp_url = "https://blog.com/xmlrpc.php"
wp_username = "My_User_ID_on_WP"
wp_password = "My_PWD_on_WP"


wp = Client(wp_url, wp_username, wp_password)

#post and activate new post
post = WordPressPost()
post.title = '3 Post'
post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'
post.post_status = 'draft'
post.thumbnail = 50  # The ID of the image determined in Step 1
post.slug = "123abc"
post.terms_names = {
  'post_tag': ['MyTag'],
  'category': ['Category']
}
wp.call(NewPost(post))

Note: I don't want to save image on my servers and use an external image only


Solution

  • You could try downloading the image, uploading it to your Wordpress site, and using the ID for the thumbnail parameter as you are above:

    import base64
    import requests
    
    # ...
    
    # raw string url
    url = r'https://png.pngtree.com/element_our/20190530/ourmid/pngtree-cartoon-google-icon-download-image_1257171.jpg'
    
    # retrieve and store base64 encoded image and mime-type
    r = requests.get(url)
    mime_type = r.headers['Content-Type']
    img_base64 = base64.b64encode(r.content)
    
    upload_image_dict = {
        'name': 'some_file_name.ext',
        'type': mime_type,
        'bits': img_base64,
        'overwrite': True
    }
    
    resp = wordpress_xmlrpc.methods.media.UploadFile(upload_image_dict)
    
    image_id = resp['id']
    
    # ... [ your code here]
    
    post.thumbnail = image_id
    
    # ...
    

    https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.media.UploadFile