On the previous tutorial, we learned about how to import content into a WordPress site. In this tutorial, I will explain how to import bulk images into a WordPress site.
I will also put a download link of a script with sample files so you can install and run it on your system.
Please go through part 1 on things that are required before using the API feature of WordPress.
Here’s the quick overview of requirements before we start.
- Basic – Auth Plugin: https://github.com/WP-API/Basic-Auth
- Python >= 3
- Administrator username and password of your WordPress site.
Libraries used for uploading images are,
import requests
import csv
import json
import os
import re
def upload_images(self):
"""upload files from local directory to the wordpress site
:returns: ids of uploaded images | list
"""
url = self.domain+"/wp-json/wp/v2/media/"
upload_file_ids = []
with os.scandir('images/') as d:
for entry in d:
if entry.is_file():
path = entry.path
filename = re.search('.*\/(.*?)\.(.*)', path)
if filename:
name = filename.group(1)
image_type = filename.group(2)
else:
return None
data = open(path, 'rb').read()
headers = dict()
headers['Content-Type'] = 'image/'+image_type
headers['Content-Disposition'] = 'attachment; filename=%s'% name+"."+image_type
response = self.request.post(url, data=data, headers=headers)
content = json.loads(response.text)
upload_file_ids.append(content['id'])
return upload_file_ids
This function loops through all the files in the images folder and uploads them into WordPress.
Download complete code with a sample image.
[download id=”69″]
Import bulk content into WordPress site with sample data and running python script.
One thought on “Importing bulk content into WordPress – part 2”