首页 问答 正文

如何批量上传图片到wordpress媒体库?

注册会员 / 悠然自学 / 2023-07-11/ 浏览 160 次

批量上传图片到WordPress媒体库可以使用WordPress提供的REST API来实现。以下是一个示例代码,使用Python的requests库发送POST请求来上传图片到WordPress媒体库:

import requests

# WordPress站点的URL和认证信息
site_url = 'https://example.com/wp-json/wp/v2/'
username = 'your_username'
password = 'your_password'

# 获取认证令牌
auth_response = requests.post(site_url + 'jwt-auth/v1/token', json={'username': username, 'password': password})
auth_data = auth_response.json()
token = auth_data['token']

# 设置请求头包含认证令牌
headers = {
    'Authorization': 'Bearer ' + token
}

# 批量上传图片
image_files = ['image1.jpg', 'image2.jpg', 'image3.jpg']  # 替换为你的图片路径
for image_file in image_files:
    with open(image_file, 'rb') as file:
        image_data = file.read()
        files = {'file': (image_file, image_data, 'image/jpeg')}
        upload_response = requests.post(site_url + 'media', headers=headers, files=files)
        upload_data = upload_response.json()
        # 获取上传图片的URL
        image_url = upload_data['source_url']
        # 输出上传图片的URL
        print(f"上传成功: {image_url}") 

请替换示例代码中的site_urlusernamepassword为你的WordPress站点的URL和认证信息。同时,将image_files替换为你想要上传的图片文件路径列表。

以上代码使用了WordPress的JWT Authentication插件来实现认证。确保你的WordPress站点已安装并启用了这个插件。如果没有则需要先安装并进行相应配置。

注意:以上代码仅供参考,实际应用中可能需要根据自己的环境和需求进行修改和优化。

大家谈论
    我的见解