【问题标题】:Get the alt text of featured image wordpress rest api python获取特色图片 wordpress rest api python 的替代文本
【发布时间】:2022-08-24 16:58:42
【问题描述】:
我正在尝试使用 rest api 和 python 获取特色图像的替代文本。
这是我的代码:
media = {
\"file\": open(f\"images/{filename}\", \"rb\"),
\"caption\": \"caption\",
\"description\": \"description\",
\"alt_text\": \"Custom Alt Text\",
}
upload_image = requests.post(url + \"/media\", headers=headers, files=media)
一切正常,而不是替代文本。它保持空白。
任何人,如果我做错了什么或错过了什么,请帮助我?
谢谢
标签:
python-3.x
file-upload
wordpress-rest-api
alt
【解决方案1】:
当我看到您的代码时,我认为您想为图像设置alt_text。
如果要使用WordPress REST API 上传图片并为其设置alt_text,可以使用以下函数:
import requests
import os
from pathlib import Path
# WordPress authentication
WP_URL = 'xxxxxxxxx/wp-json/wp/v2'
WP_USERNAME = 'xxxxx'
WP_PASSWORD = 'xxxxxxxxxxxxxxx'
WP_CREDS = WP_USERNAME + ':' + WP_PASSWORD
WP_TOKEN = base64.b64encode(WP_CREDS.encode())
WP_HEADER = {"Authorization":"Basic " + WP_TOKEN.decode("utf-8")}
def img_upload(img_path, my_alt_text):
image_extension = Path(img_path).suffix
if image_extension != '.jpg':
img_path = img_path.replace(image_extension, '.jpg')
image_name = os.path.basename(img_path)
data = open(imgPath, 'rb').read()
img_header = { 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% image_name}
# Upload the image
image_json = requests.post(WP_URL + '/media/' , data=data, headers=img_header,
auth=(WP_USERNAME, WP_PASSWORD)).json()
# Update the uploaded image data
update_image = {'alt_text': my_alt_text}
updated_image_json = requests.post(WP_URL + '/media/' + str(image_json['id']),
headers=WP_HEADER, json=update_image).json()
return updated_image_json