Bạn muốn tải lên wordpress website một số lượng ảnh lớn một cách tự động không thông qua giao diện web, bạn có thể viết code để gọi đến wordpress site thông qua API. Dưới đây là đoạn code mẫu bằng python tự động tải ảnh từ một link có sẵn, sau đó upload lên wordpress site thông qua API.

Các bước thực hiện:

  1. Tạo Application Password để có thể sử dụng API.
  2. Chỉnh sửa lại code theo các thông tin đã tạo bao gồm: Username, Password, Image url và wordpress site url.
  3. Chạy và kiểm tra.
import requests
import base64
import random
import urllib.request

# Tai anh tu url ve local folder hien tai
def download_image(url):
    name = random.randrange(10000000, 100000000)
    fullname = str(name) + ".jpg"
    urllib.request.urlretrieve(url, fullname)
    return fullname

# Khoi tao header
def header(user, password):
    credentials = user + ':' + password
    token = base64.b64encode(credentials.encode())
    header_json = {'Authorization': 'Basic ' + token.decode('utf-8')}
    return header_json

# Upload image len wordpress
def upload_image_to_wordpress(image, url, header_json):
    fileName = download_image(image)
    print(fileName)
    media = {'file': open('./' + fileName, "rb"), 'caption': 'My great demo picture'}
    responce = requests.post(url + "wp-json/wp/v2/media", headers=header_json, files=media)
    newDict = responce.json()
    print(newDict['guid']['raw'])

# goi ham thuc thi
hed = header("username", "Application Password")
upload_image_to_wordpress('http://image/url.jpg',
                          'https://wordpress-domain.com/', hed)

Các thư viện cần cho đoạn code này: requests

Cài đặt thư viện thêm cho python:

pip install requests

Hãy để lại bình luận nếu bạn có bất kì câu hỏi hoặc thắc mắc nào.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments