Auto-upload images to WordPress in python with caption, description, alt-text, etc.


Hello fellow Pythonians and beloved readers! Today we will automate your image uploads in WordPress! Did you ever wonder what people do who have to upload a big bunch of images to their WordPress page? They use the WordPress  uploader fine… BUT what do you do when you have a thousand tagged images with special descriptions, caption and data in tables? Auto-upload with Python to the rescue!

This post is based upon the code of the user smaffulli @ >> here. However I wanted a way to set the extra parameters of images. On this we can build on and automate the process of managing many images and parameters using simple excel files. (Followup post incoming!)

Auto-upload with the rest-Api

first of all we have to define an authentication token for the user we want to use to upload the images. For this you can use the light plugin: “Application Passwords” from >> here.

Just install the plugin as usual and go to your WordPress-Tab Users, pick the user you want to use for your application and scroll to Application Passwords.

if you see the following error message, don’t panic, there is a solution:

Due to a potential server misconfiguration, it seems that HTTP Basic Authorization may not work for the REST API on this site: `Authorization` headers are not being sent to WordPress by the web server. You can learn more about this problem, and a possible solution, on our GitHub Wiki.

Solution to the Error:

To fix the above problem just go into your .htaccess file and add the following line after the RewriteEngine On line:

RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

it should look similar to this now:

# BEGIN WordPress
 
 RewriteEngine On
 RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]


# END WordPress

The error massage should be gone after a reload of the User-Page.

this solution is cited from here: https://github.com/georgestephanis/application-passwords/wiki/Basic-Authorization-Header—-Missing

Continue with Application Passwords

We fixed the issues hopefully, continue by typing in an application name e.g. pythonapp and click Add New. Copy your Auth. Token you are not able to recover it!

Programming part

Now you are all set to continue with the code. We first set up our python environment. You will need just one package which you can install with pip in the windows cmd:

pip install requests
Now let us code the first part. We initialize the user and pythonapp authentication token. Keep in mind, that anyone who has the auth. token will be able to upload anything on your WordPress installation so be careful!

import requests
import json
import base64

user = 'theuserwiththeauthcode' # the user in which the auth. token is given
pythonapp = 'WWWW WWWW WWWW WWWW WWWW WWWW' # paste here your auth. token
url = 'http://www.mypage.com/wp-json/wp/v2' # the url of the wp access location
token = base64.standard_b64encode((user + ':' + pythonapp).encode('utf-8')) # we have to encode the usr and pw
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}

alright so we encoded and configured our authentication lets post something now:

media = {'file': open('picture.jpg','rb')} # 'picture.jpg' path to the image

image = requests.post(url + '/media', headers=headers, files=media)
link = json.loads(image.content.decode('utf-8'))['link']
postid =json.loads(image.content.decode('utf-8'))['id']
print('Your image is published on {} with ID {}'.format(link, postid))


In the variable postid we store the Post-ID of our uploaded media file. This Post-ID can be used now to add or change parameters of the image. The json structure of the post variable is now filled with the parameters we want to add or change. You can even use HTML in the caption:

post = {'caption': 'My great demo picture',
        'description': 'my great descrition'
        }
r = requests.post(url + '/media/'+str(postid), headers=headers, json=post)
print('Your image is updated on {} with ID {}'.format(link, postid))


Now that’s it, put this in a function and you can auto-upload anything from your command line! You are free to download the complete python file at my GitHub repository: https://github.com/timsamart/wp_upload_media

 

 

Leave a comment

Your email address will not be published. Required fields are marked *