简体   繁体   中英

Get the alt text of featured image wordpress rest api python

I am trying to get alt text of featured image using rest api and python.

Here is my code:

 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)

Everything works fine instead of alt text. It keeps blank.

Anyone, please help me if I did anything wrong or missed something?

Thanks

As I saw your code, I think you want to set alt_text for the image.

If you want to upload an image by using WordPress REST API and set an alt_text for it, you can use the following function:

import os
import base64
import requests
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM